This commit is contained in:
bradwilson 2012-07-02 11:17:06 -07:00
Родитель c1bf28fb35
Коммит 372fb8888f
61 изменённых файлов: 8 добавлений и 18377 удалений

Просмотреть файл

@ -53,18 +53,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Web.Http", "src\Syst
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Web.Http.Test", "test\System.Web.Http.Test\System.Web.Http.Test.csproj", "{7F2C796F-43B2-4F8F-ABFF-A154EC8AAFA1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Json", "src\System.Json\System.Json.csproj", "{F0441BE9-BDC0-4629-BE5A-8765FFAA2481}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Net.Http.Formatting", "src\System.Net.Http.Formatting\System.Net.Http.Formatting.csproj", "{668E9021-CE84-49D9-98FB-DF125A9FCDB0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.TestCommon", "test\Microsoft.TestCommon\Microsoft.TestCommon.csproj", "{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Json.Test.Unit", "test\System.Json.Test.Unit\System.Json.Test.Unit.csproj", "{EB09CD33-992B-4A31-AB95-8673BA90F1CD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Net.Http.Formatting.Test.Unit", "test\System.Net.Http.Formatting.Test.Unit\System.Net.Http.Formatting.Test.Unit.csproj", "{7AF77741-9158-4D5F-8782-8F21FADF025F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Json.Test.Integration", "test\System.Json.Test.Integration\System.Json.Test.Integration.csproj", "{A7B1264E-BCE5-42A8-8B5E-001A5360B128}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Net.Http.Formatting.Test.Integration", "test\System.Net.Http.Formatting.Test.Integration\System.Net.Http.Formatting.Test.Integration.csproj", "{6C18CC83-1E4C-42D2-B93E-55D6C363850C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Web.Http.SelfHost", "src\System.Web.Http.SelfHost\System.Web.Http.SelfHost.csproj", "{66492E69-CE4C-4FB1-9B1F-88DEE09D06F1}"
@ -200,10 +194,6 @@ Global
{7F2C796F-43B2-4F8F-ABFF-A154EC8AAFA1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7F2C796F-43B2-4F8F-ABFF-A154EC8AAFA1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7F2C796F-43B2-4F8F-ABFF-A154EC8AAFA1}.Release|Any CPU.Build.0 = Release|Any CPU
{F0441BE9-BDC0-4629-BE5A-8765FFAA2481}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F0441BE9-BDC0-4629-BE5A-8765FFAA2481}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F0441BE9-BDC0-4629-BE5A-8765FFAA2481}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F0441BE9-BDC0-4629-BE5A-8765FFAA2481}.Release|Any CPU.Build.0 = Release|Any CPU
{668E9021-CE84-49D9-98FB-DF125A9FCDB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{668E9021-CE84-49D9-98FB-DF125A9FCDB0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{668E9021-CE84-49D9-98FB-DF125A9FCDB0}.Release|Any CPU.ActiveCfg = Release|Any CPU
@ -212,18 +202,10 @@ Global
{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}.Release|Any CPU.Build.0 = Release|Any CPU
{EB09CD33-992B-4A31-AB95-8673BA90F1CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EB09CD33-992B-4A31-AB95-8673BA90F1CD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EB09CD33-992B-4A31-AB95-8673BA90F1CD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EB09CD33-992B-4A31-AB95-8673BA90F1CD}.Release|Any CPU.Build.0 = Release|Any CPU
{7AF77741-9158-4D5F-8782-8F21FADF025F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7AF77741-9158-4D5F-8782-8F21FADF025F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7AF77741-9158-4D5F-8782-8F21FADF025F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7AF77741-9158-4D5F-8782-8F21FADF025F}.Release|Any CPU.Build.0 = Release|Any CPU
{A7B1264E-BCE5-42A8-8B5E-001A5360B128}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A7B1264E-BCE5-42A8-8B5E-001A5360B128}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A7B1264E-BCE5-42A8-8B5E-001A5360B128}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A7B1264E-BCE5-42A8-8B5E-001A5360B128}.Release|Any CPU.Build.0 = Release|Any CPU
{6C18CC83-1E4C-42D2-B93E-55D6C363850C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6C18CC83-1E4C-42D2-B93E-55D6C363850C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6C18CC83-1E4C-42D2-B93E-55D6C363850C}.Release|Any CPU.ActiveCfg = Release|Any CPU
@ -297,7 +279,6 @@ Global
{3D3FFD8A-624D-4E9B-954B-E1C105507975} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}
{D3CF7430-6DA4-42B0-BD90-CA39D16687B2} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}
{DDC1CE0C-486E-4E35-BB3B-EAB61F8F9440} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}
{F0441BE9-BDC0-4629-BE5A-8765FFAA2481} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}
{668E9021-CE84-49D9-98FB-DF125A9FCDB0} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}
{66492E69-CE4C-4FB1-9B1F-88DEE09D06F1} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}
{A0187BC2-8325-4BB2-8697-7F955CF4173E} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}
@ -319,9 +300,7 @@ Global
{6C28DA70-60F1-4442-967F-591BF3962EC5} = {C40883CD-366D-4534-8B58-3EA0D13136DF}
{7F2C796F-43B2-4F8F-ABFF-A154EC8AAFA1} = {C40883CD-366D-4534-8B58-3EA0D13136DF}
{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0} = {C40883CD-366D-4534-8B58-3EA0D13136DF}
{EB09CD33-992B-4A31-AB95-8673BA90F1CD} = {C40883CD-366D-4534-8B58-3EA0D13136DF}
{7AF77741-9158-4D5F-8782-8F21FADF025F} = {C40883CD-366D-4534-8B58-3EA0D13136DF}
{A7B1264E-BCE5-42A8-8B5E-001A5360B128} = {C40883CD-366D-4534-8B58-3EA0D13136DF}
{6C18CC83-1E4C-42D2-B93E-55D6C363850C} = {C40883CD-366D-4534-8B58-3EA0D13136DF}
{81876811-6C36-492A-9609-F0E85990FBC9} = {C40883CD-366D-4534-8B58-3EA0D13136DF}
{F6C0671C-B832-4807-BA9A-9206BD35A650} = {C40883CD-366D-4534-8B58-3EA0D13136DF}

Просмотреть файл

@ -1,382 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic;
using System.IO;
using System.Json;
using System.Linq.Expressions;
namespace System.Runtime.Serialization.Json
{
/// <summary>
/// This class extends the functionality of the <see cref="JsonValue"/> type.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class JsonValueExtensions
{
/// <summary>
/// Creates a <see cref="System.Json.JsonValue"/> object based on an arbitrary CLR object.
/// </summary>
/// <param name="value">The object to be converted to <see cref="System.Json.JsonValue"/>.</param>
/// <returns>The <see cref="System.Json.JsonValue"/> which represents the given object.</returns>
/// <remarks>The conversion is done through the <see cref="System.Runtime.Serialization.Json.DataContractJsonSerializer"/>;
/// the object is first serialized into JSON using the serializer, then parsed into a <see cref="System.Json.JsonValue"/>
/// object.</remarks>
public static JsonValue CreateFrom(object value)
{
JsonValue jsonValue = null;
if (value != null)
{
jsonValue = value as JsonValue;
if (jsonValue == null)
{
jsonValue = JsonValueExtensions.CreatePrimitive(value);
if (jsonValue == null)
{
jsonValue = JsonValueExtensions.CreateFromDynamic(value);
if (jsonValue == null)
{
jsonValue = JsonValueExtensions.CreateFromComplex(value);
}
}
}
}
return jsonValue;
}
/// <summary>
/// Attempts to convert this <see cref="System.Json.JsonValue"/> instance into the type T.
/// </summary>
/// <typeparam name="T">The type to which the conversion is being performed.</typeparam>
/// <param name="jsonValue">The <see cref="JsonValue"/> instance this method extension is to be applied to.</param>
/// <param name="valueOfT">An instance of T initialized with this instance, or the default
/// value of T, if the conversion cannot be performed.</param>
/// <returns>true if this <see cref="System.Json.JsonValue"/> instance can be read as type T; otherwise, false.</returns>
public static bool TryReadAsType<T>(this JsonValue jsonValue, out T valueOfT)
{
if (jsonValue == null)
{
throw new ArgumentNullException("jsonValue");
}
object value;
if (JsonValueExtensions.TryReadAsType(jsonValue, typeof(T), out value))
{
valueOfT = (T)value;
return true;
}
valueOfT = default(T);
return false;
}
/// <summary>
/// Attempts to convert this <see cref="System.Json.JsonValue"/> instance into the type T.
/// </summary>
/// <typeparam name="T">The type to which the conversion is being performed.</typeparam>
/// <param name="jsonValue">The <see cref="JsonValue"/> instance this method extension is to be applied to.</param>
/// <returns>An instance of T initialized with the <see cref="System.Json.JsonValue"/> value
/// specified if the conversion.</returns>
/// <exception cref="System.NotSupportedException">If this <see cref="System.Json.JsonValue"/> value cannot be
/// converted into the type T.</exception>
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter",
Justification = "The generic parameter is used to specify the output type")]
public static T ReadAsType<T>(this JsonValue jsonValue)
{
if (jsonValue == null)
{
throw new ArgumentNullException("jsonValue");
}
return (T)JsonValueExtensions.ReadAsType(jsonValue, typeof(T));
}
/// <summary>
/// Attempts to convert this <see cref="System.Json.JsonValue"/> instance into the type T, returning a fallback value
/// if the conversion fails.
/// </summary>
/// <typeparam name="T">The type to which the conversion is being performed.</typeparam>
/// <param name="jsonValue">The <see cref="JsonValue"/> instance this method extension is to be applied to.</param>
/// <param name="fallback">A fallback value to be retuned in case the conversion cannot be performed.</param>
/// <returns>An instance of T initialized with the <see cref="System.Json.JsonValue"/> value
/// specified if the conversion succeeds or the specified fallback value if it fails.</returns>
public static T ReadAsType<T>(this JsonValue jsonValue, T fallback)
{
if (jsonValue == null)
{
throw new ArgumentNullException("jsonValue");
}
T outVal;
if (JsonValueExtensions.TryReadAsType<T>(jsonValue, out outVal))
{
return outVal;
}
return fallback;
}
/// <summary>
/// Attempts to convert this <see cref="System.Json.JsonValue"/> instance into an instance of the specified type.
/// </summary>
/// <param name="jsonValue">The <see cref="JsonValue"/> instance this method extension is to be applied to.</param>
/// <param name="type">The type to which the conversion is being performed.</param>
/// <returns>An object instance initialized with the <see cref="System.Json.JsonValue"/> value
/// specified if the conversion.</returns>
/// <exception cref="System.NotSupportedException">If this <see cref="System.Json.JsonValue"/> value cannot be
/// converted into the type T.</exception>
public static object ReadAsType(this JsonValue jsonValue, Type type)
{
if (jsonValue == null)
{
throw new ArgumentNullException("jsonValue");
}
if (type == null)
{
throw new ArgumentNullException("type");
}
object result;
if (JsonValueExtensions.TryReadAsType(jsonValue, type, out result))
{
return result;
}
throw new NotSupportedException(RS.Format(System.Json.Properties.Resources.CannotReadAsType, jsonValue.GetType().FullName, type.FullName));
}
/// <summary>
/// Attempts to convert this <see cref="System.Json.JsonValue"/> instance into an instance of the specified type.
/// </summary>
/// <param name="jsonValue">The <see cref="JsonValue"/> instance this method extension is to be applied to.</param>
/// <param name="type">The type to which the conversion is being performed.</param>
/// <param name="value">An object to be initialized with this instance or null if the conversion cannot be performed.</param>
/// <returns>true if this <see cref="System.Json.JsonValue"/> instance can be read as the specified type; otherwise, false.</returns>
[SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate",
Justification = "This is the non-generic version of the method.")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exception translates to fail.")]
public static bool TryReadAsType(this JsonValue jsonValue, Type type, out object value)
{
if (jsonValue == null)
{
throw new ArgumentNullException("jsonValue");
}
if (type == null)
{
throw new ArgumentNullException("type");
}
if (type == typeof(JsonValue) || type == typeof(object))
{
value = jsonValue;
return true;
}
if (type == typeof(object[]) || type == typeof(Dictionary<string, object>))
{
if (!JsonValueExtensions.CanConvertToClrCollection(jsonValue, type))
{
value = null;
return false;
}
}
if (jsonValue.TryReadAs(type, out value))
{
return true;
}
try
{
using (MemoryStream ms = new MemoryStream())
{
jsonValue.Save(ms);
ms.Position = 0;
DataContractJsonSerializer dcjs = new DataContractJsonSerializer(type);
value = dcjs.ReadObject(ms);
}
return true;
}
catch (Exception)
{
value = null;
return false;
}
}
/// <summary>
/// Determines whether the specified <see cref="JsonValue"/> instance can be converted to the specified collection <see cref="Type"/>.
/// </summary>
/// <param name="jsonValue">The instance to be converted.</param>
/// <param name="collectionType">The collection type to convert the instance to.</param>
/// <returns>true if the instance can be converted, false otherwise</returns>
private static bool CanConvertToClrCollection(JsonValue jsonValue, Type collectionType)
{
if (jsonValue != null)
{
return (jsonValue.JsonType == JsonType.Object && collectionType == typeof(Dictionary<string, object>)) ||
(jsonValue.JsonType == JsonType.Array && collectionType == typeof(object[]));
}
return false;
}
private static JsonValue CreatePrimitive(object value)
{
JsonPrimitive jsonPrimitive;
if (JsonPrimitive.TryCreate(value, out jsonPrimitive))
{
return jsonPrimitive;
}
return null;
}
private static JsonValue CreateFromComplex(object value)
{
DataContractJsonSerializer dcjs = new DataContractJsonSerializer(value.GetType());
using (MemoryStream ms = new MemoryStream())
{
dcjs.WriteObject(ms, value);
ms.Position = 0;
return JsonValue.Load(ms);
}
}
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "value is not the same")]
private static JsonValue CreateFromDynamic(object value)
{
JsonObject parent = null;
DynamicObject dynObj = value as DynamicObject;
if (dynObj != null)
{
parent = new JsonObject();
Stack<CreateFromTypeStackInfo> infoStack = new Stack<CreateFromTypeStackInfo>();
IEnumerator<string> keys = null;
do
{
if (keys == null)
{
keys = dynObj.GetDynamicMemberNames().GetEnumerator();
}
while (keys.MoveNext())
{
JsonValue child = null;
string key = keys.Current;
SimpleGetMemberBinder binder = new SimpleGetMemberBinder(key);
if (dynObj.TryGetMember(binder, out value))
{
DynamicObject childDynObj = value as DynamicObject;
if (childDynObj != null)
{
child = new JsonObject();
parent.Add(key, child);
infoStack.Push(new CreateFromTypeStackInfo(parent, dynObj, keys));
parent = child as JsonObject;
dynObj = childDynObj;
keys = null;
break;
}
else
{
if (value != null)
{
child = value as JsonValue;
if (child == null)
{
child = JsonValueExtensions.CreatePrimitive(value);
if (child == null)
{
child = JsonValueExtensions.CreateFromComplex(value);
}
}
}
parent.Add(key, child);
}
}
}
if (infoStack.Count > 0 && keys != null)
{
CreateFromTypeStackInfo info = infoStack.Pop();
parent = info.JsonObject;
dynObj = info.DynamicObject;
keys = info.Keys;
}
}
while (infoStack.Count > 0);
}
return parent;
}
private class CreateFromTypeStackInfo
{
public CreateFromTypeStackInfo(JsonObject jsonObject, DynamicObject dynamicObject, IEnumerator<string> keyEnumerator)
{
JsonObject = jsonObject;
DynamicObject = dynamicObject;
Keys = keyEnumerator;
}
/// <summary>
/// Gets of sets
/// </summary>
public JsonObject JsonObject { get; set; }
/// <summary>
/// Gets of sets
/// </summary>
public DynamicObject DynamicObject { get; set; }
/// <summary>
/// Gets of sets
/// </summary>
public IEnumerator<string> Keys { get; set; }
}
private class SimpleGetMemberBinder : GetMemberBinder
{
public SimpleGetMemberBinder(string name)
: base(name, false)
{
}
public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
{
if (target != null && errorSuggestion == null)
{
string exceptionMessage = RS.Format(System.Json.Properties.Resources.DynamicPropertyNotDefined, target.LimitType, Name);
Expression throwExpression = Expression.Throw(Expression.Constant(new InvalidOperationException(exceptionMessage)), typeof(object));
errorSuggestion = new DynamicMetaObject(throwExpression, target.Restrictions);
}
return errorSuggestion;
}
}
}
}

Просмотреть файл

@ -1,6 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Microsoft.Design", "CA2210:AssembliesShouldHaveValidStrongNames", Justification = "These assemblies are delay-signed.")]
[assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Justification = "Classes are grouped logically for user clarity.", Scope = "namespace", Target = "System.Runtime.Serialization.Json")]

Просмотреть файл

@ -1,304 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Xml;
namespace System.Json
{
internal static class JXmlToJsonValueConverter
{
internal const string RootElementName = "root";
internal const string ItemElementName = "item";
internal const string TypeAttributeName = "type";
internal const string ArrayAttributeValue = "array";
internal const string BooleanAttributeValue = "boolean";
internal const string NullAttributeValue = "null";
internal const string NumberAttributeValue = "number";
internal const string ObjectAttributeValue = "object";
internal const string StringAttributeValue = "string";
private const string TypeHintAttributeName = "__type";
private static readonly char[] _floatingPointChars = new char[] { '.', 'e', 'E' };
public static JsonValue JXMLToJsonValue(Stream jsonStream)
{
if (jsonStream == null)
{
throw new ArgumentNullException("jsonStream");
}
return JXMLToJsonValue(jsonStream, null);
}
public static JsonValue JXMLToJsonValue(string jsonString)
{
if (jsonString == null)
{
throw new ArgumentNullException("jsonString");
}
if (jsonString.Length == 0)
{
throw new ArgumentException(Properties.Resources.JsonStringCannotBeEmpty, "jsonString");
}
byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonString);
return JXMLToJsonValue(null, jsonBytes);
}
public static JsonValue JXMLToJsonValue(XmlDictionaryReader jsonReader)
{
if (jsonReader == null)
{
throw new ArgumentNullException("jsonReader");
}
const string RootObjectName = "RootObject";
Stack<JsonValue> jsonStack = new Stack<JsonValue>();
string nodeType = null;
bool isEmptyElement = false;
JsonValue parent = new JsonObject();
jsonStack.Push(parent);
string currentName = RootObjectName;
try
{
MoveToRootNode(jsonReader);
while (jsonStack.Count > 0 && jsonReader.NodeType != XmlNodeType.None)
{
if (parent is JsonObject && currentName == null)
{
currentName = GetMemberName(jsonReader);
}
nodeType = jsonReader.GetAttribute(TypeAttributeName) ?? StringAttributeValue;
if (parent is JsonArray)
{
// For arrays, the element name has to be "item"
if (jsonReader.Name != ItemElementName)
{
throw new FormatException(Properties.Resources.IncorrectJsonFormat);
}
}
switch (nodeType)
{
case NullAttributeValue:
case BooleanAttributeValue:
case StringAttributeValue:
case NumberAttributeValue:
JsonPrimitive jsonPrimitive = ReadPrimitive(nodeType, jsonReader);
InsertJsonValue(jsonStack, ref parent, ref currentName, jsonPrimitive, true);
break;
case ArrayAttributeValue:
JsonArray jsonArray = CreateJsonArray(jsonReader, ref isEmptyElement);
InsertJsonValue(jsonStack, ref parent, ref currentName, jsonArray, isEmptyElement);
break;
case ObjectAttributeValue:
JsonObject jsonObject = CreateObjectWithTypeHint(jsonReader, ref isEmptyElement);
InsertJsonValue(jsonStack, ref parent, ref currentName, jsonObject, isEmptyElement);
break;
default:
throw new FormatException(Properties.Resources.IncorrectJsonFormat);
}
while (jsonReader.NodeType == XmlNodeType.EndElement && jsonStack.Count > 0)
{
jsonReader.Read();
SkipWhitespace(jsonReader);
jsonStack.Pop();
if (jsonStack.Count > 0)
{
parent = jsonStack.Peek();
}
}
}
}
catch (XmlException xmlException)
{
throw new FormatException(Properties.Resources.IncorrectJsonFormat, xmlException);
}
if (jsonStack.Count != 1)
{
throw new FormatException(Properties.Resources.IncorrectJsonFormat);
}
return parent[RootObjectName];
}
private static JsonValue JXMLToJsonValue(Stream jsonStream, byte[] jsonBytes)
{
try
{
using (XmlDictionaryReader jsonReader =
jsonStream != null
? JsonReaderWriterFactory.CreateJsonReader(jsonStream, XmlDictionaryReaderQuotas.Max)
: JsonReaderWriterFactory.CreateJsonReader(jsonBytes, XmlDictionaryReaderQuotas.Max))
{
return JXMLToJsonValue(jsonReader);
}
}
catch (XmlException)
{
throw new FormatException(Properties.Resources.IncorrectJsonFormat);
}
}
private static void InsertJsonValue(Stack<JsonValue> jsonStack, ref JsonValue parent, ref string currentName, JsonValue jsonValue, bool isEmptyElement)
{
if (parent is JsonArray)
{
((JsonArray)parent).Add(jsonValue);
}
else
{
if (currentName != null)
{
((JsonObject)parent)[currentName] = jsonValue;
currentName = null;
}
}
if (!isEmptyElement)
{
jsonStack.Push(jsonValue);
parent = jsonValue;
}
}
private static string GetMemberName(XmlDictionaryReader jsonReader)
{
string name;
if (jsonReader.NamespaceURI == ItemElementName && jsonReader.LocalName == ItemElementName)
{
// JXML special case for names which aren't valid XML names
name = jsonReader.GetAttribute(ItemElementName);
if (name == null)
{
throw new FormatException(Properties.Resources.IncorrectJsonFormat);
}
}
else
{
name = jsonReader.Name;
}
return name;
}
private static JsonObject CreateObjectWithTypeHint(XmlDictionaryReader jsonReader, ref bool isEmptyElement)
{
JsonObject jsonObject = new JsonObject();
string typeHintAttribute = jsonReader.GetAttribute(TypeHintAttributeName);
isEmptyElement = jsonReader.IsEmptyElement;
jsonReader.ReadStartElement();
SkipWhitespace(jsonReader);
if (typeHintAttribute != null)
{
jsonObject.Add(TypeHintAttributeName, typeHintAttribute);
}
return jsonObject;
}
private static JsonArray CreateJsonArray(XmlDictionaryReader jsonReader, ref bool isEmptyElement)
{
JsonArray jsonArray = new JsonArray();
isEmptyElement = jsonReader.IsEmptyElement;
jsonReader.ReadStartElement();
SkipWhitespace(jsonReader);
return jsonArray;
}
private static void MoveToRootNode(XmlDictionaryReader jsonReader)
{
while (!jsonReader.EOF && (jsonReader.NodeType == XmlNodeType.None || jsonReader.NodeType == XmlNodeType.XmlDeclaration))
{
// read into <root> node
jsonReader.Read();
SkipWhitespace(jsonReader);
}
if (jsonReader.NodeType != XmlNodeType.Element || !String.IsNullOrEmpty(jsonReader.NamespaceURI) || jsonReader.Name != RootElementName)
{
throw new FormatException(Properties.Resources.IncorrectJsonFormat);
}
}
private static JsonPrimitive ReadPrimitive(string type, XmlDictionaryReader jsonReader)
{
JsonValue result = null;
switch (type)
{
case NullAttributeValue:
jsonReader.Skip();
result = null;
break;
case BooleanAttributeValue:
result = jsonReader.ReadElementContentAsBoolean();
break;
case StringAttributeValue:
result = jsonReader.ReadElementContentAsString();
break;
case NumberAttributeValue:
string temp = jsonReader.ReadElementContentAsString();
result = ConvertStringToJsonNumber(temp);
break;
}
SkipWhitespace(jsonReader);
return (JsonPrimitive)result;
}
private static void SkipWhitespace(XmlDictionaryReader reader)
{
while (!reader.EOF && (reader.NodeType == XmlNodeType.Whitespace || reader.NodeType == XmlNodeType.SignificantWhitespace))
{
reader.Read();
}
}
private static JsonValue ConvertStringToJsonNumber(string value)
{
if (value.IndexOfAny(_floatingPointChars) < 0)
{
int intVal;
if (Int32.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out intVal))
{
return intVal;
}
long longVal;
if (Int64.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out longVal))
{
return longVal;
}
}
decimal decValue;
if (Decimal.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out decValue) && decValue != 0)
{
return decValue;
}
double dblValue;
if (Double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out dblValue))
{
return dblValue;
}
throw new ArgumentException(RS.Format(Properties.Resources.InvalidJsonPrimitive, value.ToString()), "value");
}
}
}

Просмотреть файл

@ -1,389 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.Serialization;
using System.Xml;
namespace System.Json
{
/// <summary>
/// A JsonArray is an ordered sequence of zero or more <see cref="System.Json.JsonValue"/> objects.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix",
Justification = "Array already conveys the meaning of collection")]
[DataContract]
public sealed class JsonArray : JsonValue, IList<JsonValue>
{
[DataMember]
private List<JsonValue> values = new List<JsonValue>();
/// <summary>
/// Creates an instance of the <see cref="System.Json.JsonArray"/> class initialized by
/// an <see cref="System.Collections.Generic.IEnumerable{T}"/> enumeration of
/// objects of type <see cref="System.Json.JsonValue"/>.
/// </summary>
/// <param name="items">The <see cref="System.Collections.Generic.IEnumerable{T}"/> enumeration
/// of objects of type <see cref="System.Json.JsonValue"/> used to initialize the JavaScript Object Notation (JSON)
/// array.</param>
/// <exception cref="System.ArgumentNullException">If items is null.</exception>
/// <exception cref="System.ArgumentException">If any of the items in the collection
/// is a <see cref="System.Json.JsonValue"/> with <see cref="System.Json.JsonValue.JsonType"/> property of
/// value <see cref="F:System.Json.JsonType.Default"/>.</exception>
public JsonArray(IEnumerable<JsonValue> items)
{
AddRange(items);
}
/// <summary>
/// Creates an instance of the <see cref="System.Json.JsonArray"/> class, initialized by an array of type <see cref="System.Json.JsonValue"/>.
/// </summary>
/// <param name="items">The array of type <see cref="System.Json.JsonValue"/> used to initialize the
/// JavaScript Object Notation (JSON) array.</param>
/// <exception cref="System.ArgumentException">If any of the items in the collection
/// is a <see cref="System.Json.JsonValue"/> with <see cref="System.Json.JsonValue.JsonType"/> property of
/// value <see cref="F:System.Json.JsonType.Default"/>.</exception>
public JsonArray(params JsonValue[] items)
{
if (items != null)
{
AddRange(items);
}
}
/// <summary>
/// Gets the JSON type of this <see cref="System.Json.JsonArray"/>. The return value
/// is always <see cref="F:System.Json.JsonType.Array"/>.
/// </summary>
public override JsonType JsonType
{
get { return JsonType.Array; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="System.Json.JsonArray"/> is read-only.
/// </summary>
public bool IsReadOnly
{
get { return ((IList)values).IsReadOnly; }
}
/// <summary>
/// Returns the number of <see cref="System.Json.JsonValue"/> elements in the array.
/// </summary>
public override int Count
{
get { return values.Count; }
}
/// <summary>
/// Gets or sets the JSON value at a specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <returns>The <see cref="System.Json.JsonValue"/> element at the specified index.</returns>
/// <exception cref="System.ArgumentOutOfRangeException">If index is not a valid index for this array.</exception>
/// <exception cref="System.ArgumentException">The property is set and the value is a
/// <see cref="System.Json.JsonValue"/> with <see cref="System.Json.JsonValue.JsonType"/>
/// property of value <see cref="F:System.Json.JsonType.Default"/>.</exception>
public override JsonValue this[int index]
{
get { return values[index]; }
set
{
if (value != null && value.JsonType == JsonType.Default)
{
throw new ArgumentNullException("value", Properties.Resources.UseOfDefaultNotAllowed);
}
JsonValue oldValue = values[index];
RaiseItemChanging(value, JsonValueChange.Replace, index);
values[index] = value;
RaiseItemChanged(oldValue, JsonValueChange.Replace, index);
}
}
/// <summary>
/// Adds the elements from a collection of type <see cref="System.Json.JsonValue"/> to this instance.
/// </summary>
/// <param name="items">Collection of items to add.</param>
/// <exception cref="System.ArgumentNullException">If items is null.</exception>
/// <exception cref="System.ArgumentException">If any of the items in the collection
/// is a <see cref="System.Json.JsonValue"/> with <see cref="System.Json.JsonValue.JsonType"/> property of
/// value <see cref="F:System.Json.JsonType.Default"/>.</exception>
public void AddRange(IEnumerable<JsonValue> items)
{
if (items == null)
{
throw new ArgumentNullException("items");
}
if (ChangingListenersCount > 0)
{
int index = Count;
foreach (JsonValue toBeAdded in items)
{
RaiseItemChanging(toBeAdded, JsonValueChange.Add, index++);
}
}
foreach (JsonValue item in items)
{
if (item != null && item.JsonType == JsonType.Default)
{
throw new ArgumentNullException("items", Properties.Resources.UseOfDefaultNotAllowed);
}
values.Add(item);
RaiseItemChanged(item, JsonValueChange.Add, values.Count - 1);
}
}
/// <summary>
/// Adds the elements from an array of type <see cref="System.Json.JsonValue"/> to this instance.
/// </summary>
/// <param name="items">The array of type JsonValue to be added to this instance.</param>
/// <exception cref="System.ArgumentNullException">If items is null.</exception>
/// <exception cref="System.ArgumentException">If any of the items in the array
/// is a <see cref="System.Json.JsonValue"/> with <see cref="System.Json.JsonValue.JsonType"/> property of
/// value <see cref="F:System.Json.JsonType.Default"/>.</exception>
public void AddRange(params JsonValue[] items)
{
AddRange(items as IEnumerable<JsonValue>);
}
/// <summary>
/// Searches for a specified object and returns the zero-based index of its first
/// occurrence within this <see cref="System.Json.JsonArray"/>.
/// </summary>
/// <param name="item">The <see cref="System.Json.JsonValue"/> object to look up.</param>
/// <returns>The zero-based index of the first occurrence of item within the
/// <see cref="System.Json.JsonArray"/>, if found; otherwise, -1.</returns>
public int IndexOf(JsonValue item)
{
return values.IndexOf(item);
}
/// <summary>
/// Insert a JSON CLR type into the array at a specified index.
/// </summary>
/// <param name="index">The zero-based index at which the item should be inserted.</param>
/// <param name="item">The <see cref="System.Json.JsonValue"/> object to insert.</param>
/// <exception cref="System.ArgumentOutOfRangeException">If index is less than zero or larger than
/// the size of the array.</exception>
/// <exception cref="System.ArgumentException">If the object to insert has a
/// <see cref="System.Json.JsonValue.JsonType"/> property of value
/// <see cref="F:System.Json.JsonType.Default"/>.</exception>
public void Insert(int index, JsonValue item)
{
if (item != null && item.JsonType == JsonType.Default)
{
throw new ArgumentNullException("item", Properties.Resources.UseOfDefaultNotAllowed);
}
RaiseItemChanging(item, JsonValueChange.Add, index);
values.Insert(index, item);
RaiseItemChanged(item, JsonValueChange.Add, index);
}
/// <summary>
/// Remove the JSON value at a specified index of <see cref="System.Json.JsonArray"/>.
/// </summary>
/// <param name="index">The zero-based index at which to remove the <see cref="System.Json.JsonValue"/>.</param>
/// <exception cref="System.ArgumentOutOfRangeException">If index is less than zero or index
/// is equal or larger than the size of the array.</exception>
public void RemoveAt(int index)
{
JsonValue item = values[index];
RaiseItemChanging(item, JsonValueChange.Remove, index);
values.RemoveAt(index);
RaiseItemChanged(item, JsonValueChange.Remove, index);
}
/// <summary>
/// Adds a <see cref="System.Json.JsonValue"/> object to the end of the array.
/// </summary>
/// <param name="item">The <see cref="System.Json.JsonValue"/> object to add.</param>
/// <exception cref="System.ArgumentException">If the object to add has a
/// <see cref="System.Json.JsonValue.JsonType"/> property of value
/// <see cref="F:System.Json.JsonType.Default"/>.</exception>
public void Add(JsonValue item)
{
if (item != null && item.JsonType == JsonType.Default)
{
throw new ArgumentNullException("item", Properties.Resources.UseOfDefaultNotAllowed);
}
int index = Count;
RaiseItemChanging(item, JsonValueChange.Add, index);
values.Add(item);
RaiseItemChanged(item, JsonValueChange.Add, index);
}
/// <summary>
/// Removes all JSON CLR types from the <see cref="System.Json.JsonArray"/>.
/// </summary>
public void Clear()
{
RaiseItemChanging(null, JsonValueChange.Clear, 0);
values.Clear();
RaiseItemChanged(null, JsonValueChange.Clear, 0);
}
/// <summary>
/// Checks whether a specified JSON CLR type is in the <see cref="System.Json.JsonArray"/>.
/// </summary>
/// <param name="item">The <see cref="System.Json.JsonValue"/> to check for in the array.</param>
/// <returns>true if item is found in the <see cref="System.Json.JsonArray"/>; otherwise, false.</returns>
public bool Contains(JsonValue item)
{
return values.Contains(item);
}
/// <summary>
/// Copies the contents of the current JSON CLR array instance into a specified
/// destination array beginning at the specified index.
/// </summary>
/// <param name="array">The destination array to which the elements of the current
/// <see cref="System.Json.JsonArray"/> object are copied.</param>
/// <param name="arrayIndex">The zero-based index in the destination array at which the
/// copying of the elements of the JSON CLR array begins.</param>
public void CopyTo(JsonValue[] array, int arrayIndex)
{
values.CopyTo(array, arrayIndex);
}
/// <summary>
/// Removes the first occurrence of the specified JSON value from the array.
/// </summary>
/// <param name="item">The <see cref="System.Json.JsonValue"/> to remove from the <see cref="System.Json.JsonArray"/>.</param>
/// <returns>true if item is successfully removed; otherwise, false. This method
/// also returns false if item was not found in the <see cref="System.Json.JsonArray"/>.</returns>
public bool Remove(JsonValue item)
{
int index = -1;
if (ChangingListenersCount > 0 || ChangedListenersCount > 0)
{
index = IndexOf(item);
}
if (index >= 0)
{
RaiseItemChanging(item, JsonValueChange.Remove, index);
}
bool result = values.Remove(item);
if (index >= 0)
{
RaiseItemChanged(item, JsonValueChange.Remove, index);
}
return result;
}
/// <summary>
/// Returns an enumerator that iterates through the <see cref="System.Json.JsonValue"/> objects in the array.
/// </summary>
/// <returns>Returns an <see cref="System.Collections.IEnumerator"/> object that
/// iterates through the <see cref="System.Json.JsonValue"/> elements in this <see cref="System.Json.JsonArray"/>.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return values.GetEnumerator();
}
/// <summary>
/// Safe indexer for the <see cref="System.Json.JsonValue"/> type.
/// </summary>
/// <param name="index">The zero-based index of the element to get.</param>
/// <returns>If the index is within the array bounds and the value corresponding to the
/// index is not null, then it will return that value. Otherwise it will return a
/// <see cref="System.Json.JsonValue"/> instance with <see cref="System.Json.JsonValue.JsonType"/>
/// equals to <see cref="F:System.Json.JsonType.Default"/>.</returns>
public override JsonValue ValueOrDefault(int index)
{
if (index >= 0 && index < Count && this[index] != null)
{
return this[index];
}
return base.ValueOrDefault(index);
}
/// <summary>
/// Returns an enumerator that iterates through the <see cref="System.Json.JsonValue"/> objects in the array.
/// </summary>
/// <returns>Returns an <see cref="System.Collections.Generic.IEnumerator{T}"/> object that
/// iterates through the <see cref="System.Json.JsonValue"/> elements in this <see cref="System.Json.JsonArray"/>.</returns>
public new IEnumerator<JsonValue> GetEnumerator()
{
return values.GetEnumerator();
}
/// <summary>
/// Returns an enumerator which iterates through the values in this object.
/// </summary>
/// <returns>An <see cref="System.Collections.Generic.IEnumerator{T}"/> which iterates through the values in this object.</returns>
/// <remarks>The enumerator returned by this class contains one pair for each element
/// in this array, whose key is the element index (as a string), and the value is the
/// element itself.</remarks>
protected override IEnumerator<KeyValuePair<string, JsonValue>> GetKeyValuePairEnumerator()
{
for (int i = 0; i < values.Count; i++)
{
yield return new KeyValuePair<string, JsonValue>(i.ToString(CultureInfo.InvariantCulture), values[i]);
}
}
/// <summary>
/// Callback method called to let an instance write the proper JXML attribute when saving this
/// instance.
/// </summary>
/// <param name="jsonWriter">The JXML writer used to write JSON.</param>
internal override void WriteAttributeString(XmlDictionaryWriter jsonWriter)
{
if (jsonWriter == null)
{
throw new ArgumentNullException("jsonWriter");
}
jsonWriter.WriteAttributeString(JXmlToJsonValueConverter.TypeAttributeName, JXmlToJsonValueConverter.ArrayAttributeValue);
}
/// <summary>
/// Callback method called during Save operations to let the instance write the start element
/// and return the next element in the collection.
/// </summary>
/// <param name="jsonWriter">The JXML writer used to write JSON.</param>
/// <param name="currentIndex">The index within this collection.</param>
/// <returns>The next item in the collection, or null of there are no more items.</returns>
internal override JsonValue WriteStartElementAndGetNext(XmlDictionaryWriter jsonWriter, int currentIndex)
{
if (jsonWriter == null)
{
throw new ArgumentNullException("jsonWriter");
}
jsonWriter.WriteStartElement(JXmlToJsonValueConverter.ItemElementName);
JsonValue nextValue = this[currentIndex];
return nextValue;
}
private void RaiseItemChanging(JsonValue child, JsonValueChange change, int index)
{
if (ChangingListenersCount > 0)
{
RaiseChangingEvent(this, new JsonValueChangeEventArgs(child, change, index));
}
}
private void RaiseItemChanged(JsonValue child, JsonValueChange change, int index)
{
if (ChangedListenersCount > 0)
{
RaiseChangedEvent(this, new JsonValueChangeEventArgs(child, change, index));
}
}
}
}

Просмотреть файл

@ -1,474 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
using System.Xml;
using WrappedPair = System.Json.NGenWrapper<System.Collections.Generic.KeyValuePair<string, System.Json.JsonValue>>;
namespace System.Json
{
/// <summary>
/// A JsonObject is an unordered collection of zero or more key/value pairs.
/// </summary>
/// <remarks>A JsonObject is an unordered collection of zero or more key/value pairs,
/// where each key is a String and each value is a <see cref="System.Json.JsonValue"/>, which can be a
/// <see cref="System.Json.JsonPrimitive"/>, a <see cref="System.Json.JsonArray"/>, or a JsonObject.</remarks>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix",
Justification = "Object in the context of JSON already conveys the meaning of dictionary")]
[DataContract]
public sealed class JsonObject : JsonValue, IDictionary<string, JsonValue>
{
[DataMember]
private Dictionary<string, JsonValue> values = new Dictionary<string, JsonValue>(StringComparer.Ordinal);
private List<WrappedPair> indexedPairs;
private int instanceSaveCount;
private object saveLock = new object();
/// <summary>
/// Creates an instance of the <see cref="System.Json.JsonObject"/> class initialized with an
/// <see cref="System.Collections.Generic.IEnumerable{T}"/> collection of key/value pairs.
/// </summary>
/// <param name="items">The <see cref="System.Collections.Generic.IEnumerable{T}"/> collection of
/// <see cref="System.Collections.Generic.KeyValuePair{K, V}"/> used to initialize the
/// key/value pairs</param>
/// <exception cref="System.ArgumentNullException">If items is null.</exception>
/// <exception cref="System.ArgumentException">If any of the values in the collection
/// is a <see cref="System.Json.JsonValue"/> with <see cref="System.Json.JsonValue.JsonType"/> property of
/// value <see cref="F:System.Json.JsonType.Default"/>.</exception>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "There's no complexity using this design because nested generic type is atomic type not another collection")]
public JsonObject(IEnumerable<KeyValuePair<string, JsonValue>> items)
{
AddRange(items);
}
/// <summary>
/// Creates an instance of the <see cref="System.Json.JsonObject"/> class initialized with a collection of key/value pairs.
/// </summary>
/// <param name="items">The <see cref="System.Collections.Generic.KeyValuePair{K, V}"/> objects used to initialize the key/value pairs.</param>
/// <exception cref="System.ArgumentException">If any of the values in the collection
/// is a <see cref="System.Json.JsonValue"/> with <see cref="System.Json.JsonValue.JsonType"/> property of
/// value <see cref="F:System.Json.JsonType.Default"/>.</exception>
public JsonObject(params KeyValuePair<string, JsonValue>[] items)
{
if (items != null)
{
AddRange(items);
}
}
/// <summary>
/// Gets the JSON type of this <see cref="System.Json.JsonObject"/>. The return value
/// is always <see cref="F:System.Json.JsonType.Object"/>.
/// </summary>
public override JsonType JsonType
{
get { return JsonType.Object; }
}
/// <summary>
/// Gets a collection that contains the keys in this <see cref="System.Json.JsonObject"/>.
/// </summary>
public ICollection<string> Keys
{
get { return values.Keys; }
}
/// <summary>
/// Gets a collection that contains the values in this <see cref="System.Json.JsonObject"/>.
/// </summary>
public ICollection<JsonValue> Values
{
get { return values.Values; }
}
/// <summary>
/// Returns the number of key/value pairs in this <see cref="System.Json.JsonObject"/>.
/// </summary>
public override int Count
{
get { return values.Count; }
}
/// <summary>
/// Gets a value indicating whether this JSON CLR object is read-only.
/// </summary>
bool ICollection<KeyValuePair<string, JsonValue>>.IsReadOnly
{
get { return ((ICollection<KeyValuePair<string, JsonValue>>)values).IsReadOnly; }
}
/// <summary>
/// Gets or sets the value associated with the specified key.
/// </summary>
/// <param name="key">The key of the value to get or set.</param>
/// <returns>The <see cref="System.Json.JsonValue"/> associated to the specified key.</returns>
/// <exception cref="System.ArgumentNullException">If key is null.</exception>
/// <exception cref="System.ArgumentException">The property is set and the value is a
/// <see cref="System.Json.JsonValue"/> with <see cref="System.Json.JsonValue.JsonType"/>
/// property of value <see cref="F:System.Json.JsonType.Default"/>.</exception>
public override JsonValue this[string key]
{
get
{
if (key == null)
{
throw new ArgumentNullException("key");
}
return values[key];
}
set
{
if (value != null && value.JsonType == JsonType.Default)
{
throw new ArgumentNullException("value", Properties.Resources.UseOfDefaultNotAllowed);
}
if (key == null)
{
throw new ArgumentNullException("key");
}
bool replacement = values.ContainsKey(key);
JsonValue oldValue = null;
if (replacement)
{
oldValue = values[key];
RaiseItemChanging(value, JsonValueChange.Replace, key);
}
else
{
RaiseItemChanging(value, JsonValueChange.Add, key);
}
values[key] = value;
if (replacement)
{
RaiseItemChanged(oldValue, JsonValueChange.Replace, key);
}
else
{
RaiseItemChanged(value, JsonValueChange.Add, key);
}
}
}
/// <summary>
/// Safe string indexer for the <see cref="System.Json.JsonValue"/> type.
/// </summary>
/// <param name="key">The key of the element to get.</param>
/// <returns>If this instance contains the given key and the value corresponding to
/// the key is not null, then it will return that value. Otherwise it will return a
/// <see cref="System.Json.JsonValue"/> instance with <see cref="System.Json.JsonValue.JsonType"/>
/// equals to <see cref="F:System.Json.JsonType.Default"/>.</returns>
public override JsonValue ValueOrDefault(string key)
{
if (key != null && ContainsKey(key) && this[key] != null)
{
return this[key];
}
return base.ValueOrDefault(key);
}
/// <summary>
/// Adds a specified collection of key/value pairs to this instance.
/// </summary>
/// <param name="items">The collection of key/value pairs to add.</param>
/// <exception cref="System.ArgumentNullException">If items is null.</exception>
/// <exception cref="System.ArgumentException">If the value of any of the items in the collection
/// is a <see cref="System.Json.JsonValue"/> with <see cref="System.Json.JsonValue.JsonType"/> property of
/// value <see cref="F:System.Json.JsonType.Default"/>.</exception>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "There's no complexity using this design because nested generic type is atomic type not another collection")]
public void AddRange(IEnumerable<KeyValuePair<string, JsonValue>> items)
{
if (items == null)
{
throw new ArgumentNullException("items");
}
if (ChangingListenersCount > 0)
{
foreach (KeyValuePair<string, JsonValue> item in items)
{
RaiseItemChanging(item.Value, JsonValueChange.Add, item.Key);
}
}
foreach (KeyValuePair<string, JsonValue> item in items)
{
if (item.Value != null && item.Value.JsonType == JsonType.Default)
{
throw new ArgumentNullException("items", Properties.Resources.UseOfDefaultNotAllowed);
}
values.Add(item.Key, item.Value);
RaiseItemChanged(item.Value, JsonValueChange.Add, item.Key);
}
}
/// <summary>
/// Adds the elements from an array of type <see cref="System.Json.JsonValue"/> to this instance.
/// </summary>
/// <param name="items">The array of key/value paris to be added to this instance.</param>
/// <exception cref="System.ArgumentException">If the value of any of the items in the array
/// is a <see cref="System.Json.JsonValue"/> with <see cref="System.Json.JsonValue.JsonType"/> property of
/// value <see cref="F:System.Json.JsonType.Default"/>.</exception>
public void AddRange(params KeyValuePair<string, JsonValue>[] items)
{
AddRange(items as IEnumerable<KeyValuePair<string, JsonValue>>);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)values).GetEnumerator();
}
/// <summary>
/// Adds a key/value pair to this <see cref="System.Json.JsonObject"/> instance.
/// </summary>
/// <param name="key">The key for the element added.</param>
/// <param name="value">The <see cref="System.Json.JsonValue"/> for the element added.</param>
/// <exception cref="System.ArgumentException">If the value is a <see cref="System.Json.JsonValue"/>
/// with <see cref="System.Json.JsonValue.JsonType"/> property of
/// value <see cref="F:System.Json.JsonType.Default"/>.</exception>
public void Add(string key, JsonValue value)
{
if (value != null && value.JsonType == JsonType.Default)
{
throw new ArgumentNullException("value", Properties.Resources.UseOfDefaultNotAllowed);
}
RaiseItemChanging(value, JsonValueChange.Add, key);
values.Add(key, value);
RaiseItemChanged(value, JsonValueChange.Add, key);
}
/// <summary>
/// Adds a key/value pair to this <see cref="System.Json.JsonObject"/> instance.
/// </summary>
/// <param name="item">The key/value pair to be added.</param>
/// <exception cref="System.ArgumentException">If the value of the pair is a
/// <see cref="System.Json.JsonValue"/> with <see cref="System.Json.JsonValue.JsonType"/>
/// property of value <see cref="F:System.Json.JsonType.Default"/>.</exception>
public void Add(KeyValuePair<string, JsonValue> item)
{
Add(item.Key, item.Value);
}
/// <summary>
/// Checks whether a key/value pair with a specified key exists in this <see cref="System.Json.JsonObject"/> instance.
/// </summary>
/// <param name="key">The key to check for.</param>
/// <returns>true if this instance contains the key; otherwise, false.</returns>
public override bool ContainsKey(string key)
{
return values.ContainsKey(key);
}
/// <summary>
/// Removes the key/value pair with a specified key from this <see cref="System.Json.JsonObject"/> instance.
/// </summary>
/// <param name="key">The key of the item to remove.</param>
/// <returns>true if the element is successfully found and removed; otherwise, false.
/// This method returns false if key is not found in this <see cref="System.Json.JsonObject"/> instance.</returns>
public bool Remove(string key)
{
JsonValue original = null;
bool containsKey = false;
if (ChangingListenersCount > 0 || ChangedListenersCount > 0)
{
containsKey = TryGetValue(key, out original);
}
if (containsKey && ChangingListenersCount > 0)
{
RaiseItemChanging(original, JsonValueChange.Remove, key);
}
bool result = values.Remove(key);
if (containsKey && ChangedListenersCount > 0)
{
RaiseItemChanged(original, JsonValueChange.Remove, key);
}
return result;
}
/// <summary>
/// Attempts to get the value that corresponds to the specified key.
/// </summary>
/// <param name="key">The key of the value to retrieve.</param>
/// <param name="value">The primitive or structured <see cref="System.Json.JsonValue"/> object that has the key
/// specified. If this object does not contain a key/value pair with the given key,
/// this parameter is set to null.</param>
/// <returns>true if the instance of the <see cref="System.Json.JsonObject"/> contains an element with the
/// specified key; otherwise, false.</returns>
public bool TryGetValue(string key, out JsonValue value)
{
return values.TryGetValue(key, out value);
}
/// <summary>
/// Removes all key/value pairs from this <see cref="System.Json.JsonObject"/> instance.
/// </summary>
public void Clear()
{
RaiseItemChanging(null, JsonValueChange.Clear, null);
values.Clear();
RaiseItemChanged(null, JsonValueChange.Clear, null);
}
bool ICollection<KeyValuePair<string, JsonValue>>.Contains(KeyValuePair<string, JsonValue> item)
{
return ((ICollection<KeyValuePair<string, JsonValue>>)values).Contains(item);
}
/// <summary>
/// Copies the contents of this <see cref="System.Json.JsonObject"/> instance into a specified
/// key/value destination array beginning at a specified index.
/// </summary>
/// <param name="array">The destination array of type <see cref="System.Collections.Generic.KeyValuePair{K, V}"/>
/// to which the elements of this <see cref="System.Json.JsonObject"/> are copied.</param>
/// <param name="arrayIndex">The zero-based index at which to begin the insertion of the
/// contents from this <see cref="System.Json.JsonObject"/> instance.</param>
public void CopyTo(KeyValuePair<string, JsonValue>[] array, int arrayIndex)
{
((ICollection<KeyValuePair<string, JsonValue>>)values).CopyTo(array, arrayIndex);
}
bool ICollection<KeyValuePair<string, JsonValue>>.Remove(KeyValuePair<string, JsonValue> item)
{
if (ChangingListenersCount > 0)
{
if (ContainsKey(item.Key) && EqualityComparer<JsonValue>.Default.Equals(item.Value, values[item.Key]))
{
RaiseItemChanging(item.Value, JsonValueChange.Remove, item.Key);
}
}
bool result = ((ICollection<KeyValuePair<string, JsonValue>>)values).Remove(item);
if (result)
{
RaiseItemChanged(item.Value, JsonValueChange.Remove, item.Key);
}
return result;
}
/// <summary>
/// Returns an enumerator over the key/value pairs contained in this <see cref="System.Json.JsonObject"/> instance.
/// </summary>
/// <returns>An <see cref="System.Collections.Generic.IEnumerator{T}"/> which iterates
/// through the members of this instance.</returns>
protected override IEnumerator<KeyValuePair<string, JsonValue>> GetKeyValuePairEnumerator()
{
return values.GetEnumerator();
}
/// <summary>
/// Callback method called when a Save operation is starting for this instance.
/// </summary>
protected override void OnSaveStarted()
{
lock (saveLock)
{
instanceSaveCount++;
if (indexedPairs == null)
{
indexedPairs = new List<WrappedPair>();
foreach (KeyValuePair<string, JsonValue> item in values)
{
indexedPairs.Add(new WrappedPair(item));
}
}
}
}
/// <summary>
/// Callback method called when a Save operation is finished for this instance.
/// </summary>
protected override void OnSaveEnded()
{
lock (saveLock)
{
instanceSaveCount--;
if (instanceSaveCount == 0)
{
indexedPairs = null;
}
}
}
/// <summary>
/// Callback method called to let an instance write the proper JXML attribute when saving this
/// instance.
/// </summary>
/// <param name="jsonWriter">The JXML writer used to write JSON.</param>
internal override void WriteAttributeString(XmlDictionaryWriter jsonWriter)
{
jsonWriter.WriteAttributeString(JXmlToJsonValueConverter.TypeAttributeName, JXmlToJsonValueConverter.ObjectAttributeValue);
}
/// <summary>
/// Callback method called during Save operations to let the instance write the start element
/// and return the next element in the collection.
/// </summary>
/// <param name="jsonWriter">The JXML writer used to write JSON.</param>
/// <param name="currentIndex">The index within this collection.</param>
/// <returns>The next item in the collection, or null of there are no more items.</returns>
internal override JsonValue WriteStartElementAndGetNext(XmlDictionaryWriter jsonWriter, int currentIndex)
{
KeyValuePair<string, JsonValue> currentPair = indexedPairs[currentIndex];
string currentKey = currentPair.Key;
if (currentKey.Length == 0)
{
// special case in JXML world
jsonWriter.WriteStartElement(JXmlToJsonValueConverter.ItemElementName, JXmlToJsonValueConverter.ItemElementName);
jsonWriter.WriteAttributeString(JXmlToJsonValueConverter.ItemElementName, String.Empty);
}
else
{
jsonWriter.WriteStartElement(currentKey);
}
return currentPair.Value;
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "Context is required by CLR for this to work.")]
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
saveLock = new object();
}
private void RaiseItemChanging(JsonValue child, JsonValueChange change, string key)
{
if (ChangingListenersCount > 0)
{
RaiseChangingEvent(this, new JsonValueChangeEventArgs(child, change, key));
}
}
private void RaiseItemChanged(JsonValue child, JsonValueChange change, string key)
{
if (ChangedListenersCount > 0)
{
RaiseChangedEvent(this, new JsonValueChangeEventArgs(child, change, key));
}
}
}
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -1,50 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace System.Json
{
/// <summary>
/// An enumeration that specifies primitive and structured JavaScript Object
/// Notation (JSON) common language runtime (CLR) types.
/// </summary>
public enum JsonType
{
/// <summary>
/// Specifies the JSON string CLR type.
/// </summary>
String,
/// <summary>
/// Specifies the JSON number CLR type.
/// </summary>
Number,
/// <summary>
/// Specifies the JSON object CLR type that consists of an unordered collection
/// of key/value pairs, where the key is of type String and the value is of
/// type <see cref="System.Json.JsonValue"/>, which can, in turn, be either a
/// primitive or a structured JSON type.
/// </summary>
Object,
/// <summary>
/// Specifies the JSON array CLR type that consists of an ordered collection of
/// <see cref="System.Json.JsonValue"/>types, which can, in turn, be either
/// primitive or structured JSON types.
/// </summary>
Array,
/// <summary>
/// Specifies the JSON Boolean CLR type.
/// </summary>
Boolean,
/// <summary>
/// Specifies the type returned by calls to <see cref="System.Json.JsonValue.ValueOrDefault(string)"/>
/// or <see cref="System.Json.JsonValue.ValueOrDefault(int)"/>
/// when the element searches doesn't exist in the JSON collection. This is a special
/// value which does not represent any JSON element, and cannot be added to any
/// JSON collections.
/// </summary>
Default
}
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -1,30 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace System.Json
{
/// <summary>
/// Specifies the event type when an event is raised for a <see cref="System.Json.JsonValue"/>.
/// </summary>
public enum JsonValueChange
{
/// <summary>
/// An element has been or will be added to the collection.
/// </summary>
Add,
/// <summary>
/// An element has been or will be removed from the collection.
/// </summary>
Remove,
/// <summary>
/// An element has been or will be replaced in the collection. Used on indexers.
/// </summary>
Replace,
/// <summary>
/// All elements of the collection have been or will be removed.
/// </summary>
Clear,
}
}

Просмотреть файл

@ -1,98 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace System.Json
{
/// <summary>
/// Provide data for the <see cref="System.Json.JsonValue.Changing"/> and <see cref="System.Json.JsonValue.Changed"/> events.
/// </summary>
public class JsonValueChangeEventArgs : EventArgs
{
private JsonValue child;
private JsonValueChange change;
private int index;
private string key;
/// <summary>
/// Initializes a new instance of the <see cref="System.Json.JsonValueChangeEventArgs"/> class for
/// changes in a <see cref="System.Json.JsonArray"/>.
/// </summary>
/// <param name="child">The <see cref="System.Json.JsonValue"/> instance which will be or has been modified.</param>
/// <param name="change">The type of change of the <see cref="System.Json.JsonValue"/> event.</param>
/// <param name="index">The index of the element being changed in a <see cref="System.Json.JsonArray"/>.</param>
public JsonValueChangeEventArgs(JsonValue child, JsonValueChange change, int index)
{
if (index < 0)
{
throw new ArgumentOutOfRangeException("index", RS.Format(Properties.Resources.ArgumentMustBeGreaterThanOrEqualTo, index, 0));
}
this.child = child;
this.change = change;
this.index = index;
}
/// <summary>
/// Initializes a new instance of the <see cref="System.Json.JsonValueChangeEventArgs"/> class for
/// changes in a <see cref="System.Json.JsonObject"/>.
/// </summary>
/// <param name="child">The <see cref="System.Json.JsonValue"/> instance which will be or has been modified.</param>
/// <param name="change">The type of change of the <see cref="System.Json.JsonValue"/> event.</param>
/// <param name="key">The key of the element being changed in a <see cref="System.Json.JsonObject"/>.</param>
public JsonValueChangeEventArgs(JsonValue child, JsonValueChange change, string key)
{
if (change != JsonValueChange.Clear)
{
if (key == null)
{
throw new ArgumentNullException("key");
}
}
this.child = child;
this.change = change;
index = -1;
this.key = key;
}
/// <summary>
/// Gets the child which will be or has been modified.
/// </summary>
/// <remarks><p>This property is <code>null</code> for <see cref="System.Json.JsonValueChange.Clear"/> event types
/// raised by <see cref="System.Json.JsonValue"/> instances.</p>
/// <p>For <see cref="System.Json.JsonValueChange">Replace</see> events, this property contains the new value in
/// the <see cref="System.Json.JsonValue.Changing"/> event, and the old value (the one being replaced) in the
/// <see cref="System.Json.JsonValue.Changed"/> event.</p></remarks>
public JsonValue Child
{
get { return child; }
}
/// <summary>
/// Gets the type of change.
/// </summary>
public JsonValueChange Change
{
get { return change; }
}
/// <summary>
/// Gets the index in the <see cref="System.Json.JsonArray"/> where the change happened, or
/// <code>-1</code> if the change happened in a <see cref="System.Json.JsonValue"/> of a different type.
/// </summary>
public int Index
{
get { return index; }
}
/// <summary>
/// Gets the key in the <see cref="System.Json.JsonObject"/> where the change happened, or
/// <code>null</code> if the change happened in a <see cref="System.Json.JsonValue"/> of a different type.
/// </summary>
/// <remarks>This property can also be <code>null</code> if the event type is
/// <see cref="System.Json.JsonValueChange">Clear</see>.</remarks>
public string Key
{
get { return key; }
}
}
}

Просмотреть файл

@ -1,383 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Dynamic;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Serialization.Json;
namespace System.Json
{
/// <summary>
/// This class provides dynamic behavior support for the JsonValue types.
/// </summary>
internal class JsonValueDynamicMetaObject : DynamicMetaObject
{
private static readonly MethodInfo _getValueByIndexMethodInfo = typeof(JsonValue).GetMethod("GetValue", new Type[] { typeof(int) });
private static readonly MethodInfo _getValueByKeyMethodInfo = typeof(JsonValue).GetMethod("GetValue", new Type[] { typeof(string) });
private static readonly MethodInfo _setValueByIndexMethodInfo = typeof(JsonValue).GetMethod("SetValue", new Type[] { typeof(int), typeof(object) });
private static readonly MethodInfo _setValueByKeyMethodInfo = typeof(JsonValue).GetMethod("SetValue", new Type[] { typeof(string), typeof(object) });
private static readonly MethodInfo _castValueMethodInfo = typeof(JsonValue).GetMethod("CastValue", new Type[] { typeof(JsonValue) });
private static readonly MethodInfo _changeTypeMethodInfo = typeof(Convert).GetMethod("ChangeType", new Type[] { typeof(object), typeof(Type) });
/// <summary>
/// Class constructor.
/// </summary>
/// <param name="parameter">The expression representing this <see cref="DynamicMetaObject"/> during the dynamic binding process.</param>
/// <param name="value">The runtime value represented by the <see cref="DynamicMetaObject"/>.</param>
internal JsonValueDynamicMetaObject(Expression parameter, JsonValue value)
: base(parameter, BindingRestrictions.Empty, value)
{
}
/// <summary>
/// Gets the default binding restrictions for this type.
/// </summary>
private BindingRestrictions DefaultRestrictions
{
get { return BindingRestrictions.GetTypeRestriction(Expression, LimitType); }
}
/// <summary>
/// Implements dynamic cast for JsonValue types.
/// </summary>
/// <param name="binder">An instance of the <see cref="ConvertBinder"/> that represents the details of the dynamic operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public override DynamicMetaObject BindConvert(ConvertBinder binder)
{
if (binder == null)
{
throw new ArgumentNullException("binder");
}
Expression expression = Expression;
bool implicitCastSupported =
binder.Type.IsAssignableFrom(LimitType) ||
binder.Type == typeof(IEnumerable<KeyValuePair<string, JsonValue>>) ||
binder.Type == typeof(IDynamicMetaObjectProvider) ||
binder.Type == typeof(object);
if (!implicitCastSupported)
{
if (JsonValue.IsSupportedExplicitCastType(binder.Type))
{
Expression instance = Expression.Convert(Expression, LimitType);
expression = Expression.Call(_castValueMethodInfo.MakeGenericMethod(binder.Type), new Expression[] { instance });
}
else
{
string exceptionMessage = RS.Format(Properties.Resources.CannotCastJsonValue, LimitType.FullName, binder.Type.FullName);
expression = Expression.Throw(Expression.Constant(new InvalidCastException(exceptionMessage)), typeof(object));
}
}
expression = Expression.Convert(expression, binder.Type);
return new DynamicMetaObject(expression, DefaultRestrictions);
}
/// <summary>
/// Implements setter for dynamic indexer by index (JsonArray)
/// </summary>
/// <param name="binder">An instance of the <see cref="GetIndexBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the get index operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes)
{
if (binder == null)
{
throw new ArgumentNullException("binder");
}
if (indexes == null)
{
throw new ArgumentNullException("indexes");
}
Expression indexExpression;
if (!JsonValueDynamicMetaObject.TryGetIndexExpression(indexes, out indexExpression))
{
return new DynamicMetaObject(indexExpression, DefaultRestrictions);
}
MethodInfo methodInfo = indexExpression.Type == typeof(string) ? _getValueByKeyMethodInfo : _getValueByIndexMethodInfo;
Expression[] args = new Expression[] { indexExpression };
return GetMethodMetaObject(methodInfo, args);
}
/// <summary>
/// Implements getter for dynamic indexer by index (JsonArray).
/// </summary>
/// <param name="binder">An instance of the <see cref="SetIndexBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="indexes">An array of <see cref="DynamicMetaObject"/> instances - indexes for the set index operation.</param>
/// <param name="value">The <see cref="DynamicMetaObject"/> representing the value for the set index operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value)
{
if (binder == null)
{
throw new ArgumentNullException("binder");
}
if (indexes == null)
{
throw new ArgumentNullException("indexes");
}
if (value == null)
{
throw new ArgumentNullException("value");
}
Expression indexExpression;
if (!JsonValueDynamicMetaObject.TryGetIndexExpression(indexes, out indexExpression))
{
return new DynamicMetaObject(indexExpression, DefaultRestrictions);
}
MethodInfo methodInfo = indexExpression.Type == typeof(string) ? _setValueByKeyMethodInfo : _setValueByIndexMethodInfo;
Expression[] args = new Expression[] { indexExpression, Expression.Convert(value.Expression, typeof(object)) };
return GetMethodMetaObject(methodInfo, args);
}
/// <summary>
/// Implements getter for dynamic indexer by key (JsonObject).
/// </summary>
/// <param name="binder">An instance of the <see cref="GetMemberBinder"/> that represents the details of the dynamic operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public override DynamicMetaObject BindGetMember(GetMemberBinder binder)
{
if (binder == null)
{
throw new ArgumentNullException("binder");
}
PropertyInfo propInfo = LimitType.GetProperty(binder.Name, BindingFlags.Instance | BindingFlags.Public);
if (propInfo != null)
{
return base.BindGetMember(binder);
}
Expression[] args = new Expression[] { Expression.Constant(binder.Name) };
return GetMethodMetaObject(_getValueByKeyMethodInfo, args);
}
/// <summary>
/// Implements setter for dynamic indexer by key (JsonObject).
/// </summary>
/// <param name="binder">An instance of the <see cref="SetMemberBinder"/> that represents the details of the dynamic operation.</param>
/// <param name="value">The <see cref="DynamicMetaObject"/> representing the value for the set member operation.</param>
/// <returns>The new <see cref="DynamicMetaObject"/> representing the result of the binding.</returns>
public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value)
{
if (binder == null)
{
throw new ArgumentNullException("binder");
}
if (value == null)
{
throw new ArgumentNullException("value");
}
Expression[] args = new Expression[] { Expression.Constant(binder.Name), Expression.Convert(value.Expression, typeof(object)) };
return GetMethodMetaObject(_setValueByKeyMethodInfo, args);
}
/// <summary>
/// Performs the binding of the dynamic invoke member operation.
/// Implemented to support extension methods defined in <see cref="JsonValueExtensions"/> type.
/// </summary>
/// <param name="binder">An instance of the InvokeMemberBinder that represents the details of the dynamic operation.</param>
/// <param name="args">An array of DynamicMetaObject instances - arguments to the invoke member operation.</param>
/// <returns>The new DynamicMetaObject representing the result of the binding.</returns>
public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
{
if (binder == null)
{
throw new ArgumentNullException("binder");
}
if (args == null)
{
throw new ArgumentNullException("args");
}
List<Type> argTypeList = new List<Type>();
for (int idx = 0; idx < args.Length; idx++)
{
argTypeList.Add(args[idx].LimitType);
}
MethodInfo methodInfo = Value.GetType().GetMethod(binder.Name, argTypeList.ToArray());
if (methodInfo == null)
{
argTypeList.Insert(0, typeof(JsonValue));
Type[] argTypes = argTypeList.ToArray();
methodInfo = JsonValueDynamicMetaObject.GetExtensionMethod(typeof(JsonValueExtensions), binder.Name, argTypes);
if (methodInfo != null)
{
Expression thisInstance = Expression.Convert(Expression, LimitType);
Expression[] argsExpression = new Expression[argTypes.Length];
argsExpression[0] = thisInstance;
for (int i = 0; i < args.Length; i++)
{
argsExpression[i + 1] = args[i].Expression;
}
Expression callExpression = Expression.Call(methodInfo, argsExpression);
if (methodInfo.ReturnType == typeof(void))
{
callExpression = Expression.Block(callExpression, Expression.Default(binder.ReturnType));
}
else
{
callExpression = Expression.Convert(Expression.Call(methodInfo, argsExpression), binder.ReturnType);
}
return new DynamicMetaObject(callExpression, DefaultRestrictions);
}
}
return base.BindInvokeMember(binder, args);
}
/// <summary>
/// Returns the enumeration of all dynamic member names.
/// </summary>
/// <returns>An <see cref="IEnumerable{T}"/> of string reprenseting the dynamic member names.</returns>
public override IEnumerable<string> GetDynamicMemberNames()
{
JsonValue jsonValue = Value as JsonValue;
if (jsonValue != null)
{
List<string> names = new List<string>();
foreach (KeyValuePair<string, JsonValue> pair in jsonValue)
{
names.Add(pair.Key);
}
return names;
}
return base.GetDynamicMemberNames();
}
/// <summary>
/// Gets a <see cref="MethodInfo"/> instance for the specified method name in the specified type.
/// </summary>
/// <param name="extensionProviderType">The extension provider type.</param>
/// <param name="methodName">The name of the method to get the info for.</param>
/// <param name="argTypes">The types of the method arguments.</param>
/// <returns>A <see cref="MethodInfo"/>instance or null if the method cannot be resolved.</returns>
private static MethodInfo GetExtensionMethod(Type extensionProviderType, string methodName, Type[] argTypes)
{
MethodInfo methodInfo = null;
MethodInfo[] methods = extensionProviderType.GetMethods();
foreach (MethodInfo info in methods)
{
if (info.Name == methodName)
{
methodInfo = info;
if (!info.IsGenericMethodDefinition)
{
bool paramsMatch = true;
ParameterInfo[] args = methodInfo.GetParameters();
if (args.Length == argTypes.Length)
{
for (int idx = 0; idx < args.Length; idx++)
{
if (!args[idx].ParameterType.IsAssignableFrom(argTypes[idx]))
{
paramsMatch = false;
break;
}
}
if (paramsMatch)
{
break;
}
}
}
}
}
return methodInfo;
}
/// <summary>
/// Attempts to get an expression for an index parameter.
/// </summary>
/// <param name="indexes">The operation indexes parameter.</param>
/// <param name="expression">A <see cref="Expression"/> to be initialized to the index expression if the operation is successful, otherwise an error expression.</param>
/// <returns>true the operation is successful, false otherwise.</returns>
private static bool TryGetIndexExpression(DynamicMetaObject[] indexes, out Expression expression)
{
if (indexes.Length == 1 && indexes[0] != null && indexes[0].Value != null)
{
DynamicMetaObject index = indexes[0];
Type indexType = indexes[0].Value.GetType();
switch (Type.GetTypeCode(indexType))
{
case TypeCode.Char:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Byte:
case TypeCode.SByte:
Expression argExp = Expression.Convert(index.Expression, typeof(object));
Expression typeExp = Expression.Constant(typeof(int));
expression = Expression.Convert(Expression.Call(_changeTypeMethodInfo, new Expression[] { argExp, typeExp }), typeof(int));
return true;
case TypeCode.Int32:
case TypeCode.String:
expression = index.Expression;
return true;
}
expression = Expression.Throw(Expression.Constant(new ArgumentException(RS.Format(Properties.Resources.InvalidIndexType, indexType))), typeof(object));
return false;
}
expression = Expression.Throw(Expression.Constant(new ArgumentException(Properties.Resources.NonSingleNonNullIndexNotSupported)), typeof(object));
return false;
}
/// <summary>
/// Gets a <see cref="DynamicMetaObject"/> for a method call.
/// </summary>
/// <param name="methodInfo">Info for the method to be performed.</param>
/// <param name="args">expression array representing the method arguments</param>
/// <returns>A meta object for the method call.</returns>
private DynamicMetaObject GetMethodMetaObject(MethodInfo methodInfo, Expression[] args)
{
Expression instance = Expression.Convert(Expression, LimitType);
Expression methodCall = Expression.Call(instance, methodInfo, args);
BindingRestrictions restrictions = DefaultRestrictions;
DynamicMetaObject metaObj = new DynamicMetaObject(methodCall, restrictions);
return metaObj;
}
}
}

Просмотреть файл

@ -1,37 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
namespace System.Json
{
/// <summary>
/// This class extends the funcionality of the <see cref="JsonValue"/> type for better Linq support .
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Linq is a technical name.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static class JsonValueLinqExtensions
{
/// <summary>
/// Extension method for creating a <see cref="JsonValue"/> from an <see cref="IEnumerable{T}"/> collection of <see cref="JsonValue"/> types.
/// </summary>
/// <param name="items">The enumerable instance.</param>
/// <returns>A <see cref="JsonArray"/> created from the specified items.</returns>
public static JsonArray ToJsonArray(this IEnumerable<JsonValue> items)
{
return new JsonArray(items);
}
/// <summary>
/// Extension method for creating a <see cref="JsonValue"/> from an <see cref="IEnumerable{T}"/> collection of <see cref="KeyValuePair{K,V}"/> of <see cref="String"/> and <see cref="JsonValue"/> types.
/// </summary>
/// <param name="items">The enumerable instance.</param>
/// <returns>A <see cref="JsonValue"/> created from the specified items.</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "JsonValue implements the nested type in param.")]
public static JsonObject ToJsonObject(this IEnumerable<KeyValuePair<string, JsonValue>> items)
{
return new JsonObject(items);
}
}
}

Просмотреть файл

@ -1,48 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace System.Json
{
/// <summary>
/// Struct that wraps values which cause JIT compilation at runtime.
/// This Struct is added to solve the FxCop warning CA908 in JsonObject.cs.
/// </summary>
/// <typeparam name="T">Wrapped type.</typeparam>
internal struct NGenWrapper<T>
{
/// <summary>
/// Value of type T which represents the actual data which is currently in hold.
/// </summary>
public T Value;
/// <summary>
/// Creates an instance of the <see cref="System.Json.NGenWrapper{T}"/> class
/// </summary>
/// <param name="value">The wrapped object of T</param>
public NGenWrapper(T value)
{
Value = value;
}
/// <summary>
/// Cast operator from <see cref="System.Json.NGenWrapper{T}"/> to <typeparamref name="T"/>
/// </summary>
/// <param name="value">Object in type <see cref="System.Json.NGenWrapper{T}"/></param>
/// <returns>Object in type <typeparamref name="T">The wrapped element type</typeparamref></returns>
/// <typeparamref name="T">The wrapped element type</typeparamref>
public static implicit operator T(NGenWrapper<T> value)
{
return value.Value;
}
/// <summary>
/// Cast operator from <typeparamref name="T"/> to <see cref="System.Json.NGenWrapper{T}"/>
/// </summary>
/// <param name="value">Object in type <typeparamref name="T"/></param>
/// <returns>Object in type <see cref="System.Json.NGenWrapper{T}"/></returns>
/// <typeparamref name="T">The wrapped element type</typeparamref>
public static implicit operator NGenWrapper<T>(T value)
{
return new NGenWrapper<T>(value);
}
}
}

Просмотреть файл

@ -1,12 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("System.Json")]
[assembly: AssemblyDescription("")]
[assembly: Guid("6fd72360-ebfc-4097-96fa-2ee418c04f7b")]

216
src/System.Json/Properties/Resources.Designer.cs сгенерированный
Просмотреть файл

@ -1,216 +0,0 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.239
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace System.Json.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("System.Json.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to The argument &apos;{0}&apos; must be greater than or equal to {1}..
/// </summary>
internal static string ArgumentMustBeGreaterThanOrEqualTo {
get {
return ResourceManager.GetString("ArgumentMustBeGreaterThanOrEqualTo", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to cast object of type &apos;{0}&apos; to type &apos;{1}&apos;..
/// </summary>
internal static string CannotCastJsonValue {
get {
return ResourceManager.GetString("CannotCastJsonValue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to CannotReadAsType=Cannot read &apos;{0}&apos; as &apos;{1}&apos; type..
/// </summary>
internal static string CannotReadAsType {
get {
return ResourceManager.GetString("CannotReadAsType", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot read JsonPrimitive value &apos;{0}&apos; as &apos;{1}&apos;..
/// </summary>
internal static string CannotReadPrimitiveAsType {
get {
return ResourceManager.GetString("CannotReadPrimitiveAsType", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &apos;{0}&apos; does not contain a definition for property &apos;{1}&apos;..
/// </summary>
internal static string DynamicPropertyNotDefined {
get {
return ResourceManager.GetString("DynamicPropertyNotDefined", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The input source is not correctly formatted..
/// </summary>
internal static string IncorrectJsonFormat {
get {
return ResourceManager.GetString("IncorrectJsonFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &apos;{0}&apos; type indexer is not supported on JsonValue of &apos;JsonType.{1}&apos; type..
/// </summary>
internal static string IndexerNotSupportedOnJsonType {
get {
return ResourceManager.GetString("IndexerNotSupportedOnJsonType", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot convert null to &apos;{0}&apos; because it is a non-nullable value type..
/// </summary>
internal static string InvalidCastNonNullable {
get {
return ResourceManager.GetString("InvalidCastNonNullable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot cast JsonPrimitive value &apos;{0}&apos; as &apos;{1}&apos;. It is not in a valid date format..
/// </summary>
internal static string InvalidDateFormat {
get {
return ResourceManager.GetString("InvalidDateFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid &apos;{0}&apos; index type; only &apos;System.String&apos; and non-negative &apos;System.Int32&apos; types are supported..
/// </summary>
internal static string InvalidIndexType {
get {
return ResourceManager.GetString("InvalidIndexType", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid JSON primitive: {0}..
/// </summary>
internal static string InvalidJsonPrimitive {
get {
return ResourceManager.GetString("InvalidJsonPrimitive", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot cast &apos;{0}&apos; value &apos;{1}.{2}&apos; as a type of &apos;{3}&apos;. The provided string is not a valid relative or absolute &apos;{3}&apos;..
/// </summary>
internal static string InvalidUriFormat {
get {
return ResourceManager.GetString("InvalidUriFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An empty string cannot be parsed as JSON..
/// </summary>
internal static string JsonStringCannotBeEmpty {
get {
return ResourceManager.GetString("JsonStringCannotBeEmpty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Null index or multidimensional indexing is not supported by this indexer; use &apos;System.Int32&apos; or &apos;System.String&apos; for array and object indexing respectively..
/// </summary>
internal static string NonSingleNonNullIndexNotSupported {
get {
return ResourceManager.GetString("NonSingleNonNullIndexNotSupported", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot cast JsonPrimitive value &apos;{0}&apos; as &apos;{1}&apos;. The value is either too large or too small for the specified CLR type..
/// </summary>
internal static string OverflowReadAs {
get {
return ResourceManager.GetString("OverflowReadAs", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Object type not supported..
/// </summary>
internal static string TypeNotSupported {
get {
return ResourceManager.GetString("TypeNotSupported", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Operation not supported on JsonValue instances of &apos;JsonType.Default&apos; type..
/// </summary>
internal static string UseOfDefaultNotAllowed {
get {
return ResourceManager.GetString("UseOfDefaultNotAllowed", resourceCulture);
}
}
}
}

Просмотреть файл

@ -1,171 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="ArgumentMustBeGreaterThanOrEqualTo" xml:space="preserve">
<value>The argument '{0}' must be greater than or equal to {1}.</value>
</data>
<data name="CannotCastJsonValue" xml:space="preserve">
<value>Unable to cast object of type '{0}' to type '{1}'.</value>
</data>
<data name="CannotReadAsType" xml:space="preserve">
<value>CannotReadAsType=Cannot read '{0}' as '{1}' type.</value>
</data>
<data name="CannotReadPrimitiveAsType" xml:space="preserve">
<value>Cannot read JsonPrimitive value '{0}' as '{1}'.</value>
</data>
<data name="DynamicPropertyNotDefined" xml:space="preserve">
<value>'{0}' does not contain a definition for property '{1}'.</value>
</data>
<data name="IncorrectJsonFormat" xml:space="preserve">
<value>The input source is not correctly formatted.</value>
</data>
<data name="IndexerNotSupportedOnJsonType" xml:space="preserve">
<value>'{0}' type indexer is not supported on JsonValue of 'JsonType.{1}' type.</value>
</data>
<data name="InvalidCastNonNullable" xml:space="preserve">
<value>Cannot convert null to '{0}' because it is a non-nullable value type.</value>
</data>
<data name="InvalidDateFormat" xml:space="preserve">
<value>Cannot cast JsonPrimitive value '{0}' as '{1}'. It is not in a valid date format.</value>
</data>
<data name="InvalidIndexType" xml:space="preserve">
<value>Invalid '{0}' index type; only 'System.String' and non-negative 'System.Int32' types are supported.</value>
</data>
<data name="InvalidJsonPrimitive" xml:space="preserve">
<value>Invalid JSON primitive: {0}.</value>
</data>
<data name="InvalidUriFormat" xml:space="preserve">
<value>Cannot cast '{0}' value '{1}.{2}' as a type of '{3}'. The provided string is not a valid relative or absolute '{3}'.</value>
</data>
<data name="JsonStringCannotBeEmpty" xml:space="preserve">
<value>An empty string cannot be parsed as JSON.</value>
</data>
<data name="NonSingleNonNullIndexNotSupported" xml:space="preserve">
<value>Null index or multidimensional indexing is not supported by this indexer; use 'System.Int32' or 'System.String' for array and object indexing respectively.</value>
</data>
<data name="OverflowReadAs" xml:space="preserve">
<value>Cannot cast JsonPrimitive value '{0}' as '{1}'. The value is either too large or too small for the specified CLR type.</value>
</data>
<data name="TypeNotSupported" xml:space="preserve">
<value>Object type not supported.</value>
</data>
<data name="UseOfDefaultNotAllowed" xml:space="preserve">
<value>Operation not supported on JsonValue instances of 'JsonType.Default' type.</value>
</data>
</root>

Просмотреть файл

@ -1,12 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Globalization;
internal static class RS
{
public static string Format(string format, params object[] args)
{
return String.Format(CultureInfo.CurrentCulture, format, args);
}
}

Просмотреть файл

@ -1,198 +0,0 @@
<StyleCopSettings Version="4.3">
<!-- Files in this SourceFileList are excluded from DocumentationRules only -->
<SourceFileList>
<Settings>
<GlobalSettings>
<StringProperty Name="MergeSettingsFiles">Merge</StringProperty>
</GlobalSettings>
<Analyzers>
<Analyzer AnalyzerId="Microsoft.StyleCop.CSharp.DocumentationRules">
<Rules>
<Rule Name="ElementsMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="PartialElementsMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="EnumerationItemsMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="DocumentationMustContainValidXml">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementDocumentationMustHaveSummary">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="PartialElementDocumentationMustHaveSummary">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementDocumentationMustHaveSummaryText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="PartialElementDocumentationMustHaveSummaryText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementDocumentationMustNotHaveDefaultSummary">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementParametersMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementParameterDocumentationMustMatchElementParameters">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementParameterDocumentationMustDeclareParameterName">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementParameterDocumentationMustHaveText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementReturnValueMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementReturnValueDocumentationMustHaveText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="VoidReturnValueMustNotBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="GenericTypeParametersMustBeDocumented">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="GenericTypeParametersMustBeDocumentedPartialClass">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="GenericTypeParameterDocumentationMustMatchTypeParameters">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="GenericTypeParameterDocumentationMustDeclareParameterName">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="GenericTypeParameterDocumentationMustHaveText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="PropertySummaryDocumentationMustMatchAccessors">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="PropertySummaryDocumentationMustOmitSetAccessorWithRestrictedAccess">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ElementDocumentationMustNotBeCopiedAndPasted">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="SingleLineCommentsMustNotUseDocumentationStyleSlashes">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="DocumentationTextMustNotBeEmpty">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="DocumentationTextMustContainWhitespace">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="DocumentationMustMeetCharacterPercentage">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="DocumentationTextMustMeetMinimumCharacterLength">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="IncludedDocumentationXPathDoesNotExist">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="IncludeNodeDoesNotContainValidFileAndPath">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FileMustHaveHeader">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FileHeaderMustShowCopyright">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FileHeaderMustHaveCopyrightText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
</Rules>
<AnalyzerSettings />
</Analyzer>
</Analyzers>
</Settings>
<SourceFile>JXmlToJsonValueConverter.cs</SourceFile>
<SourceFile>JsonPrimitive.cs</SourceFile>
<SourceFile>JsonObject.cs</SourceFile>
<SourceFile>JsonValue.cs</SourceFile>
<SourceFile>JsonValueExtensions.cs</SourceFile>
</SourceFileList>
</StyleCopSettings>

Просмотреть файл

@ -1,95 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\tools\WebStack.settings.targets" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<CodeAnalysis Condition=" '$(CodeAnalysis)' == '' ">false</CodeAnalysis>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{F0441BE9-BDC0-4629-BE5A-8765FFAA2481}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>System.Json</RootNamespace>
<AssemblyName>System.Json</AssemblyName>
<TargetFrameworkProfile Condition="'$(TargetFrameworkVersion)' != 'v4.5'">Client</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\..\bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;ASPNETMVC</DefineConstants>
<CodeAnalysisRuleSet>..\Strict.ruleset</CodeAnalysisRuleSet>
<DocumentationFile>$(OutputPath)\$(AssemblyName).xml</DocumentationFile>
<NoWarn>1591</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\..\bin\Release\</OutputPath>
<DefineConstants>TRACE;ASPNETMVC</DefineConstants>
<CodeAnalysisRuleSet>..\Strict.ruleset</CodeAnalysisRuleSet>
<RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>
<DocumentationFile>$(OutputPath)\$(AssemblyName).xml</DocumentationFile>
<NoWarn>1591</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'CodeCoverage|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>..\..\bin\CodeCoverage\</OutputPath>
<DefineConstants>TRACE;DEBUG;CODE_COVERAGE;ASPNETMVC</DefineConstants>
<DebugType>full</DebugType>
<CodeAnalysisRuleSet>..\Strict.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\CommonAssemblyInfo.cs">
<Link>Properties\CommonAssemblyInfo.cs</Link>
</Compile>
<Compile Include="..\TransparentCommonAssemblyInfo.cs">
<Link>Properties\TransparentCommonAssemblyInfo.cs</Link>
</Compile>
<Compile Include="GlobalSuppressions.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="JsonArray.cs" />
<Compile Include="JsonObject.cs" />
<Compile Include="JsonPrimitive.cs" />
<Compile Include="JsonType.cs" />
<Compile Include="JsonValue.cs" />
<Compile Include="JsonValueChange.cs" />
<Compile Include="JsonValueChangeEventArgs.cs" />
<Compile Include="JsonValueDynamicMetaObject.cs" />
<Compile Include="JsonValueLinqExtensions.cs" />
<Compile Include="JXmlToJsonValueConverter.cs" />
<Compile Include="NGenWrapper.cs" />
<Compile Include="Extensions\JsonValueExtensions.cs" />
<Compile Include="RS.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<CodeAnalysisDictionary Include="..\CodeAnalysisDictionary.xml">
<Link>CodeAnalysisDictionary.xml</Link>
</CodeAnalysisDictionary>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

Просмотреть файл

@ -1,12 +1,13 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
namespace System.Json
namespace Microsoft.TestCommon
{
/// <summary>
/// Settings used by the <see cref="InstanceCreator"/> class.
@ -166,7 +167,7 @@ namespace System.Json
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="DateTime"/> type.</returns>
public static System.DateTime CreateInstanceOfDateTime(Random rndGen)
public static DateTime CreateInstanceOfDateTime(Random rndGen)
{
long temp = CreateInstanceOfInt64(rndGen);
temp = Math.Abs(temp);
@ -215,7 +216,7 @@ namespace System.Json
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="DateTimeOffset"/> type.</returns>
public static System.DateTimeOffset CreateInstanceOfDateTimeOffset(Random rndGen)
public static DateTimeOffset CreateInstanceOfDateTimeOffset(Random rndGen)
{
DateTime temp = CreateInstanceOfDateTime(rndGen);
temp = DateTime.SpecifyKind(temp, DateTimeKind.Unspecified);
@ -274,7 +275,7 @@ namespace System.Json
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="Guid"/> type.</returns>
public static System.Guid CreateInstanceOfGuid(Random rndGen)
public static Guid CreateInstanceOfGuid(Random rndGen)
{
byte[] temp = new byte[16];
rndGen.NextBytes(temp);
@ -353,7 +354,6 @@ namespace System.Json
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="SByte"/> type.</returns>
[CLSCompliant(false)]
public static sbyte CreateInstanceOfSByte(Random rndGen)
{
byte[] rndValue = new byte[1];
@ -505,7 +505,6 @@ namespace System.Json
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="UInt16"/> type.</returns>
[CLSCompliant(false)]
public static ushort CreateInstanceOfUInt16(Random rndGen)
{
byte[] rndValue = new byte[2];
@ -525,7 +524,6 @@ namespace System.Json
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="UInt32"/> type.</returns>
[CLSCompliant(false)]
public static uint CreateInstanceOfUInt32(Random rndGen)
{
byte[] rndValue = new byte[4];
@ -545,7 +543,6 @@ namespace System.Json
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="UInt64"/> type.</returns>
[CLSCompliant(false)]
public static ulong CreateInstanceOfUInt64(Random rndGen)
{
byte[] rndValue = new byte[8];
@ -565,7 +562,7 @@ namespace System.Json
/// </summary>
/// <param name="rndGen">A <see cref="Random"/> used to create the instance.</param>
/// <returns>An instance of the <see cref="Uri"/> type.</returns>
public static System.Uri CreateInstanceOfUri(Random rndGen)
public static Uri CreateInstanceOfUri(Random rndGen)
{
Uri result;
UriKind kind;

Просмотреть файл

@ -63,6 +63,7 @@
</ItemGroup>
<ItemGroup>
<Compile Include="EnumHelperTestBase.cs" />
<Compile Include="InstanceCreator.cs" />
<Compile Include="PartialTrustRunner.cs" />
<Compile Include="Platform.cs" />
<Compile Include="PlatformInfo.cs" />

Просмотреть файл

@ -104,10 +104,6 @@
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\System.Json\System.Json.csproj">
<Project>{F0441BE9-BDC0-4629-BE5A-8765FFAA2481}</Project>
<Name>System.Json</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\System.Net.Http.Formatting\System.Net.Http.Formatting.csproj">
<Project>{668E9021-CE84-49D9-98FB-DF125A9FCDB0}</Project>
<Name>System.Net.Http.Formatting</Name>

Просмотреть файл

@ -97,10 +97,6 @@
<Compile Include="TestHelpers.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\System.Json\System.Json.csproj">
<Project>{F0441BE9-BDC0-4629-BE5A-8765FFAA2481}</Project>
<Name>System.Json</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\System.Net.Http.Formatting\System.Net.Http.Formatting.csproj">
<Project>{668E9021-CE84-49D9-98FB-DF125A9FCDB0}</Project>
<Name>System.Net.Http.Formatting</Name>

Просмотреть файл

@ -1,12 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace System.Json
{
internal static class Log
{
public static void Info(string text, params object[] args)
{
Console.WriteLine(text, args);
}
}
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -1,203 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace System.Json
{
internal static class Util
{
public static bool CompareObjects<T>(T o1, T o2) where T : class
{
if ((o1 == null) != (o2 == null))
{
return false;
}
return (o1 == null) || o1.Equals(o2);
}
public static bool CompareNullable<T>(Nullable<T> n1, Nullable<T> n2) where T : struct
{
if (n1.HasValue != n2.HasValue)
{
return false;
}
return (!n1.HasValue) || n1.Value.Equals(n2.Value);
}
public static bool CompareLists<T>(List<T> list1, List<T> list2)
{
if (list1 == null)
{
return list2 == null;
}
if (list2 == null)
{
return false;
}
return CompareArrays(list1.ToArray(), list2.ToArray());
}
public static bool CompareDictionaries<K, V>(Dictionary<K, V> dict1, Dictionary<K, V> dict2)
where K : IComparable
where V : class
{
if (dict1 == null)
{
return dict2 == null;
}
if (dict2 == null)
{
return false;
}
List<K> keys1 = new List<K>(dict1.Keys);
List<K> keys2 = new List<K>(dict2.Keys);
keys1.Sort();
keys2.Sort();
if (!CompareLists<K>(keys1, keys2))
{
return false;
}
foreach (K key in keys1)
{
V value1 = dict1[key];
V value2 = dict2[key];
if (!CompareObjects<V>(value1, value2))
{
return false;
}
}
return true;
}
public static bool CompareArrays(Array array1, Array array2)
{
if (array1 == null)
{
return array2 == null;
}
if (array2 == null || array1.Length != array2.Length)
{
return false;
}
for (int i = 0; i < array1.Length; i++)
{
object o1 = array1.GetValue(i);
object o2 = array2.GetValue(i);
if ((o1 == null) != (o2 == null))
{
return false;
}
if (o1 != null)
{
if ((o1 is Array) && (o2 is Array))
{
if (!CompareArrays((Array)o1, (Array)o2))
{
return false;
}
}
else if (o1 is IEnumerable && o2 is IEnumerable)
{
if (!CompareArrays(ToObjectArray((IEnumerable)o1), ToObjectArray((IEnumerable)o2)))
{
return false;
}
}
else
{
if (!o1.Equals(o2))
{
return false;
}
}
}
}
return true;
}
public static int ComputeArrayHashCode(Array array)
{
if (array == null)
{
return 0;
}
int result = 0;
result += array.Length;
for (int i = 0; i < array.Length; i++)
{
object o = array.GetValue(i);
if (o != null)
{
if (o is Array)
{
result ^= ComputeArrayHashCode((Array)o);
}
else if (o is Enumerable)
{
result ^= ComputeArrayHashCode(ToObjectArray((IEnumerable)o));
}
else
{
result ^= o.GetHashCode();
}
}
}
return result;
}
public static string EscapeString(object obj)
{
StringBuilder sb = new StringBuilder();
if (obj == null)
{
return "<<null>>";
}
else
{
string str = obj.ToString();
for (int i = 0; i < str.Length; i++)
{
char c = str[i];
if (c < ' ' || c > '~')
{
sb.AppendFormat("\\u{0:X4}", (int)c);
}
else
{
sb.Append(c);
}
}
}
return sb.ToString();
}
static object[] ToObjectArray(IEnumerable enumerable)
{
List<object> result = new List<object>();
foreach (var item in enumerable)
{
result.Add(item);
}
return result.ToArray();
}
}
}

Просмотреть файл

@ -1,992 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Json
{
/// <summary>
/// Functional tests for the JsonObject class.
/// </summary>
public class JObjectFunctionalTest
{
static int iterationCount = 500;
static int arrayLength = 10;
/// <summary>
/// Validates round-trip of a JsonArray containing both primitives and objects.
/// </summary>
[Fact]
public void MixedJsonTypeFunctionalTest()
{
bool oldValue = CreatorSettings.CreateDateTimeWithSubMilliseconds;
CreatorSettings.CreateDateTimeWithSubMilliseconds = false;
try
{
int seed = 1;
for (int i = 0; i < iterationCount; i++)
{
seed++;
Log.Info("Seed: {0}", seed);
Random rndGen = new Random(seed);
JsonArray sourceJson = new JsonArray(new List<JsonValue>()
{
PrimitiveCreator.CreateInstanceOfBoolean(rndGen),
PrimitiveCreator.CreateInstanceOfByte(rndGen),
PrimitiveCreator.CreateInstanceOfDateTime(rndGen),
PrimitiveCreator.CreateInstanceOfDateTimeOffset(rndGen),
PrimitiveCreator.CreateInstanceOfDecimal(rndGen),
PrimitiveCreator.CreateInstanceOfDouble(rndGen),
PrimitiveCreator.CreateInstanceOfInt16(rndGen),
PrimitiveCreator.CreateInstanceOfInt32(rndGen),
PrimitiveCreator.CreateInstanceOfInt64(rndGen),
PrimitiveCreator.CreateInstanceOfSByte(rndGen),
PrimitiveCreator.CreateInstanceOfSingle(rndGen),
PrimitiveCreator.CreateInstanceOfString(rndGen),
PrimitiveCreator.CreateInstanceOfUInt16(rndGen),
PrimitiveCreator.CreateInstanceOfUInt32(rndGen),
PrimitiveCreator.CreateInstanceOfUInt64(rndGen),
new JsonObject(new Dictionary<string, JsonValue>()
{
{ "Boolean", PrimitiveCreator.CreateInstanceOfBoolean(rndGen) },
{ "Byte", PrimitiveCreator.CreateInstanceOfByte(rndGen) },
{ "DateTime", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) },
{ "DateTimeOffset", PrimitiveCreator.CreateInstanceOfDateTimeOffset(rndGen) },
{ "Decimal", PrimitiveCreator.CreateInstanceOfDecimal(rndGen) },
{ "Double", PrimitiveCreator.CreateInstanceOfDouble(rndGen) },
{ "Int16", PrimitiveCreator.CreateInstanceOfInt16(rndGen) },
{ "Int32", PrimitiveCreator.CreateInstanceOfInt32(rndGen) },
{ "Int64", PrimitiveCreator.CreateInstanceOfInt64(rndGen) },
{ "SByte", PrimitiveCreator.CreateInstanceOfSByte(rndGen) },
{ "Single", PrimitiveCreator.CreateInstanceOfSingle(rndGen) },
{ "String", PrimitiveCreator.CreateInstanceOfString(rndGen) },
{ "UInt16", PrimitiveCreator.CreateInstanceOfUInt16(rndGen) },
{ "UInt32", PrimitiveCreator.CreateInstanceOfUInt32(rndGen) },
{ "UInt64", PrimitiveCreator.CreateInstanceOfUInt64(rndGen) }
})
});
JsonArray newJson = (JsonArray)JsonValue.Parse(sourceJson.ToString());
Assert.True(JsonValueVerifier.Compare(sourceJson, newJson));
}
}
finally
{
CreatorSettings.CreateDateTimeWithSubMilliseconds = oldValue;
}
}
/// <summary>
/// Tests for the <see cref="System.Json.JsonArray.CopyTo"/> method.
/// </summary>
[Fact]
public void JsonArrayCopytoFunctionalTest()
{
int seed = 1;
for (int i = 0; i < iterationCount / 10; i++)
{
seed++;
Log.Info("Seed: {0}", seed);
Random rndGen = new Random(seed);
bool retValue = true;
JsonArray sourceJson = SpecialJsonValueHelper.CreatePrePopulatedJsonArray(seed, arrayLength);
JsonValue[] destJson = new JsonValue[arrayLength];
sourceJson.CopyTo(destJson, 0);
for (int k = 0; k < destJson.Length; k++)
{
if (destJson[k] != sourceJson[k])
{
retValue = false;
}
}
Assert.True(retValue, "[JsonArrayCopytoFunctionalTest] JsonArray.CopyTo() failed to function properly. destJson.GetLength(0) = " + destJson.GetLength(0));
}
}
/// <summary>
/// Tests for add and remove methods in the <see cref="System.Json.JsonArray"/> class.
/// </summary>
[Fact]
public void JsonArrayAddRemoveFunctionalTest()
{
int seed = 1;
for (int i = 0; i < iterationCount / 10; i++)
{
seed++;
Log.Info("Seed: {0}", seed);
Random rndGen = new Random(seed);
bool retValue = true;
JsonArray sourceJson = SpecialJsonValueHelper.CreatePrePopulatedJsonArray(seed, arrayLength);
JsonValue[] cloneJson = SpecialJsonValueHelper.CreatePrePopulatedJsonValueArray(seed, 3);
// JsonArray.AddRange(JsonValue[])
sourceJson.AddRange(cloneJson);
if (sourceJson.Count != arrayLength + cloneJson.Length)
{
Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.AddRange(JsonValue[]) failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.AddRange(JsonValue[]) passed test.");
}
// JsonArray.RemoveAt(int)
int count = sourceJson.Count;
for (int j = 0; j < count; j++)
{
sourceJson.RemoveAt(0);
}
if (sourceJson.Count > 0)
{
Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.RemoveAt(int) failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.RemoveAt(int) passed test.");
}
// JsonArray.JsonType
if (sourceJson.JsonType != JsonType.Array)
{
Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.JsonType failed to function properly.");
retValue = false;
}
// JsonArray.Clear()
sourceJson = SpecialJsonValueHelper.CreatePrePopulatedJsonArray(seed, arrayLength);
sourceJson.Clear();
if (sourceJson.Count > 0)
{
Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.Clear() failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.Clear() passed test.");
}
// JsonArray.AddRange(JsonValue)
sourceJson = SpecialJsonValueHelper.CreatePrePopulatedJsonArray(seed, arrayLength);
// adding one additional value to the array
sourceJson.AddRange(SpecialJsonValueHelper.GetRandomJsonPrimitives(seed));
if (sourceJson.Count != arrayLength + 1)
{
Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.AddRange(JsonValue) failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.AddRange(JsonValue) passed test.");
}
// JsonArray.AddRange(IEnumerable<JsonValue> items)
sourceJson = SpecialJsonValueHelper.CreatePrePopulatedJsonArray(seed, arrayLength);
MyJsonValueCollection<JsonValue> myCols = new MyJsonValueCollection<JsonValue>();
myCols.Add(new JsonPrimitive(PrimitiveCreator.CreateInstanceOfUInt32(rndGen)));
string str;
do
{
str = PrimitiveCreator.CreateInstanceOfString(rndGen);
} while (str == null);
myCols.Add(new JsonPrimitive(str));
myCols.Add(new JsonPrimitive(PrimitiveCreator.CreateInstanceOfDateTime(rndGen)));
// adding 3 additional value to the array
sourceJson.AddRange(myCols);
if (sourceJson.Count != arrayLength + 3)
{
Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.AddRange(IEnumerable<JsonValue> items) failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.AddRange(IEnumerable<JsonValue> items) passed test.");
}
// JsonArray[index].set_Item
sourceJson = SpecialJsonValueHelper.CreatePrePopulatedJsonArray(seed, arrayLength);
string temp;
do
{
temp = PrimitiveCreator.CreateInstanceOfString(rndGen);
} while (temp == null);
sourceJson[1] = temp;
if ((string)sourceJson[1] != temp)
{
Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray[index].set_Item failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray[index].set_Item passed test.");
}
// JsonArray.Remove(JsonValue)
count = sourceJson.Count;
for (int j = 0; j < count; j++)
{
sourceJson.Remove(sourceJson[0]);
}
if (sourceJson.Count > 0)
{
Log.Info("[JsonArrayAddRemoveFunctionalTest] JsonArray.Remove(JsonValue) failed to function properly.");
retValue = false;
}
Assert.True(retValue);
}
}
/// <summary>
/// Tests for indexers in the <see cref="System.Json.JsonArray"/> class.
/// </summary>
[Fact]
public void JsonArrayItemsFunctionalTest()
{
int seed = 1;
for (int i = 0; i < iterationCount / 10; i++)
{
seed++;
Log.Info("Seed: {0}", seed);
Random rndGen = new Random(seed);
bool retValue = true;
// JsonArray.Contains(JsonValue)
// JsonArray.IndexOf(JsonValue)
JsonArray sourceJson = SpecialJsonValueHelper.CreatePrePopulatedJsonArray(seed, arrayLength);
for (int j = 0; j < sourceJson.Count; j++)
{
if (!sourceJson.Contains(sourceJson[j]))
{
Log.Info("[JsonArrayItemsFunctionalTest] JsonArray.Contains(JsonValue) failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonArrayItemsFunctionalTest] JsonArray.Contains(JsonValue) passed test.");
}
if (sourceJson.IndexOf(sourceJson[j]) != j)
{
Log.Info("[JsonArrayItemsFunctionalTest] JsonArray.IndexOf(JsonValue) failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonArrayItemsFunctionalTest] JsonArray.IndexOf(JsonValue) passed test.");
}
}
// JsonArray.Insert(int, JsonValue)
JsonValue newItem = SpecialJsonValueHelper.GetRandomJsonPrimitives(seed);
sourceJson.Insert(3, newItem);
if (sourceJson[3] != newItem || sourceJson.Count != arrayLength + 1)
{
Log.Info("[JsonArrayItemsFunctionalTest] JsonArray.Insert(int, JsonValue) failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonArrayItemsFunctionalTest] JsonArray.Insert(int, JsonValue) passed test.");
}
Assert.True(retValue);
}
}
/// <summary>
/// Tests for the CopyTo methods in the <see cref="System.Json.JsonObject"/> class.
/// </summary>
[Fact]
public void JsonObjectCopytoFunctionalTest()
{
int seed = 1;
for (int i = 0; i < iterationCount / 10; i++)
{
seed++;
Log.Info("Seed: {0}", seed);
Random rndGen = new Random(seed);
bool retValue = true;
JsonObject sourceJson = SpecialJsonValueHelper.CreateIndexPopulatedJsonObject(seed, arrayLength);
KeyValuePair<string, JsonValue>[] destJson = new KeyValuePair<string, JsonValue>[arrayLength];
if (sourceJson != null && destJson != null)
{
sourceJson.CopyTo(destJson, 0);
}
else
{
Log.Info("[JsonObjectCopytoFunctionalTest] sourceJson.ToString() = " + sourceJson.ToString());
Log.Info("[JsonObjectCopytoFunctionalTest] destJson.ToString() = " + destJson.ToString());
Assert.False(true, "[JsonObjectCopytoFunctionalTest] failed to create the source JsonObject object.");
return;
}
if (destJson.Length == arrayLength)
{
for (int k = 0; k < destJson.Length; k++)
{
JsonValue temp;
sourceJson.TryGetValue(k.ToString(), out temp);
if (!(temp != null && destJson[k].Value == temp))
{
retValue = false;
}
}
}
else
{
retValue = false;
}
Assert.True(retValue, "[JsonObjectCopytoFunctionalTest] JsonObject.CopyTo() failed to function properly. destJson.GetLength(0) = " + destJson.GetLength(0));
}
}
/// <summary>
/// Tests for the add and remove methods in the <see cref="System.Json.JsonObject"/> class.
/// </summary>
[Fact]
public void JsonObjectAddRemoveFunctionalTest()
{
int seed = 1;
for (int i = 0; i < iterationCount / 10; i++)
{
seed++;
Log.Info("Seed: {0}", seed);
Random rndGen = new Random(seed);
bool retValue = true;
JsonObject sourceJson = SpecialJsonValueHelper.CreateIndexPopulatedJsonObject(seed, arrayLength);
// JsonObject.JsonType
if (sourceJson.JsonType != JsonType.Object)
{
Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonArray.JsonType failed to function properly.");
retValue = false;
}
// JsonObject.Add(KeyValuePair<string, JsonValue> item)
// JsonObject.Add(string key, JsonValue value)
// + various numers below so .AddRange() won't try to add an already existing value
sourceJson.Add(SpecialJsonValueHelper.GetUniqueNonNullInstanceOfString(seed + 3, sourceJson), SpecialJsonValueHelper.GetUniqueValue(seed, sourceJson));
KeyValuePair<string, JsonValue> kvp;
int startingSeed = seed + 1;
do
{
kvp = SpecialJsonValueHelper.CreatePrePopulatedKeyValuePair(startingSeed);
startingSeed++;
}
while (sourceJson.ContainsKey(kvp.Key));
sourceJson.Add(kvp);
do
{
kvp = SpecialJsonValueHelper.CreatePrePopulatedKeyValuePair(startingSeed);
startingSeed++;
}
while (sourceJson.ContainsKey(kvp.Key));
sourceJson.Add(kvp);
if (sourceJson.Count != arrayLength + 3)
{
Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonObject.Add() failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonObject.Add() passed test.");
}
// JsonObject.Clear()
sourceJson.Clear();
if (sourceJson.Count > 0)
{
Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonObject.Clear() failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonObject.Clear() passed test.");
}
// JsonObject.AddRange(IEnumerable<KeyValuePair<string, JsonValue>> items)
sourceJson = SpecialJsonValueHelper.CreateIndexPopulatedJsonObject(seed, arrayLength);
// + various numers below so .AddRange() won't try to add an already existing value
sourceJson.AddRange(SpecialJsonValueHelper.CreatePrePopulatedListofKeyValuePair(seed + 13 + (arrayLength * 2), 5));
if (sourceJson.Count != arrayLength + 5)
{
Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonObject.AddRange(IEnumerable<KeyValuePair<string, JsonValue>> items) failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonObject.AddRange(IEnumerable<KeyValuePair<string, JsonValue>> items) passed test.");
}
// JsonObject.AddRange(params KeyValuePair<string, JsonValue>[] items)
sourceJson = SpecialJsonValueHelper.CreateIndexPopulatedJsonObject(seed, arrayLength);
// + various numers below so .AddRange() won't try to add an already existing value
KeyValuePair<string, JsonValue> item1 = SpecialJsonValueHelper.CreatePrePopulatedKeyValuePair(seed + arrayLength + 41);
KeyValuePair<string, JsonValue> item2 = SpecialJsonValueHelper.CreatePrePopulatedKeyValuePair(seed + arrayLength + 47);
KeyValuePair<string, JsonValue> item3 = SpecialJsonValueHelper.CreatePrePopulatedKeyValuePair(seed + arrayLength + 53);
sourceJson.AddRange(new KeyValuePair<string, JsonValue>[] { item1, item2, item3 });
if (sourceJson.Count != arrayLength + 3)
{
Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonObject.AddRange(params KeyValuePair<string, JsonValue>[] items) failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonObject.AddRange(params KeyValuePair<string, JsonValue>[] items) passed test.");
}
sourceJson.Clear();
// JsonObject.Remove(Key)
sourceJson = SpecialJsonValueHelper.CreateIndexPopulatedJsonObject(seed, arrayLength);
int count = sourceJson.Count;
List<string> keys = new List<string>(sourceJson.Keys);
foreach (string key in keys)
{
sourceJson.Remove(key);
}
if (sourceJson.Count > 0)
{
Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonObject.Remove(Key) failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonObjectAddRemoveFunctionalTest] JsonObject.Remove(Key) passed test.");
}
Assert.True(retValue);
}
}
/// <summary>
/// Tests for the indexers in the <see cref="System.Json.JsonObject"/> class.
/// </summary>
[Fact]
public void JsonObjectItemsFunctionalTest()
{
int seed = 1;
for (int i = 0; i < iterationCount / 10; i++)
{
seed++;
Log.Info("Seed: {0}", seed);
Random rndGen = new Random(seed);
bool retValue = true;
JsonObject sourceJson = SpecialJsonValueHelper.CreateIndexPopulatedJsonObject(seed, arrayLength);
// JsonObject[key].set_Item
sourceJson["1"] = new JsonPrimitive(true);
if (sourceJson["1"].ToString() != "true")
{
Log.Info("[JsonObjectItemsFunctionalTest] JsonObject[key].set_Item failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonObjectItemsFunctionalTest] JsonObject[key].set_Item passed test.");
}
// ICollection<KeyValuePair<string, JsonValue>>.Contains(KeyValuePair<string, JsonValue> item)
KeyValuePair<string, System.Json.JsonValue> kp = new KeyValuePair<string, JsonValue>("5", sourceJson["5"]);
if (!((ICollection<KeyValuePair<string, JsonValue>>)sourceJson).Contains(kp))
{
Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.Contains(KeyValuePair<string, JsonValue> item) failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.Contains(KeyValuePair<string, JsonValue> item) passed test.");
}
// ICollection<KeyValuePair<string, JsonValue>>.IsReadOnly
if (((ICollection<KeyValuePair<string, JsonValue>>)sourceJson).IsReadOnly)
{
Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.IsReadOnly failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.IsReadOnly passed test.");
}
// ICollection<KeyValuePair<string, JsonValue>>.Add(KeyValuePair<string, JsonValue> item)
kp = new KeyValuePair<string, JsonValue>("100", new JsonPrimitive(100));
((ICollection<KeyValuePair<string, JsonValue>>)sourceJson).Add(kp);
if (sourceJson.Count != arrayLength + 1)
{
Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.Add(KeyValuePair<string, JsonValue> item) failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.Add(KeyValuePair<string, JsonValue> item) passed test.");
}
// ICollection<KeyValuePair<string, JsonValue>>.Remove(KeyValuePair<string, JsonValue> item)
((ICollection<KeyValuePair<string, JsonValue>>)sourceJson).Remove(kp);
if (sourceJson.Count != arrayLength)
{
Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.Remove(KeyValuePair<string, JsonValue> item) failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.Remove(KeyValuePair<string, JsonValue> item) passed test.");
}
// ICollection<KeyValuePair<string, JsonValue>>.GetEnumerator()
JsonObject jo = new JsonObject { { "member 1", 123 }, { "member 2", new JsonArray { 1, 2, 3 } } };
List<string> expected = new List<string> { "member 1 - 123", "member 2 - [1,2,3]" };
expected.Sort();
IEnumerator<KeyValuePair<string, JsonValue>> ko = ((ICollection<KeyValuePair<string, JsonValue>>)jo).GetEnumerator();
List<string> actual = new List<string>();
ko.Reset();
ko.MoveNext();
do
{
actual.Add(String.Format("{0} - {1}", ko.Current.Key, ko.Current.Value.ToString()));
Log.Info("added one item: {0}", String.Format("{0} - {1}", ko.Current.Key, ko.Current.Value));
ko.MoveNext();
}
while (ko.Current.Value != null);
actual.Sort();
if (!JsonValueVerifier.CompareStringLists(expected, actual))
{
Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.GetEnumerator() failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.GetEnumerator() passed test.");
}
// JsonObject.Values
sourceJson = SpecialJsonValueHelper.CreateIndexPopulatedJsonObject(seed, arrayLength);
JsonValue[] manyValues = SpecialJsonValueHelper.CreatePrePopulatedJsonValueArray(seed, arrayLength);
JsonObject jov = new JsonObject();
for (int j = 0; j < manyValues.Length; j++)
{
jov.Add("member" + j, manyValues[j]);
}
List<string> expectedList = new List<string>();
foreach (JsonValue v in manyValues)
{
expectedList.Add(v.ToString());
}
expectedList.Sort();
List<string> actualList = new List<string>();
foreach (JsonValue v in jov.Values)
{
actualList.Add(v.ToString());
}
actualList.Sort();
if (!JsonValueVerifier.CompareStringLists(expectedList, actualList))
{
Log.Info("[JsonObjectItemsFunctionalTest] JsonObject.Values failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonObjectItemsFunctionalTest] JsonObject.Values passed test.");
}
for (int j = 0; j < sourceJson.Count; j++)
{
// JsonObject.Contains(Key)
if (!sourceJson.ContainsKey(j.ToString()))
{
Log.Info("[JsonObjectItemsFunctionalTest] JsonObject.Contains(Key) failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonObjectItemsFunctionalTest] JsonObject.Contains(Key) passed test.");
}
// JsonObject.TryGetValue(String, out JsonValue)
JsonValue retJson;
if (!sourceJson.TryGetValue(j.ToString(), out retJson))
{
Log.Info("[JsonObjectItemsFunctionalTest] JsonObject.TryGetValue(String, out JsonValue) failed to function properly.");
retValue = false;
}
else if (retJson != sourceJson[j.ToString()])
{
// JsonObjectthis[string key]
Log.Info("[JsonObjectItemsFunctionalTest] JsonObject[string key] or JsonObject.TryGetValue(String, out JsonValue) failed to function properly.");
retValue = false;
}
else
{
Log.Info("[JsonObjectItemsFunctionalTest] JsonObject.TryGetValue(String, out JsonValue) & JsonObject[string key] passed test.");
}
}
Assert.True(retValue);
}
}
/// <summary>
/// Tests for casting to integer values.
/// </summary>
[Fact]
public void GettingIntegerValueTest()
{
string json = "{\"byte\":160,\"sbyte\":-89,\"short\":12345,\"ushort\":65530," +
"\"int\":1234567890,\"uint\":3000000000,\"long\":1234567890123456," +
"\"ulong\":10000000000000000000}";
Dictionary<string, object> expected = new Dictionary<string, object>();
expected.Add("byte", (byte)160);
expected.Add("sbyte", (sbyte)-89);
expected.Add("short", (short)12345);
expected.Add("ushort", (ushort)65530);
expected.Add("int", (int)1234567890);
expected.Add("uint", (uint)3000000000);
expected.Add("long", (long)1234567890123456L);
expected.Add("ulong", (((ulong)5000000000000000000L) * 2));
JsonObject jo = (JsonObject)JsonValue.Parse(json);
bool success = true;
foreach (string key in jo.Keys)
{
object expectedObj = expected[key];
Log.Info("Testing for type = {0}", key);
try
{
switch (key)
{
case "byte":
Assert.Equal<byte>((byte)expectedObj, (byte)jo[key]);
break;
case "sbyte":
Assert.Equal<sbyte>((sbyte)expectedObj, (sbyte)jo[key]);
break;
case "short":
Assert.Equal<short>((short)expectedObj, (short)jo[key]);
break;
case "ushort":
Assert.Equal<ushort>((ushort)expectedObj, (ushort)jo[key]);
break;
case "int":
Assert.Equal<int>((int)expectedObj, (int)jo[key]);
break;
case "uint":
Assert.Equal<uint>((uint)expectedObj, (uint)jo[key]);
break;
case "long":
Assert.Equal<long>((long)expectedObj, (long)jo[key]);
break;
case "ulong":
Assert.Equal<ulong>((ulong)expectedObj, (ulong)jo[key]);
break;
}
}
catch (InvalidCastException e)
{
Log.Info("Caught InvalidCastException: {0}", e);
success = false;
}
}
Assert.True(success);
}
/// <summary>
/// Tests for casting to floating point values.
/// </summary>
[Fact]
public void GettingFloatingPointValueTest()
{
string json = "{\"float\":1.23,\"double\":1.23e+290,\"decimal\":1234567890.123456789}";
Dictionary<string, object> expected = new Dictionary<string, object>();
expected.Add("float", 1.23f);
expected.Add("double", 1.23e+290);
expected.Add("decimal", 1234567890.123456789m);
JsonObject jo = (JsonObject)JsonValue.Parse(json);
bool success = true;
foreach (string key in jo.Keys)
{
object expectedObj = expected[key];
Log.Info("Testing for type = {0}", key);
try
{
switch (key)
{
case "float":
Assert.Equal<float>((float)expectedObj, (float)jo[key]);
break;
case "double":
Assert.Equal<double>((double)expectedObj, (double)jo[key]);
break;
case "decimal":
Assert.Equal<decimal>((decimal)expectedObj, (decimal)jo[key]);
break;
}
}
catch (InvalidCastException e)
{
Log.Info("Caught InvalidCastException: {0}", e);
success = false;
}
}
Assert.True(success);
}
/// <summary>
/// Negative tests for invalid operations.
/// </summary>
[Fact]
public void TestInvalidOperations()
{
JsonArray ja = new JsonArray { 1, null, "hello" };
JsonObject jo = new JsonObject
{
{ "first", 1 },
{ "second", null },
{ "third", "hello" },
};
JsonPrimitive jp = new JsonPrimitive("hello");
Assert.Throws<InvalidOperationException>(() => "jp[\"hello\"] should fail: " + jp["hello"].ToString());
Assert.Throws<InvalidOperationException>(() => "ja[\"hello\"] should fail: " + ja["hello"].ToString());
Assert.Throws<InvalidOperationException>(() => jp["hello"] = "This shouldn't happen");
Assert.Throws<InvalidOperationException>(() => ja["hello"] = "This shouldn't happen");
Assert.Throws<InvalidOperationException>(() => ("jp[1] should fail: " + jp[1].ToString()));
Assert.Throws<InvalidOperationException>(() => "jo[0] should fail: " + jo[1].ToString());
Assert.Throws<InvalidOperationException>(() => jp[0] = "This shouldn't happen");
Assert.Throws<InvalidOperationException>(() => jo[0] = "This shouldn't happen");
Assert.Throws<InvalidCastException>(() => "(DateTimeOffset)jp[\"hello\"] should fail: " + (DateTimeOffset)jp);
Assert.Throws<InvalidCastException>(() => ("(Char)jp[\"hello\"] should fail: " + (char)jp));
Assert.Throws<InvalidCastException>(() =>
{
short jprim = (short)new JsonPrimitive(false);
});
}
/// <summary>
/// Test for consuming deeply nested object graphs.
/// </summary>
[Fact]
public void TestDeeplyNestedObjectGraph()
{
JsonObject jo = new JsonObject();
JsonObject current = jo;
StringBuilder builderExpected = new StringBuilder();
builderExpected.Append('{');
int depth = 10000;
for (int i = 0; i < depth; i++)
{
JsonObject next = new JsonObject();
string key = i.ToString(CultureInfo.InvariantCulture);
builderExpected.AppendFormat("\"{0}\":{{", key);
current.Add(key, next);
current = next;
}
for (int i = 0; i < depth + 1; i++)
{
builderExpected.Append('}');
}
Assert.Equal(builderExpected.ToString(), jo.ToString());
}
/// <summary>
/// Test for consuming deeply nested array graphs.
/// </summary>
[Fact]
public void TestDeeplyNestedArrayGraph()
{
JsonArray ja = new JsonArray();
JsonArray current = ja;
StringBuilder builderExpected = new StringBuilder();
builderExpected.Append('[');
int depth = 10000;
for (int i = 0; i < depth; i++)
{
JsonArray next = new JsonArray();
builderExpected.Append('[');
current.Add(next);
current = next;
}
for (int i = 0; i < depth + 1; i++)
{
builderExpected.Append(']');
}
Assert.Equal(builderExpected.ToString(), ja.ToString());
}
/// <summary>
/// Test for consuming deeply nested object and array graphs.
/// </summary>
[Fact]
public void TestDeeplyNestedObjectAndArrayGraph()
{
JsonObject jo = new JsonObject();
JsonObject current = jo;
StringBuilder builderExpected = new StringBuilder();
builderExpected.Append('{');
int depth = 10000;
for (int i = 0; i < depth; i++)
{
JsonObject next = new JsonObject();
string key = i.ToString(CultureInfo.InvariantCulture);
builderExpected.AppendFormat("\"{0}\":[{{", key);
current.Add(key, new JsonArray(next));
current = next;
}
for (int i = 0; i < depth; i++)
{
builderExpected.Append("}]");
}
builderExpected.Append('}');
Assert.Equal(builderExpected.ToString(), jo.ToString());
}
/// <summary>
/// Test for calling <see cref="JsonValue.ToString()"/> on the same instance in different threads.
/// </summary>
[Fact]
public void TestConcurrentToString()
{
bool exceptionThrown = false;
bool incorrectValue = false;
JsonObject jo = new JsonObject();
StringBuilder sb = new StringBuilder();
sb.Append('{');
for (int i = 0; i < 100000; i++)
{
if (i > 0)
{
sb.Append(',');
}
string key = i.ToString(CultureInfo.InvariantCulture);
jo.Add(key, i);
sb.AppendFormat("\"{0}\":{0}", key);
}
sb.Append('}');
string expected = sb.ToString();
int numberOfThreads = 5;
Thread[] threads = new Thread[numberOfThreads];
for (int i = 0; i < numberOfThreads; i++)
{
threads[i] = new Thread(new ThreadStart(delegate
{
for (int j = 0; j < 10; j++)
{
try
{
string str = jo.ToString();
if (str != expected)
{
incorrectValue = true;
Log.Info("Value is incorrect");
}
}
catch (Exception e)
{
exceptionThrown = true;
Log.Info("Exception thrown: {0}", e);
}
}
}));
}
for (int i = 0; i < numberOfThreads; i++)
{
threads[i].Start();
}
for (int i = 0; i < numberOfThreads; i++)
{
threads[i].Join();
}
Assert.False(incorrectValue);
Assert.False(exceptionThrown);
}
class MyJsonValueCollection<JsonValue> : System.Collections.Generic.IEnumerable<JsonValue>
{
List<JsonValue> internalList = new List<JsonValue>();
public MyJsonValueCollection()
{
}
public void Add(JsonValue obj)
{
this.internalList.Add(obj);
}
public IEnumerator<JsonValue> GetEnumerator()
{
return this.internalList.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -1,585 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Xunit;
namespace System.Json
{
/// <summary>
/// Tests for round-tripping <see cref="JsonValue"/> instances via JSON strings.
/// </summary>
public class JsonStringRoundTripTests
{
/// <summary>
/// Tests for <see cref="JsonObject"/> round-trip.
/// </summary>
[Fact]
public void ValidJsonObjectRoundTrip()
{
bool oldValue = CreatorSettings.CreateDateTimeWithSubMilliseconds;
CreatorSettings.CreateDateTimeWithSubMilliseconds = false;
try
{
int seed = 1;
Log.Info("Seed: {0}", seed);
Random rndGen = new Random(seed);
JsonObject sourceJson = new JsonObject(new Dictionary<string, JsonValue>()
{
{ "Name", PrimitiveCreator.CreateInstanceOfString(rndGen) },
{ "Age", PrimitiveCreator.CreateInstanceOfInt32(rndGen) },
{ "DateTimeOffset", PrimitiveCreator.CreateInstanceOfDateTimeOffset(rndGen) },
{ "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) }
});
sourceJson.Add("NewItem1", PrimitiveCreator.CreateInstanceOfString(rndGen));
sourceJson.Add(new KeyValuePair<string, JsonValue>("NewItem2", PrimitiveCreator.CreateInstanceOfString(rndGen)));
JsonObject newJson = (JsonObject)JsonValue.Parse(sourceJson.ToString());
newJson.Remove("NewItem1");
sourceJson.Remove("NewItem1");
Assert.False(newJson.ContainsKey("NewItem1"));
Assert.False(!JsonValueVerifier.Compare(sourceJson, newJson));
}
finally
{
CreatorSettings.CreateDateTimeWithSubMilliseconds = oldValue;
}
}
/// <summary>
/// Test for <see cref="JsonPrimitive"/> round-trip created via <see cref="DateTime"/>.
/// </summary>
[Fact]
public void SimpleDateTimeTest()
{
JsonValue jv = DateTime.Now;
JsonValue jv2 = JsonValue.Parse(jv.ToString());
Assert.Equal(jv.ToString(), jv2.ToString());
}
/// <summary>
/// Test for <see cref="JsonPrimitive"/> round-trip created via <see cref="DateTimeOffset"/>.
/// </summary>
[Fact]
public void ValidJsonObjectDateTimeOffsetRoundTrip()
{
int seed = 1;
Log.Info("Seed: {0}", seed);
Random rndGen = new Random(seed);
JsonPrimitive sourceJson = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfDateTimeOffset(rndGen));
JsonPrimitive newJson = (JsonPrimitive)JsonValue.Parse(sourceJson.ToString());
Assert.True(JsonValueVerifier.Compare(sourceJson, newJson));
}
/// <summary>
/// Tests for <see cref="JsonArray"/> round-trip.
/// </summary>
[Fact]
public void ValidJsonArrayRoundTrip()
{
bool oldValue = CreatorSettings.CreateDateTimeWithSubMilliseconds;
CreatorSettings.CreateDateTimeWithSubMilliseconds = false;
try
{
int seed = 1;
Log.Info("Seed: {0}", seed);
Random rndGen = new Random(seed);
JsonArray sourceJson = new JsonArray(new JsonValue[]
{
PrimitiveCreator.CreateInstanceOfBoolean(rndGen),
PrimitiveCreator.CreateInstanceOfByte(rndGen),
PrimitiveCreator.CreateInstanceOfDateTime(rndGen),
PrimitiveCreator.CreateInstanceOfDateTimeOffset(rndGen),
PrimitiveCreator.CreateInstanceOfDecimal(rndGen),
PrimitiveCreator.CreateInstanceOfDouble(rndGen),
PrimitiveCreator.CreateInstanceOfInt16(rndGen),
PrimitiveCreator.CreateInstanceOfInt32(rndGen),
PrimitiveCreator.CreateInstanceOfInt64(rndGen),
PrimitiveCreator.CreateInstanceOfSByte(rndGen),
PrimitiveCreator.CreateInstanceOfSingle(rndGen),
PrimitiveCreator.CreateInstanceOfString(rndGen),
PrimitiveCreator.CreateInstanceOfUInt16(rndGen),
PrimitiveCreator.CreateInstanceOfUInt32(rndGen),
PrimitiveCreator.CreateInstanceOfUInt64(rndGen)
});
JsonArray newJson = (JsonArray)JsonValue.Parse(sourceJson.ToString());
Log.Info("Original JsonArray object is: {0}", sourceJson);
Log.Info("Round-tripped JsonArray object is: {0}", newJson);
Assert.True(JsonValueVerifier.Compare(sourceJson, newJson));
}
finally
{
CreatorSettings.CreateDateTimeWithSubMilliseconds = oldValue;
}
}
/// <summary>
/// Test for <see cref="JsonPrimitive"/> round-trip created via <see cref="String"/>.
/// </summary>
[Fact]
public void ValidPrimitiveStringRoundTrip()
{
Assert.True(this.TestPrimitiveType("String"));
}
/// <summary>
/// Test for <see cref="JsonPrimitive"/> round-trip created via <see cref="DateTime"/>.
/// </summary>
[Fact]
public void ValidPrimitiveDateTimeRoundTrip()
{
bool oldValue = CreatorSettings.CreateDateTimeWithSubMilliseconds;
CreatorSettings.CreateDateTimeWithSubMilliseconds = false;
try
{
Assert.True(this.TestPrimitiveType("DateTime"));
}
finally
{
CreatorSettings.CreateDateTimeWithSubMilliseconds = oldValue;
}
}
/// <summary>
/// Test for <see cref="JsonPrimitive"/> round-trip created via <see cref="Boolean"/>.
/// </summary>
[Fact]
public void ValidPrimitiveBooleanRoundTrip()
{
Assert.True(this.TestPrimitiveType("Boolean"));
}
/// <summary>
/// Test for <see cref="JsonPrimitive"/> round-trip created via <see cref="Byte"/>.
/// </summary>
[Fact]
public void ValidPrimitiveByteRoundTrip()
{
Assert.True(this.TestPrimitiveType("Byte"));
}
/// <summary>
/// Test for <see cref="JsonPrimitive"/> round-trip created via <see cref="Decimal"/>.
/// </summary>
[Fact]
public void ValidPrimitiveDecimalRoundTrip()
{
Assert.True(this.TestPrimitiveType("Decimal"));
}
/// <summary>
/// Test for <see cref="JsonPrimitive"/> round-trip created via <see cref="Double"/>.
/// </summary>
[Fact]
public void ValidPrimitiveDoubleRoundTrip()
{
Assert.True(this.TestPrimitiveType("Double"));
}
/// <summary>
/// Test for <see cref="JsonPrimitive"/> round-trip created via <see cref="Int16"/>.
/// </summary>
[Fact]
public void ValidPrimitiveInt16RoundTrip()
{
Assert.True(this.TestPrimitiveType("Int16"));
}
/// <summary>
/// Test for <see cref="JsonPrimitive"/> round-trip created via <see cref="Int32"/>.
/// </summary>
[Fact]
public void ValidPrimitiveInt32RoundTrip()
{
Assert.True(this.TestPrimitiveType("Int32"));
}
/// <summary>
/// Test for <see cref="JsonPrimitive"/> round-trip created via <see cref="Int64"/>.
/// </summary>
[Fact]
public void ValidPrimitiveInt64RoundTrip()
{
Assert.True(this.TestPrimitiveType("Int64"));
}
/// <summary>
/// Test for <see cref="JsonPrimitive"/> round-trip created via <see cref="SByte"/>.
/// </summary>
[Fact]
public void ValidPrimitiveSByteRoundTrip()
{
Assert.True(this.TestPrimitiveType("SByte"));
}
/// <summary>
/// Test for <see cref="JsonPrimitive"/> round-trip created via <see cref="UInt16"/>.
/// </summary>
[Fact]
public void ValidPrimitiveUInt16RoundTrip()
{
Assert.True(this.TestPrimitiveType("Uint16"));
}
/// <summary>
/// Test for <see cref="JsonPrimitive"/> round-trip created via <see cref="UInt32"/>.
/// </summary>
[Fact]
public void ValidPrimitiveUInt32RoundTrip()
{
Assert.True(this.TestPrimitiveType("UInt32"));
}
/// <summary>
/// Test for <see cref="JsonPrimitive"/> round-trip created via <see cref="UInt64"/>.
/// </summary>
[Fact]
public void ValidPrimitiveUInt64RoundTrip()
{
Assert.True(this.TestPrimitiveType("UInt64"));
}
/// <summary>
/// Test for <see cref="JsonPrimitive"/> round-trip created via <see cref="Char"/>.
/// </summary>
[Fact]
public void ValidPrimitiveCharRoundTrip()
{
Assert.True(this.TestPrimitiveType("Char"));
}
/// <summary>
/// Test for <see cref="JsonPrimitive"/> round-trip created via <see cref="Guid"/>.
/// </summary>
[Fact]
public void ValidPrimitiveGuidRoundTrip()
{
Assert.True(this.TestPrimitiveType("Guid"));
}
/// <summary>
/// Test for <see cref="JsonPrimitive"/> round-trip created via <see cref="Uri"/>.
/// </summary>
[Fact]
public void ValidPrimitiveUriRoundTrip()
{
Assert.True(this.TestPrimitiveType("Uri"));
}
/// <summary>
/// Tests for <see cref="JsonValue"/> round-trip created via <code>null</code> values.
/// </summary>
[Fact]
public void ValidPrimitiveNullRoundTrip()
{
Assert.True(this.TestPrimitiveType("Null"));
}
/// <summary>
/// Tests for round-tripping <see cref="JsonPrimitive"/> objects via casting to CLR instances.
/// </summary>
[Fact]
public void JsonValueRoundTripCastTests()
{
int seed = 1;
Log.Info("Seed: {0}", seed);
Random rndGen = new Random(seed);
this.DoRoundTripCasting(String.Empty, typeof(string));
this.DoRoundTripCasting("null", typeof(string));
string str;
do
{
str = PrimitiveCreator.CreateInstanceOfString(rndGen);
} while (str == null);
this.DoRoundTripCasting(str, typeof(string));
this.DoRoundTripCasting(PrimitiveCreator.CreateInstanceOfInt16(rndGen), typeof(int));
this.DoRoundTripCasting(PrimitiveCreator.CreateInstanceOfInt32(rndGen), typeof(int));
this.DoRoundTripCasting(PrimitiveCreator.CreateInstanceOfInt64(rndGen), typeof(int));
this.DoRoundTripCasting(PrimitiveCreator.CreateInstanceOfUInt16(rndGen), typeof(int));
this.DoRoundTripCasting(PrimitiveCreator.CreateInstanceOfUInt32(rndGen), typeof(int));
this.DoRoundTripCasting(PrimitiveCreator.CreateInstanceOfUInt64(rndGen), typeof(int));
this.DoRoundTripCasting(PrimitiveCreator.CreateInstanceOfGuid(rndGen), typeof(Guid));
this.DoRoundTripCasting(new Uri("http://bug/test?param=hello%0a"), typeof(Uri));
this.DoRoundTripCasting(PrimitiveCreator.CreateInstanceOfChar(rndGen), typeof(char));
this.DoRoundTripCasting(PrimitiveCreator.CreateInstanceOfBoolean(rndGen), typeof(bool));
this.DoRoundTripCasting(PrimitiveCreator.CreateInstanceOfDateTime(rndGen), typeof(DateTime));
this.DoRoundTripCasting(PrimitiveCreator.CreateInstanceOfDateTimeOffset(rndGen), typeof(DateTimeOffset));
this.DoRoundTripCasting(PrimitiveCreator.CreateInstanceOfDouble(rndGen), typeof(double));
this.DoRoundTripCasting(PrimitiveCreator.CreateInstanceOfDouble(rndGen), typeof(float));
this.DoRoundTripCasting(0.12345f, typeof(double));
this.DoRoundTripCasting(0.12345f, typeof(float));
}
private bool TestPrimitiveType(string typeName)
{
bool retValue = true;
bool specialCase = false;
int seed = 1;
Log.Info("Seed: {0}", seed);
Random rndGen = new Random(seed);
JsonPrimitive sourceJson = null;
JsonPrimitive sourceJson2;
object tempValue = null;
switch (typeName.ToLower())
{
case "boolean":
tempValue = PrimitiveCreator.CreateInstanceOfBoolean(rndGen);
sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString().ToLower());
sourceJson2 = new JsonPrimitive((bool)tempValue);
break;
case "byte":
tempValue = PrimitiveCreator.CreateInstanceOfByte(rndGen);
sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString());
sourceJson2 = new JsonPrimitive((byte)tempValue);
break;
case "char":
sourceJson2 = new JsonPrimitive((char)PrimitiveCreator.CreateInstanceOfChar(rndGen));
specialCase = true;
break;
case "datetime":
tempValue = PrimitiveCreator.CreateInstanceOfDateTime(rndGen);
sourceJson2 = new JsonPrimitive((DateTime)tempValue);
sourceJson = (JsonPrimitive)JsonValue.Parse(sourceJson2.ToString());
break;
case "decimal":
tempValue = PrimitiveCreator.CreateInstanceOfDecimal(rndGen);
sourceJson = (JsonPrimitive)JsonValue.Parse(((decimal)tempValue).ToString(NumberFormatInfo.InvariantInfo));
sourceJson2 = new JsonPrimitive((decimal)tempValue);
break;
case "double":
double tempDouble = PrimitiveCreator.CreateInstanceOfDouble(rndGen);
sourceJson = (JsonPrimitive)JsonValue.Parse(tempDouble.ToString("R", NumberFormatInfo.InvariantInfo));
sourceJson2 = new JsonPrimitive(tempDouble);
break;
case "guid":
sourceJson2 = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfGuid(rndGen));
specialCase = true;
break;
case "int16":
tempValue = PrimitiveCreator.CreateInstanceOfInt16(rndGen);
sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString());
sourceJson2 = new JsonPrimitive((short)tempValue);
break;
case "int32":
tempValue = PrimitiveCreator.CreateInstanceOfInt32(rndGen);
sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString());
sourceJson2 = new JsonPrimitive((int)tempValue);
break;
case "int64":
tempValue = PrimitiveCreator.CreateInstanceOfInt64(rndGen);
sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString());
sourceJson2 = new JsonPrimitive((long)tempValue);
break;
case "sbyte":
tempValue = PrimitiveCreator.CreateInstanceOfSByte(rndGen);
sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString());
sourceJson2 = new JsonPrimitive((sbyte)tempValue);
break;
case "single":
float fltValue = PrimitiveCreator.CreateInstanceOfSingle(rndGen);
sourceJson = (JsonPrimitive)JsonValue.Parse(fltValue.ToString("R", NumberFormatInfo.InvariantInfo));
sourceJson2 = new JsonPrimitive(fltValue);
break;
case "string":
do
{
tempValue = PrimitiveCreator.CreateInstanceOfString(rndGen);
} while (tempValue == null);
sourceJson2 = new JsonPrimitive((string)tempValue);
sourceJson = (JsonPrimitive)JsonValue.Parse(sourceJson2.ToString());
break;
case "uint16":
tempValue = PrimitiveCreator.CreateInstanceOfUInt16(rndGen);
sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString());
sourceJson2 = new JsonPrimitive((ushort)tempValue);
break;
case "uint32":
tempValue = PrimitiveCreator.CreateInstanceOfUInt32(rndGen);
sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString());
sourceJson2 = new JsonPrimitive((uint)tempValue);
break;
case "uint64":
tempValue = PrimitiveCreator.CreateInstanceOfUInt64(rndGen);
sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString());
sourceJson2 = new JsonPrimitive((ulong)tempValue);
break;
case "uri":
Uri uri = null;
do
{
try
{
uri = PrimitiveCreator.CreateInstanceOfUri(rndGen);
}
catch (UriFormatException)
{
}
} while (uri == null);
sourceJson2 = new JsonPrimitive(uri);
specialCase = true;
break;
case "null":
sourceJson = (JsonPrimitive)JsonValue.Parse("null");
sourceJson2 = null;
break;
default:
sourceJson = null;
sourceJson2 = null;
break;
}
if (!specialCase)
{
// comparison between two constructors
if (!JsonValueVerifier.Compare(sourceJson, sourceJson2))
{
Log.Info("(JsonPrimitive)JsonValue.Parse(string) failed to match the results from default JsonPrimitive(obj)constructor for type {0}", typeName);
retValue = false;
}
if (sourceJson != null)
{
// test JsonValue.Load(TextReader)
JsonPrimitive newJson = null;
using (StringReader sr = new StringReader(sourceJson.ToString()))
{
newJson = (JsonPrimitive)JsonValue.Load(sr);
}
if (!JsonValueVerifier.Compare(sourceJson, newJson))
{
Log.Info("JsonValue.Load(TextReader) failed to function properly for type {0}", typeName);
retValue = false;
}
// test JsonValue.Load(Stream) is located in the JObjectFromGenoTypeLib test case
// test JsonValue.Parse(string)
newJson = null;
newJson = (JsonPrimitive)JsonValue.Parse(sourceJson.ToString());
if (!JsonValueVerifier.Compare(sourceJson, newJson))
{
Log.Info("JsonValue.Parse(string) failed to function properly for type {0}", typeName);
retValue = false;
}
}
}
else
{
// test JsonValue.Load(TextReader)
JsonPrimitive newJson2 = null;
using (StringReader sr = new StringReader(sourceJson2.ToString()))
{
newJson2 = (JsonPrimitive)JsonValue.Load(sr);
}
if (!JsonValueVerifier.Compare(sourceJson2, newJson2))
{
Log.Info("JsonValue.Load(TextReader) failed to function properly for type {0}", typeName);
retValue = false;
}
// test JsonValue.Load(Stream) is located in the JObjectFromGenoTypeLib test case
// test JsonValue.Parse(string)
newJson2 = null;
newJson2 = (JsonPrimitive)JsonValue.Parse(sourceJson2.ToString());
if (!JsonValueVerifier.Compare(sourceJson2, newJson2))
{
Log.Info("JsonValue.Parse(string) failed to function properly for type {0}", typeName);
retValue = false;
}
}
return retValue;
}
private void DoRoundTripCasting(JsonValue jo, Type type)
{
bool result = false;
// Casting
if (jo.JsonType == JsonType.String)
{
JsonValue jstr = (string)jo;
if (type == typeof(DateTime))
{
Log.Info("{0} Value:{1}", type.Name, ((DateTime)jstr).ToString(DateTimeFormatInfo.InvariantInfo));
}
else if (type == typeof(DateTimeOffset))
{
Log.Info("{0} Value:{1}", type.Name, ((DateTimeOffset)jstr).ToString(DateTimeFormatInfo.InvariantInfo));
}
else if (type == typeof(Guid))
{
Log.Info("{0} Value:{1}", type.Name, (Guid)jstr);
}
else if (type == typeof(char))
{
Log.Info("{0} Value:{1}", type.Name, (char)jstr);
}
else if (type == typeof(Uri))
{
Log.Info("{0} Value:{1}", type.Name, ((Uri)jstr).AbsoluteUri);
}
else
{
Log.Info("{0} Value:{1}", type.Name, (string)jstr);
}
if (jo.ToString() == jstr.ToString())
{
result = true;
}
}
else if (jo.JsonType == JsonType.Object)
{
JsonObject jobj = new JsonObject((JsonObject)jo);
if (jo.ToString() == jobj.ToString())
{
result = true;
}
}
else if (jo.JsonType == JsonType.Number)
{
JsonPrimitive jprim = (JsonPrimitive)jo;
Log.Info("{0} Value:{1}", type.Name, jprim);
if (jo.ToString() == jprim.ToString())
{
result = true;
}
}
else if (jo.JsonType == JsonType.Boolean)
{
JsonPrimitive jprim = (JsonPrimitive)jo;
Log.Info("{0} Value:{1}", type.Name, (bool)jprim);
if (jo.ToString() == jprim.ToString())
{
result = true;
}
}
Assert.True(result);
}
}
}

Просмотреть файл

@ -1,331 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using Xunit;
namespace System.Json
{
/// <summary>
/// Tests for the methods to convert between <see cref="JsonValue"/> instances and complex types.
/// </summary>
public class JsonValueAndComplexTypesTests
{
static readonly Type[] testTypes = new Type[]
{
typeof(DCType_1),
typeof(StructGuid),
typeof(StructInt16),
typeof(DCType_3),
typeof(SerType_4),
typeof(SerType_5),
typeof(DCType_7),
typeof(DCType_9),
typeof(SerType_11),
typeof(DCType_15),
typeof(DCType_16),
typeof(DCType_18),
typeof(DCType_19),
typeof(DCType_20),
typeof(SerType_22),
typeof(DCType_25),
typeof(SerType_26),
typeof(DCType_31),
typeof(DCType_32),
typeof(SerType_33),
typeof(DCType_34),
typeof(DCType_36),
typeof(DCType_38),
typeof(DCType_40),
typeof(DCType_42),
typeof(DCType_65),
typeof(ListType_1),
typeof(ListType_2),
typeof(BaseType),
typeof(PolymorphicMember),
typeof(PolymorphicAsInterfaceMember),
typeof(CollectionsWithPolymorphicMember),
};
/// <summary>
/// Tests for the <see cref="JsonValueExtensions.CreateFrom"/> method.
/// </summary>
[Fact]
public void CreateFromTests()
{
InstanceCreatorSurrogate oldSurrogate = CreatorSettings.CreatorSurrogate;
try
{
CreatorSettings.CreatorSurrogate = new NoInfinityFloatSurrogate();
DateTime now = DateTime.Now;
int seed = (10000 * now.Year) + (100 * now.Month) + now.Day;
Log.Info("Seed: {0}", seed);
Random rndGen = new Random(seed);
foreach (Type testType in testTypes)
{
object instance = InstanceCreator.CreateInstanceOf(testType, rndGen);
JsonValue jv = JsonValueExtensions.CreateFrom(instance);
if (instance == null)
{
Assert.Null(jv);
}
else
{
DataContractJsonSerializer dcjs = new DataContractJsonSerializer(instance == null ? testType : instance.GetType());
string fromDCJS;
using (MemoryStream ms = new MemoryStream())
{
dcjs.WriteObject(ms, instance);
fromDCJS = Encoding.UTF8.GetString(ms.ToArray());
}
Log.Info("{0}: {1}", testType.Name, fromDCJS);
if (instance == null)
{
Assert.Null(jv);
}
else
{
string fromJsonValue = jv.ToString();
Assert.Equal(fromDCJS, fromJsonValue);
}
}
}
}
finally
{
CreatorSettings.CreatorSurrogate = oldSurrogate;
}
}
/// <summary>
/// Tests for the <see cref="JsonValueExtensions.ReadAsType{T}(JsonValue)"/> method.
/// </summary>
[Fact]
public void ReadAsTests()
{
InstanceCreatorSurrogate oldSurrogate = CreatorSettings.CreatorSurrogate;
try
{
CreatorSettings.CreatorSurrogate = new NoInfinityFloatSurrogate();
DateTime now = DateTime.Now;
int seed = (10000 * now.Year) + (100 * now.Month) + now.Day;
Log.Info("Seed: {0}", seed);
Random rndGen = new Random(seed);
this.ReadAsTest<DCType_1>(rndGen);
this.ReadAsTest<StructGuid>(rndGen);
this.ReadAsTest<StructInt16>(rndGen);
this.ReadAsTest<DCType_3>(rndGen);
this.ReadAsTest<SerType_4>(rndGen);
this.ReadAsTest<SerType_5>(rndGen);
this.ReadAsTest<DCType_7>(rndGen);
this.ReadAsTest<DCType_9>(rndGen);
this.ReadAsTest<SerType_11>(rndGen);
this.ReadAsTest<DCType_15>(rndGen);
this.ReadAsTest<DCType_16>(rndGen);
this.ReadAsTest<DCType_18>(rndGen);
this.ReadAsTest<DCType_19>(rndGen);
this.ReadAsTest<DCType_20>(rndGen);
this.ReadAsTest<SerType_22>(rndGen);
this.ReadAsTest<DCType_25>(rndGen);
this.ReadAsTest<SerType_26>(rndGen);
this.ReadAsTest<DCType_31>(rndGen);
this.ReadAsTest<DCType_32>(rndGen);
this.ReadAsTest<SerType_33>(rndGen);
this.ReadAsTest<DCType_34>(rndGen);
this.ReadAsTest<DCType_36>(rndGen);
this.ReadAsTest<DCType_38>(rndGen);
this.ReadAsTest<DCType_40>(rndGen);
this.ReadAsTest<DCType_42>(rndGen);
this.ReadAsTest<DCType_65>(rndGen);
this.ReadAsTest<ListType_1>(rndGen);
this.ReadAsTest<ListType_2>(rndGen);
this.ReadAsTest<BaseType>(rndGen);
this.ReadAsTest<PolymorphicMember>(rndGen);
this.ReadAsTest<PolymorphicAsInterfaceMember>(rndGen);
this.ReadAsTest<CollectionsWithPolymorphicMember>(rndGen);
}
finally
{
CreatorSettings.CreatorSurrogate = oldSurrogate;
}
}
/// <summary>
/// Tests for the <see cref="JsonValueExtensions.CreateFrom"/> for <see cref="DateTime"/>
/// and <see cref="DateTimeOffset"/> values.
/// </summary>
[Fact]
public void CreateFromDateTimeTest()
{
DateTime dt = DateTime.Now;
DateTimeOffset dto = DateTimeOffset.Now;
JsonValue jvDt1 = (JsonValue)dt;
JsonValue jvDt2 = JsonValueExtensions.CreateFrom(dt);
JsonValue jvDto1 = (JsonValue)dto;
JsonValue jvDto2 = JsonValueExtensions.CreateFrom(dto);
Assert.Equal(dt, (DateTime)jvDt1);
Assert.Equal(dt, (DateTime)jvDt2);
Assert.Equal(dto, (DateTimeOffset)jvDto1);
Assert.Equal(dto, (DateTimeOffset)jvDto2);
Assert.Equal(dt, jvDt1.ReadAs<DateTime>());
Assert.Equal(dt, jvDt2.ReadAs<DateTime>());
Assert.Equal(dto, jvDto1.ReadAs<DateTimeOffset>());
Assert.Equal(dto, jvDto2.ReadAs<DateTimeOffset>());
Assert.Equal(jvDt1.ToString(), jvDt2.ToString());
Assert.Equal(jvDto1.ToString(), jvDto2.ToString());
}
/// <summary>
/// Tests for creating <see cref="JsonValue"/> instances from dynamic objects.
/// </summary>
[Fact]
public void CreateFromDynamic()
{
string expectedJson = "{\"int\":12,\"str\":\"hello\",\"jv\":[1,{\"a\":true}],\"dyn\":{\"char\":\"c\",\"null\":null}}";
MyDynamicObject obj = new MyDynamicObject();
obj.fields.Add("int", 12);
obj.fields.Add("str", "hello");
obj.fields.Add("jv", new JsonArray(1, new JsonObject { { "a", true } }));
MyDynamicObject dyn = new MyDynamicObject();
obj.fields.Add("dyn", dyn);
dyn.fields.Add("char", 'c');
dyn.fields.Add("null", null);
JsonValue jv = JsonValueExtensions.CreateFrom(obj);
Assert.Equal(expectedJson, jv.ToString());
}
void ReadAsTest<T>(Random rndGen)
{
T instance = InstanceCreator.CreateInstanceOf<T>(rndGen);
Log.Info("ReadAsTest<{0}>, instance = {1}", typeof(T).Name, instance);
DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(T));
JsonValue jv;
using (MemoryStream ms = new MemoryStream())
{
dcjs.WriteObject(ms, instance);
Log.Info("{0}: {1}", typeof(T).Name, Encoding.UTF8.GetString(ms.ToArray()));
ms.Position = 0;
jv = JsonValue.Load(ms);
}
if (instance == null)
{
Assert.Null(jv);
}
else
{
T newInstance = jv.ReadAsType<T>();
Assert.Equal(instance, newInstance);
}
}
/// <summary>
/// Test class.
/// </summary>
public class MyDynamicObject : DynamicObject
{
/// <summary>
/// Test member
/// </summary>
public Dictionary<string, object> fields = new Dictionary<string, object>();
/// <summary>
/// Returnes the member names in this dynamic object.
/// </summary>
/// <returns>The member names in this dynamic object.</returns>
public override IEnumerable<string> GetDynamicMemberNames()
{
return fields.Keys;
}
/// <summary>
/// Attempts to get a named member from this dynamic object.
/// </summary>
/// <param name="binder">The dynamic binder which contains the member name.</param>
/// <param name="result">The value of the member, if it exists in this dynamic object.</param>
/// <returns><code>true</code> if the member can be returned; <code>false</code> otherwise.</returns>
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (binder != null && binder.Name != null && this.fields.ContainsKey(binder.Name))
{
result = this.fields[binder.Name];
return true;
}
return base.TryGetMember(binder, out result);
}
/// <summary>
/// Attempts to set a named member from this dynamic object.
/// </summary>
/// <param name="binder">The dynamic binder which contains the member name.</param>
/// <param name="value">The value of the member to be set.</param>
/// <returns><code>true</code> if the member can be set; <code>false</code> otherwise.</returns>
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (binder != null && binder.Name != null)
{
this.fields[binder.Name] = value;
return true;
}
return base.TrySetMember(binder, value);
}
}
// Currently there are some differences in treatment of infinity between
// JsonValue (which writes them as Infinity/-Infinity) and DataContractJsonSerializer
// (which writes them as INF/-INF). This prevents those values from being used in the test.
// This also allows the creation of an instance of an IEmptyInterface type, used in the test.
class NoInfinityFloatSurrogate : InstanceCreatorSurrogate
{
public override bool CanCreateInstanceOf(Type type)
{
return type == typeof(float) || type == typeof(double) || type == typeof(IEmptyInterface) || type == typeof(BaseType);
}
public override object CreateInstanceOf(Type type, Random rndGen)
{
if (type == typeof(float))
{
float result;
do
{
result = PrimitiveCreator.CreateInstanceOfSingle(rndGen);
}
while (float.IsInfinity(result));
return result;
}
else if (type == typeof(double))
{
double result;
do
{
result = PrimitiveCreator.CreateInstanceOfDouble(rndGen);
}
while (double.IsInfinity(result));
return result;
}
else
{
return new DerivedType(rndGen);
}
}
}
}
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -1,520 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Json
{
/// <summary>
/// Tests for events on <see cref="JsonValue"/> instances.
/// </summary>
public class JsonValueEventsTests
{
/// <summary>
/// Events tests for JsonArray, test all method the causes change and all change type and validate changing/changed child and sub/unsub
/// </summary>
[Fact]
public void JsonArrayEventsTest()
{
int seed = 1;
const int maxArrayLength = 1024;
Random rand = new Random(seed);
JsonArray ja = SpecialJsonValueHelper.CreatePrePopulatedJsonArray(seed, rand.Next(maxArrayLength));
int addPosition = ja.Count;
JsonValue insertValue = SpecialJsonValueHelper.GetRandomJsonPrimitives(seed);
TestEvents(
ja,
arr => arr.Add(insertValue),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(insertValue, JsonValueChange.Add, addPosition)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(insertValue, JsonValueChange.Add, addPosition)),
});
addPosition = ja.Count;
JsonValue jv1 = SpecialJsonValueHelper.GetRandomJsonPrimitives(seed);
JsonValue jv2 = SpecialJsonValueHelper.GetRandomJsonPrimitives(seed);
TestEvents(
ja,
arr => arr.AddRange(jv1, jv2),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, ja,
new JsonValueChangeEventArgs(
jv1,
JsonValueChange.Add, addPosition)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, ja,
new JsonValueChangeEventArgs(
jv2,
JsonValueChange.Add, addPosition + 1)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, ja,
new JsonValueChangeEventArgs(
jv1,
JsonValueChange.Add, addPosition)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, ja,
new JsonValueChangeEventArgs(
jv2,
JsonValueChange.Add, addPosition + 1)),
});
int replacePosition = rand.Next(ja.Count - 1);
JsonValue oldValue = ja[replacePosition];
JsonValue newValue = SpecialJsonValueHelper.GetRandomJsonPrimitives(seed);
TestEvents(
ja,
arr => arr[replacePosition] = newValue,
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(newValue, JsonValueChange.Replace, replacePosition)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(oldValue, JsonValueChange.Replace, replacePosition)),
});
int insertPosition = rand.Next(ja.Count - 1);
insertValue = SpecialJsonValueHelper.GetRandomJsonPrimitives(seed);
TestEvents(
ja,
arr => arr.Insert(insertPosition, insertValue),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(insertValue, JsonValueChange.Add, insertPosition)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(insertValue, JsonValueChange.Add, insertPosition)),
});
TestEvents(
ja,
arr => arr.RemoveAt(insertPosition),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(insertValue, JsonValueChange.Remove, insertPosition)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(insertValue, JsonValueChange.Remove, insertPosition)),
});
ja.Insert(0, insertValue);
TestEvents(
ja,
arr => arr.Remove(insertValue),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(insertValue, JsonValueChange.Remove, 0)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(insertValue, JsonValueChange.Remove, 0)),
});
TestEvents(
ja,
arr => arr.Clear(),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(null, JsonValueChange.Clear, 0)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(null, JsonValueChange.Clear, 0)),
});
ja = new JsonArray(1, 2, 3);
TestEvents(
ja,
arr => arr.Remove(new JsonPrimitive("Not there")),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>());
JsonValue elementInArray = ja[1];
TestEvents(
ja,
arr => arr.Remove(elementInArray),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(elementInArray, JsonValueChange.Remove, 1)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(elementInArray, JsonValueChange.Remove, 1)),
});
}
/// <summary>
/// Tests for events for <see cref="JsonValue"/> instances when using the dynamic programming.
/// </summary>
[Fact]
public void DynamicEventsTest()
{
int seed = 1;
int maxObj = 10;
JsonArray ja = new JsonArray();
dynamic d = ja.AsDynamic();
TestEventsDynamic(
d,
(Action<dynamic>)(arr => arr.Add(1)),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(1, JsonValueChange.Add, 0)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(1, JsonValueChange.Add, 0)),
});
const string key1 = "first";
const string key2 = "second";
JsonObject jo = new JsonObject
{
{ key1, SpecialJsonValueHelper.GetRandomJsonPrimitives(seed) },
};
JsonObject objectToAdd = SpecialJsonValueHelper.CreateRandomPopulatedJsonObject(seed, maxObj);
dynamic d2 = jo.AsDynamic();
TestEventsDynamic(
d2,
(Action<dynamic>)(obj => obj[key2] = objectToAdd),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(objectToAdd, JsonValueChange.Add, key2)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(objectToAdd, JsonValueChange.Add, key2)),
});
TestEventsDynamic(
d2,
(Action<dynamic>)(obj => obj[key2] = objectToAdd),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(objectToAdd, JsonValueChange.Replace, key2)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(objectToAdd, JsonValueChange.Replace, key2)),
});
}
/// <summary>
/// Tests for events in <see cref="JsonObject"/> instances.
/// </summary>
[Fact]
public void JsonObjectEventsTest()
{
int seed = 1;
const int maxObj = 10;
const string key1 = "first";
const string key2 = "second";
const string key3 = "third";
const string key4 = "fourth";
const string key5 = "fifth";
JsonObject jo = new JsonObject
{
{ key1, SpecialJsonValueHelper.GetRandomJsonPrimitives(seed) },
{ key2, SpecialJsonValueHelper.GetRandomJsonPrimitives(seed) },
{ key3, null },
};
JsonObject objToAdd = SpecialJsonValueHelper.CreateRandomPopulatedJsonObject(seed, maxObj);
TestEvents(
jo,
obj => obj.Add(key4, objToAdd),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(objToAdd, JsonValueChange.Add, key4)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(objToAdd, JsonValueChange.Add, key4)),
},
obj => obj.Add("key44", objToAdd));
JsonArray jaToAdd = SpecialJsonValueHelper.CreatePrePopulatedJsonArray(seed, maxObj);
JsonValue replaced = jo[key2];
TestEvents(
jo,
obj => obj[key2] = jaToAdd,
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(jaToAdd, JsonValueChange.Replace, key2)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(replaced, JsonValueChange.Replace, key2)),
});
JsonValue jpToAdd = SpecialJsonValueHelper.GetRandomJsonPrimitives(seed);
TestEvents(
jo,
obj => obj[key5] = jpToAdd,
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(jpToAdd, JsonValueChange.Add, key5)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(jpToAdd, JsonValueChange.Add, key5)),
});
jo.Remove(key4);
jo.Remove(key5);
JsonValue jp1 = SpecialJsonValueHelper.GetRandomJsonPrimitives(seed);
JsonValue jp2 = SpecialJsonValueHelper.GetRandomJsonPrimitives(seed);
TestEvents(
jo,
obj => obj.AddRange(new JsonObject { { key4, jp1 }, { key5, jp1 } }),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(jp1, JsonValueChange.Add, key4)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(jp2, JsonValueChange.Add, key5)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(jp1, JsonValueChange.Add, key4)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(jp2, JsonValueChange.Add, key5)),
},
obj => obj.AddRange(new JsonObject { { "new key", jp1 }, { "newnewKey", jp2 } }));
TestEvents(
jo,
obj => obj.Remove(key5),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(jp2, JsonValueChange.Remove, key5)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(jp2, JsonValueChange.Remove, key5)),
});
TestEvents(
jo,
obj => obj.Remove("not there"),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>());
jo = new JsonObject { { key1, 1 }, { key2, 2 }, { key3, 3 } };
TestEvents(
jo,
obj => obj.Clear(),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(null, JsonValueChange.Clear, null)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(null, JsonValueChange.Clear, null)),
});
jo = new JsonObject { { key1, 1 }, { key2, 2 }, { key3, 3 } };
TestEvents(
jo,
obj => ((IDictionary<string, JsonValue>)obj).Remove(new KeyValuePair<string, JsonValue>(key2, jo[key2])),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(2, JsonValueChange.Remove, key2)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(2, JsonValueChange.Remove, key2)),
},
obj => ((IDictionary<string, JsonValue>)obj).Remove(new KeyValuePair<string, JsonValue>(key1, jo[key1])));
}
/// <summary>
/// Tests for events in <see cref="JsonValue"/> instances when multiple listeners are registered.
/// </summary>
[Fact]
public void MultipleListenersTest()
{
const string key1 = "first";
const string key2 = "second";
const string key3 = "third";
for (int changingListeners = 0; changingListeners <= 3; changingListeners++)
{
for (int changedListeners = 0; changedListeners <= 3; changedListeners++)
{
MultipleListenersTestInternal<JsonObject>(
() => new JsonObject { { key1, 1 }, { key2, 2 } },
delegate(JsonObject obj)
{
obj[key2] = "hello";
obj.Remove(key1);
obj.Add(key3, "world");
obj.Clear();
},
new List<JsonValueChangeEventArgs>
{
new JsonValueChangeEventArgs("hello", JsonValueChange.Replace, key2),
new JsonValueChangeEventArgs(1, JsonValueChange.Remove, key1),
new JsonValueChangeEventArgs("world", JsonValueChange.Add, key3),
new JsonValueChangeEventArgs(null, JsonValueChange.Clear, null),
},
new List<JsonValueChangeEventArgs>
{
new JsonValueChangeEventArgs(2, JsonValueChange.Replace, key2),
new JsonValueChangeEventArgs(1, JsonValueChange.Remove, key1),
new JsonValueChangeEventArgs("world", JsonValueChange.Add, key3),
new JsonValueChangeEventArgs(null, JsonValueChange.Clear, null),
},
changingListeners,
changedListeners);
MultipleListenersTestInternal<JsonArray>(
() => new JsonArray(1, 2),
delegate(JsonArray arr)
{
arr[1] = "hello";
arr.RemoveAt(0);
arr.Add("world");
arr.Clear();
},
new List<JsonValueChangeEventArgs>
{
new JsonValueChangeEventArgs("hello", JsonValueChange.Replace, 1),
new JsonValueChangeEventArgs(1, JsonValueChange.Remove, 0),
new JsonValueChangeEventArgs("world", JsonValueChange.Add, 1),
new JsonValueChangeEventArgs(null, JsonValueChange.Clear, 0),
},
new List<JsonValueChangeEventArgs>
{
new JsonValueChangeEventArgs(2, JsonValueChange.Replace, 1),
new JsonValueChangeEventArgs(1, JsonValueChange.Remove, 0),
new JsonValueChangeEventArgs("world", JsonValueChange.Add, 1),
new JsonValueChangeEventArgs(null, JsonValueChange.Clear, 0),
},
changingListeners,
changedListeners);
}
}
}
internal static void TestEvents<JsonValueType>(JsonValueType target, Action<JsonValueType> actionToTriggerEvent, List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>> expectedEvents, Action<JsonValueType> actionToTriggerEvent2 = null) where JsonValueType : JsonValue
{
var actualEvents = new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>();
EventHandler<JsonValueChangeEventArgs> changingHandler = (sender, e) => actualEvents.Add(new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, sender as JsonValue, e));
EventHandler<JsonValueChangeEventArgs> changedHandler = (sender, e) => actualEvents.Add(new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, sender as JsonValue, e));
target.Changing += changingHandler;
target.Changed += changedHandler;
actionToTriggerEvent(target);
target.Changing -= changingHandler;
target.Changed -= changedHandler;
ValidateExpectedEvents(expectedEvents, actualEvents);
if (actionToTriggerEvent2 == null)
{
actionToTriggerEvent(target);
}
else
{
actionToTriggerEvent2(target);
}
ValidateExpectedEvents(expectedEvents, actualEvents);
}
internal static void TestEventsDynamic(dynamic target, Action<dynamic> actionToTriggerEvent, List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>> expectedEvents)
{
var actualEvents = new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>();
EventHandler<JsonValueChangeEventArgs> changingHandler = (sender, e) => actualEvents.Add(new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, sender as JsonValue, e));
EventHandler<JsonValueChangeEventArgs> changedHandler = (sender, e) => actualEvents.Add(new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, sender as JsonValue, e));
target.Changing += changingHandler;
target.Changed += changedHandler;
actionToTriggerEvent(target);
target.Changing -= changingHandler;
target.Changed -= changedHandler;
ValidateExpectedEvents(expectedEvents, actualEvents);
actionToTriggerEvent(target);
ValidateExpectedEvents(expectedEvents, actualEvents);
}
private static void ValidateExpectedEvents(List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>> expectedEvents, List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>> actualEvents)
{
Assert.Equal(expectedEvents.Count, actualEvents.Count);
for (int i = 0; i < expectedEvents.Count; i++)
{
bool expectedIsChanging = expectedEvents[i].Item1;
bool actualIsChanging = expectedEvents[i].Item1;
Assert.Equal(expectedIsChanging, actualIsChanging);
JsonValue expectedSender = expectedEvents[i].Item2;
JsonValue actualSender = actualEvents[i].Item2;
Assert.Equal(expectedSender, actualSender);
JsonValueChangeEventArgs expectedEventArgs = expectedEvents[i].Item3;
JsonValueChangeEventArgs actualEventArgs = actualEvents[i].Item3;
Assert.Equal(expectedEventArgs.Change, actualEventArgs.Change);
Assert.Equal(expectedEventArgs.Index, actualEventArgs.Index);
Assert.Equal(expectedEventArgs.Key, actualEventArgs.Key);
string expectedChild = expectedEventArgs.Child == null ? "null" : expectedEventArgs.Child.ToString();
string actualChild = actualEventArgs.Child == null ? "null" : actualEventArgs.Child.ToString();
Assert.Equal(expectedChild, actualChild);
}
}
internal static void MultipleListenersTestInternal<JsonValueType>(
Func<JsonValueType> createTarget,
Action<JsonValueType> actionToTriggerEvents,
List<JsonValueChangeEventArgs> expectedChangingEventArgs,
List<JsonValueChangeEventArgs> expectedChangedEventArgs,
int changingListeners,
int changedListeners) where JsonValueType : JsonValue
{
Log.Info("Testing events on a {0} for {1} changING listeners and {2} changED listeners", typeof(JsonValueType).Name, changingListeners, changedListeners);
JsonValueType target = createTarget();
List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>[] actualChangingEvents = new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>[changingListeners];
List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>[] actualChangedEvents = new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>[changedListeners];
List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>> expectedChangingEvents = new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>(
expectedChangingEventArgs.Select((args) => new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, target, args)));
List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>> expectedChangedEvents = new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>(
expectedChangedEventArgs.Select((args) => new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, target, args)));
for (int i = 0; i < changingListeners; i++)
{
actualChangingEvents[i] = new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>();
var index = i;
target.Changing += delegate(object sender, JsonValueChangeEventArgs e)
{
actualChangingEvents[index].Add(new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, sender as JsonValue, e));
};
}
for (int i = 0; i < changedListeners; i++)
{
actualChangedEvents[i] = new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>();
var index = i;
target.Changed += delegate(object sender, JsonValueChangeEventArgs e)
{
actualChangedEvents[index].Add(new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, sender as JsonValue, e));
};
}
actionToTriggerEvents(target);
for (int i = 0; i < changingListeners; i++)
{
Log.Info("Validating Changing events for listener {0}", i);
ValidateExpectedEvents(expectedChangingEvents, actualChangingEvents[i]);
}
for (int i = 0; i < changedListeners; i++)
{
Log.Info("Validating Changed events for listener {0}", i);
ValidateExpectedEvents(expectedChangedEvents, actualChangedEvents[i]);
}
for (int i = 0; i < changingListeners; i++)
{
actualChangingEvents[i] = new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>();
var index = i;
target.Changing -= delegate(object sender, JsonValueChangeEventArgs e)
{
actualChangingEvents[i].Add(new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, sender as JsonValue, e));
};
}
for (int i = 0; i < changedListeners; i++)
{
actualChangedEvents[i] = new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>();
var index = i;
target.Changed -= delegate(object sender, JsonValueChangeEventArgs e)
{
actualChangedEvents[i].Add(new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, sender as JsonValue, e));
};
}
target = createTarget();
expectedChangingEvents.Clear();
expectedChangedEvents.Clear();
actionToTriggerEvents(target);
for (int i = 0; i < changingListeners; i++)
{
Log.Info("Validating Changing events for listener {0}", i);
ValidateExpectedEvents(expectedChangingEvents, actualChangingEvents[i]);
}
for (int i = 0; i < changedListeners; i++)
{
Log.Info("Validating Changed events for listener {0}", i);
ValidateExpectedEvents(expectedChangedEvents, actualChangedEvents[i]);
}
}
private static void ValidateJsonArrayItems(JsonArray jsonArray, IEnumerable<JsonValue> expectedItems)
{
List<JsonValue> expected = new List<JsonValue>(expectedItems);
Assert.Equal(expected.Count, jsonArray.Count);
for (int i = 0; i < expected.Count; i++)
{
Assert.Equal(expected[i], jsonArray[i]);
}
}
}
}

Просмотреть файл

@ -1,70 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Linq;
using Xunit;
namespace System.Json
{
/// <summary>
/// Tests for the Linq extensions to the <see cref="JsonValue"/> types.
/// </summary>
public class JsonValueLinqExtensionsIntegrationTest
{
/// <summary>
/// Test for the <see cref="JsonValueLinqExtensions.ToJsonArray"/> method.
/// </summary>
[Fact]
public void ToJsonArrayTest()
{
string json = "{\"SearchResponse\":{\"Phonebook\":{\"Results\":[{\"name\":1,\"rating\":1}, {\"name\":2,\"rating\":2}, {\"name\":3,\"rating\":3}]}}}";
string expected = "[{\"name\":2,\"rating\":2},{\"name\":3,\"rating\":3}]";
JsonValue jv = JsonValue.Parse(json);
double rating = 1;
var jsonResult = from n in jv.ValueOrDefault("SearchResponse", "Phonebook", "Results")
where n.Value.ValueOrDefault("rating").ReadAs<double>(0.0) > rating
select n.Value;
var ja = jsonResult.ToJsonArray();
Assert.Equal(expected, ja.ToString());
}
/// <summary>
/// Test for the <see cref="JsonValueLinqExtensions.ToJsonObject"/> method.
/// </summary>
[Fact]
public void ToJsonObjectTest()
{
string json = "{\"Name\":\"Bill Gates\",\"Age\":23,\"AnnualIncome\":45340.45,\"MaritalStatus\":\"Single\",\"EducationLevel\":\"MiddleSchool\",\"SSN\":432332453,\"CellNumber\":2340393420}";
string expected = "{\"AnnualIncome\":45340.45,\"SSN\":432332453,\"CellNumber\":2340393420}";
JsonValue jv = JsonValue.Parse(json);
decimal decVal;
var jsonResult = from n in jv
where n.Value.TryReadAs<decimal>(out decVal) && decVal > 100
select n;
var jo = jsonResult.ToJsonObject();
Assert.Equal(expected, jo.ToString());
}
/// <summary>
/// Test for the <see cref="JsonValueLinqExtensions.ToJsonObject"/> method where the origin is a <see cref="JsonArray"/>.
/// </summary>
[Fact]
public void ToJsonObjectFromArrayTest()
{
string json = "{\"SearchResponse\":{\"Phonebook\":{\"Results\":[{\"name\":1,\"rating\":1}, {\"name\":2,\"rating\":2}, {\"name\":3,\"rating\":3}]}}}";
string expected = "{\"1\":{\"name\":2,\"rating\":2},\"2\":{\"name\":3,\"rating\":3}}";
JsonValue jv = JsonValue.Parse(json);
double rating = 1;
var jsonResult = from n in jv.ValueOrDefault("SearchResponse", "Phonebook", "Results")
where n.Value.ValueOrDefault("rating").ReadAs<double>(0.0) > rating
select n;
var jo = jsonResult.ToJsonObject();
Assert.Equal(expected, jo.ToString());
}
}
}

Просмотреть файл

@ -1,188 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.Security;
using System.Security.Policy;
using Xunit;
namespace System.Json
{
/// <summary>
/// Tests for using the <see cref="JsonValue"/> types in partial trust.
/// </summary>
[Serializable]
public class JsonValuePartialTrustTests
{
/// <summary>
/// Validates the condition, throwing an exception if it is false.
/// </summary>
/// <param name="condition">The condition to be evaluated.</param>
/// <param name="msg">The exception message to be thrown, in case the condition is false.</param>
public static void AssertIsTrue(bool condition, string msg)
{
if (!condition)
{
throw new InvalidOperationException(msg);
}
}
/// <summary>
/// Validates that the two objects are equal, throwing an exception if it is false.
/// </summary>
/// <param name="obj1">The first object to be compared.</param>
/// <param name="obj2">The second object to be compared.</param>
/// <param name="msg">The exception message to be thrown, in case the condition is false.</param>
public static void AssertAreEqual(object obj1, object obj2, string msg)
{
if (obj1 == obj2)
{
return;
}
if (obj1 == null || obj2 == null || !obj1.Equals(obj2))
{
throw new InvalidOperationException(String.Format("[{0}, {2}] and [{1}, {3}] expected to be equal. {4}", obj1, obj2, obj1.GetType().Name, obj2.GetType().Name, msg));
}
}
/// <summary>
/// Partial trust tests for <see cref="JsonValue"/> instances where no dynamic references are used.
/// </summary>
[Fact(Skip = "Re-enable when CSDMain 216528: 'Partial trust support for Web API' has been fixed")]
public void RunNonDynamicTest()
{
RunInPartialTrust(this.NonDynamicTest);
}
/// <summary>
/// Partial trust tests for <see cref="JsonValue"/> with dynamic references.
/// </summary>
[Fact(Skip = "Re-enable when CSDMain 216528: 'Partial trust support for Web API' has been fixed")]
public void RunDynamicTest()
{
RunInPartialTrust(this.DynamicTest);
}
/// <summary>
/// Tests for <see cref="JsonValue"/> instances without dynamic references.
/// </summary>
public void NonDynamicTest()
{
int seed = GetRandomSeed();
Log.Info("Seed: {0}", seed);
Random rndGen = new Random(seed);
AssertIsTrue(Assembly.GetExecutingAssembly().IsFullyTrusted == false, "Executing assembly not expected to be fully trusted!");
Person person = new Person(rndGen);
Person person2 = new Person(rndGen);
person.AddFriends(3, rndGen);
person2.AddFriends(3, rndGen);
JsonValue jo = JsonValueExtensions.CreateFrom(person);
JsonValue jo2 = JsonValueExtensions.CreateFrom(person2);
AssertAreEqual(person.Address.City, jo["Address"]["City"].ReadAs<string>(), "Address.City");
AssertAreEqual(person.Friends[1].Age, jo["Friends"][1]["Age"].ReadAs<int>(), "Friends[1].Age");
string newCityName = "Bellevue";
jo["Address"]["City"] = newCityName;
AssertAreEqual(newCityName, (string)jo["Address"]["City"], "Address.City2");
jo["Friends"][1] = jo2;
AssertAreEqual(person2.Age, (int)jo["Friends"][1]["Age"], "Friends[1].Age2");
AssertAreEqual(person2.Address.City, jo.ValueOrDefault("Friends").ValueOrDefault(1).ValueOrDefault("Address").ValueOrDefault("City").ReadAs<string>(), "Address.City3");
AssertAreEqual(person2.Age, (int)jo.ValueOrDefault("Friends").ValueOrDefault(1).ValueOrDefault("Age"), "Friends[1].Age3");
AssertAreEqual(person2.Address.City, jo.ValueOrDefault("Friends", 1, "Address", "City").ReadAs<string>(), "Address.City3");
AssertAreEqual(person2.Age, (int)jo.ValueOrDefault("Friends", 1, "Age"), "Friends[1].Age3");
int newAge = 42;
JsonValue ageValue = jo["Friends"][1]["Age"] = newAge;
AssertAreEqual(newAge, (int)ageValue, "Friends[1].Age4");
}
/// <summary>
/// Tests for <see cref="JsonValue"/> instances with dynamic references.
/// </summary>
public void DynamicTest()
{
int seed = GetRandomSeed();
Log.Info("Seed: {0}", seed);
Random rndGen = new Random(seed);
AssertIsTrue(Assembly.GetExecutingAssembly().IsFullyTrusted == false, "Executing assembly not expected to be fully trusted!");
Person person = new Person(rndGen);
person.AddFriends(1, rndGen);
dynamic jo = JsonValueExtensions.CreateFrom(person);
AssertAreEqual(person.Friends[0].Name, jo.Friends[0].Name.ReadAs<string>(), "Friends[0].Name");
AssertAreEqual(person.Address.City, jo.Address.City.ReadAs<string>(), "Address.City");
AssertAreEqual(person.Friends[0].Age, (int)jo.Friends[0].Age, "Friends[0].Age");
string newCityName = "Bellevue";
jo.Address.City = newCityName;
AssertAreEqual(newCityName, (string)jo.Address.City, "Address.City2");
AssertAreEqual(person.Friends[0].Address.City, jo.ValueOrDefault("Friends").ValueOrDefault(0).ValueOrDefault("Address").ValueOrDefault("City").ReadAs<string>(), "Friends[0].Address.City");
AssertAreEqual(person.Friends[0].Age, (int)jo.ValueOrDefault("Friends").ValueOrDefault(0).ValueOrDefault("Age"), "Friends[0].Age2");
AssertAreEqual(person.Friends[0].Address.City, jo.ValueOrDefault("Friends", 0, "Address", "City").ReadAs<string>(), "Friends[0].Address.City");
AssertAreEqual(person.Friends[0].Age, (int)jo.ValueOrDefault("Friends", 0, "Age"), "Friends[0].Age2");
int newAge = 42;
JsonValue ageValue = jo.Friends[0].Age = newAge;
AssertAreEqual(newAge, (int)ageValue, "Friends[0].Age3");
AssertIsTrue(jo.NonExistentProperty is JsonValue, "Expected a JsonValue");
AssertIsTrue(jo.NonExistentProperty.JsonType == JsonType.Default, "Expected default JsonValue");
}
private static void RunInPartialTrust(CrossAppDomainDelegate testMethod)
{
Assert.True(Assembly.GetExecutingAssembly().IsFullyTrusted);
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
PermissionSet perms = PermissionsHelper.InternetZone;
AppDomain domain = AppDomain.CreateDomain("PartialTrustSandBox", null, setup, perms);
domain.DoCallBack(testMethod);
}
private static int GetRandomSeed()
{
DateTime now = DateTime.Now;
return (now.Year * 10000) + (now.Month * 100) + now.Day;
}
internal static class PermissionsHelper
{
private static PermissionSet internetZone;
public static PermissionSet InternetZone
{
get
{
if (internetZone == null)
{
Evidence evidence = new Evidence();
evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
internetZone = SecurityManager.GetStandardSandbox(evidence);
}
return internetZone;
}
}
}
}
}

Просмотреть файл

@ -1,611 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Globalization;
namespace System.Json
{
internal static class JsonValueVerifier
{
public static bool Compare(JsonValue objA, JsonValue objB)
{
if (objA == null && objB == null)
{
return true;
}
if ((objA == null && objB != null) || (objA != null && objB == null))
{
Log.Info("JsonValueVerifier Error: At least one of the JsonValue compared is null");
return false;
}
if (objA.JsonType != objB.JsonType)
{
Log.Info("JsonValueVerifier Error: These two JsonValues are not of the same Type!");
Log.Info("objA is of type {0} while objB is of type {1}", objA.JsonType.ToString(), objB.JsonType.ToString());
return false;
}
return CompareJsonValues(objA, objB);
}
public static bool CompareStringLists(List<string> strListA, List<string> strListB)
{
bool retValue = true;
if (strListA.Count != strListB.Count)
{
retValue = false;
}
else
{
for (int i = 0; i < strListA.Count; i++)
{
if (strListA[i] != strListB[i])
{
retValue = false;
break;
}
}
}
return retValue;
}
// Because we are currently taking a "flat design" model on JsonValues, the intellense doesn't work, and we have to be smart about what to verify
// and what not to so to avoid any potentially invalid access
private static bool CompareJsonValues(JsonValue objA, JsonValue objB)
{
bool retValue = false;
switch (objA.JsonType)
{
case JsonType.Array:
retValue = CompareJsonArrayTypes((JsonArray)objA, (JsonArray)objB);
break;
case JsonType.Object:
retValue = CompareJsonObjectTypes((JsonObject)objA, (JsonObject)objB);
break;
case JsonType.Boolean:
case JsonType.Number:
case JsonType.String:
retValue = CompareJsonPrimitiveTypes((JsonPrimitive)objA, (JsonPrimitive)objB);
break;
default:
Log.Info("JsonValueVerifier Error: the JsonValue isnt an array, a complex type or a primitive type!");
break;
}
return retValue;
}
private static bool CompareJsonArrayTypes(JsonArray objA, JsonArray objB)
{
bool retValue = true;
if (objA == null || objB == null || objA.Count != objB.Count || objA.IsReadOnly != objB.IsReadOnly)
{
return false;
}
try
{
for (int i = 0; i < objA.Count; i++)
{
if (!Compare(objA[i], objB[i]))
{
Log.Info("JsonValueVerifier (JsonArrayType) Error: objA[{0}] = {1}", i, objA[i].ToString());
Log.Info("JsonValueVerifier (JsonArrayType) Error: objB[{0}] = {1}", i, objB[i].ToString());
return false;
}
}
}
catch (Exception e)
{
Log.Info("JsonValueVerifier (JsonArrayType) Error: An Exception was thrown: " + e);
return false;
}
return retValue;
}
private static bool CompareJsonObjectTypes(JsonObject objA, JsonObject objB)
{
bool retValue = true;
try
{
if (objA.Keys.Count != objB.Keys.Count)
{
Log.Info("JsonValueVerifier (JsonObjectTypes) Error: objA.Keys.Count does not match objB.Keys.Count!");
Log.Info("JsonValueVerifier (JsonObjectTypes) Error: objA.Keys.Count = {0}, objB.Keys.Count = {1}", objA.Keys.Count, objB.Keys.Count);
return false;
}
if (objA.Keys.IsReadOnly != objB.Keys.IsReadOnly)
{
Log.Info("JsonValueVerifier (JsonObjectTypes) Error: objA.Keys.IsReadOnly does not match objB.Keys.IsReadOnly!");
Log.Info("JsonValueVerifier (JsonObjectTypes) Error: objA.Keys.IsReadOnly = {0}, objB.Keys.IsReadOnly = {1}", objA.Keys.IsReadOnly, objB.Keys.IsReadOnly);
return false;
}
else
{
foreach (string keyA in objA.Keys)
{
if (!objB.ContainsKey(keyA))
{
Log.Info("JsonValueVerifier (JsonObjectTypes) Error: objB does not contain Key " + keyA + "!");
return false;
}
if (!Compare(objA[keyA], objB[keyA]))
{
Log.Info("JsonValueVerifier (JsonObjectTypes) Error: objA[" + keyA + "] = " + objA[keyA]);
Log.Info("JsonValueVerifier (JsonObjectTypes) Error: objB[" + keyA + "] = " + objB[keyA]);
return false;
}
}
}
}
catch (Exception e)
{
Log.Info("JsonValueVerifier (JsonObjectTypes) Error: An Exception was thrown: " + e);
return false;
}
return retValue;
}
private static bool CompareJsonPrimitiveTypes(JsonPrimitive objA, JsonPrimitive objB)
{
try
{
if (objA.ToString() != objB.ToString())
{
// Special case due to daylight saving hours change: every March on the morning of the third Sunday, we adjust the time
// from 2am to 3am straight, so for that one hour 2:13am = 3:15am. We must result to the UTC ticks to verify the actual
// time is always the same, regardless of the loc/glob setup on the machine
if (objA.ToString().StartsWith("\"\\/Date(") && objA.ToString().EndsWith(")\\/\""))
{
return GetUTCTicks(objA) == GetUTCTicks(objB);
}
else
{
Log.Info("JsonValueVerifier (JsonPrimitiveTypes) Error: objA = " + objA.ToString());
Log.Info("JsonValueVerifier (JsonPrimitiveTypes) Error: objB = " + objB.ToString());
return false;
}
}
else
{
return true;
}
}
catch (Exception e)
{
Log.Info("JsonValueVerifier (JsonPrimitiveTypes) Error: An Exception was thrown: " + e);
return false;
}
}
// the input JsonPrimitive DateTime format is "\/Date(24735422733034-0700)\/" or "\/Date(24735422733034)\/"
// the only thing useful for us is the UTC ticks "24735422733034"
// everything after - if present - is just an optional offset between the local time and UTC
private static string GetUTCTicks(JsonPrimitive jprim)
{
string retValue = String.Empty;
string origStr = jprim.ToString();
int startIndex = origStr.IndexOf("Date(") + 5;
int endIndex = origStr.IndexOf('-', startIndex + 1); // the UTC ticks can start with a '-' sign (dates prior to 1970/01/01)
// if the optional offset is present in the data format, we want to take only the UTC ticks
if (startIndex < endIndex)
{
retValue = origStr.Substring(startIndex, endIndex - startIndex);
}
else
{
// otherwise we assume the time format is without the oiptional offset, or unexpected, and use the whole string for comparison.
retValue = origStr;
}
return retValue;
}
}
internal static class SpecialJsonValueHelper
{
public static JsonArray CreateDeepLevelJsonValuePair(int seed, out JsonArray newOrderJson)
{
Log.Info("Seed: {0}", seed);
Random rndGen = new Random(seed);
bool myBool = PrimitiveCreator.CreateInstanceOfBoolean(rndGen);
byte myByte = PrimitiveCreator.CreateInstanceOfByte(rndGen);
DateTime myDatetime = PrimitiveCreator.CreateInstanceOfDateTime(rndGen);
DateTimeOffset myDateTimeOffset = PrimitiveCreator.CreateInstanceOfDateTimeOffset(rndGen);
decimal myDecimal = PrimitiveCreator.CreateInstanceOfDecimal(rndGen);
double myDouble = PrimitiveCreator.CreateInstanceOfDouble(rndGen);
short myInt16 = PrimitiveCreator.CreateInstanceOfInt16(rndGen);
int myInt32 = PrimitiveCreator.CreateInstanceOfInt32(rndGen);
long myInt64 = PrimitiveCreator.CreateInstanceOfInt64(rndGen);
sbyte mySByte = PrimitiveCreator.CreateInstanceOfSByte(rndGen);
float mySingle = PrimitiveCreator.CreateInstanceOfSingle(rndGen);
string myString = PrimitiveCreator.CreateInstanceOfString(rndGen, 20, null);
ushort myUInt16 = PrimitiveCreator.CreateInstanceOfUInt16(rndGen);
uint myUInt32 = PrimitiveCreator.CreateInstanceOfUInt32(rndGen);
ulong myUInt64 = PrimitiveCreator.CreateInstanceOfUInt64(rndGen);
JsonArray myArray = new JsonArray { myBool, myByte, myDatetime, myDateTimeOffset, myDecimal, myDouble, myInt16, myInt32, myInt64, mySByte, mySingle, myString, myUInt16, myUInt32, myUInt64 };
JsonArray myArrayLevel2 = new JsonArray { myArray, myArray, myArray };
JsonArray myArrayLevel3 = new JsonArray { myArrayLevel2, myArrayLevel2, myArrayLevel2 };
JsonArray myArrayLevel4 = new JsonArray { myArrayLevel3, myArrayLevel3, myArrayLevel3 };
JsonArray myArrayLevel5 = new JsonArray { myArrayLevel4, myArrayLevel4, myArrayLevel4 };
JsonArray myArrayLevel6 = new JsonArray { myArrayLevel5, myArrayLevel5, myArrayLevel5 };
JsonArray myArrayLevel7 = new JsonArray { myArrayLevel6, myArrayLevel6, myArrayLevel6 };
JsonArray sourceJson = BuildJsonArrayinSequence1(myBool, myByte, myDatetime, myDateTimeOffset, myDecimal, myDouble, myInt16, myInt32, myInt64, mySByte, mySingle, myString, myUInt16, myUInt32, myUInt64, myArray, myArrayLevel2, myArrayLevel3, myArrayLevel4, myArrayLevel5, myArrayLevel6, myArrayLevel7);
newOrderJson = BuildJsonArrayinSequence2(myBool, myByte, myDatetime, myDateTimeOffset, myDecimal, myDouble, myInt16, myInt32, myInt64, mySByte, mySingle, myString, myUInt16, myUInt32, myUInt64, myArray, myArrayLevel2, myArrayLevel3, myArrayLevel4, myArrayLevel5, myArrayLevel6, myArrayLevel7);
return sourceJson;
}
public static JsonValue CreateDeepLevelJsonValue()
{
int seed = Environment.TickCount;
Log.Info("Seed: {0}", seed);
Random rndGen = new Random(seed);
bool myBool = PrimitiveCreator.CreateInstanceOfBoolean(rndGen);
byte myByte = PrimitiveCreator.CreateInstanceOfByte(rndGen);
DateTime myDatetime = PrimitiveCreator.CreateInstanceOfDateTime(rndGen);
DateTimeOffset myDateTimeOffset = PrimitiveCreator.CreateInstanceOfDateTimeOffset(rndGen);
decimal myDecimal = PrimitiveCreator.CreateInstanceOfDecimal(rndGen);
double myDouble = PrimitiveCreator.CreateInstanceOfDouble(rndGen);
short myInt16 = PrimitiveCreator.CreateInstanceOfInt16(rndGen);
int myInt32 = PrimitiveCreator.CreateInstanceOfInt32(rndGen);
long myInt64 = PrimitiveCreator.CreateInstanceOfInt64(rndGen);
sbyte mySByte = PrimitiveCreator.CreateInstanceOfSByte(rndGen);
float mySingle = PrimitiveCreator.CreateInstanceOfSingle(rndGen);
string myString = PrimitiveCreator.CreateInstanceOfString(rndGen, 20, null);
ushort myUInt16 = PrimitiveCreator.CreateInstanceOfUInt16(rndGen);
uint myUInt32 = PrimitiveCreator.CreateInstanceOfUInt32(rndGen);
ulong myUInt64 = PrimitiveCreator.CreateInstanceOfUInt64(rndGen);
JsonArray myArray = new JsonArray { myBool, myByte, myDatetime, myDateTimeOffset, myDecimal, myDouble, myInt16, myInt32, myInt64, mySByte, mySingle, myString, myUInt16, myUInt32, myUInt64 };
JsonArray myArrayLevel2 = new JsonArray { myArray, myArray, myArray };
JsonArray myArrayLevel3 = new JsonArray { myArrayLevel2, myArrayLevel2, myArrayLevel2 };
JsonArray myArrayLevel4 = new JsonArray { myArrayLevel3, myArrayLevel3, myArrayLevel3 };
JsonArray myArrayLevel5 = new JsonArray { myArrayLevel4, myArrayLevel4, myArrayLevel4 };
JsonArray myArrayLevel6 = new JsonArray { myArrayLevel5, myArrayLevel5, myArrayLevel5 };
JsonArray myArrayLevel7 = new JsonArray { myArrayLevel6, myArrayLevel6, myArrayLevel6 };
JsonArray sourceJson = BuildJsonArrayinSequence1(myBool, myByte, myDatetime, myDateTimeOffset, myDecimal, myDouble, myInt16, myInt32, myInt64, mySByte, mySingle, myString, myUInt16, myUInt32, myUInt64, myArray, myArrayLevel2, myArrayLevel3, myArrayLevel4, myArrayLevel5, myArrayLevel6, myArrayLevel7);
return sourceJson;
}
public static JsonObject CreateRandomPopulatedJsonObject(int seed, int length)
{
JsonObject myObject;
myObject = new JsonObject(
new Dictionary<string, JsonValue>()
{
{ "Name", "myArray" },
{ "Index", 1 }
});
for (int i = myObject.Count; i < length / 2; i++)
{
myObject.Add(PrimitiveCreator.CreateInstanceOfString(new Random(seed + i)), GetRandomJsonPrimitives(seed + (i * 2)));
}
for (int i = myObject.Count; i < length; i++)
{
myObject.Add(new KeyValuePair<string, JsonValue>(PrimitiveCreator.CreateInstanceOfString(new Random(seed + (i * 10))), GetRandomJsonPrimitives(seed + (i * 20))));
}
return myObject;
}
public static JsonArray CreatePrePopulatedJsonArray(int seed, int length)
{
JsonArray myObject;
myObject = new JsonArray(new List<JsonValue>());
for (int i = myObject.Count; i < length; i++)
{
myObject.Add(GetRandomJsonPrimitives(seed + i));
}
return myObject;
}
public static JsonObject CreateIndexPopulatedJsonObject(int seed, int length)
{
JsonObject myObject;
myObject = new JsonObject(new Dictionary<string, JsonValue>() { });
for (int i = myObject.Count; i < length; i++)
{
myObject.Add(i.ToString(CultureInfo.InvariantCulture), GetRandomJsonPrimitives(seed + i));
}
return myObject;
}
public static JsonValue[] CreatePrePopulatedJsonValueArray(int seed, int length)
{
JsonValue[] myObject = new JsonValue[length];
for (int i = 0; i < length; i++)
{
myObject[i] = GetRandomJsonPrimitives(seed + i);
}
return myObject;
}
public static KeyValuePair<string, JsonValue> CreatePrePopulatedKeyValuePair(int seed)
{
KeyValuePair<string, JsonValue> myObject = new KeyValuePair<string, JsonValue>(seed.ToString(), GetRandomJsonPrimitives(seed));
return myObject;
}
public static List<KeyValuePair<string, JsonValue>> CreatePrePopulatedListofKeyValuePair(int seed, int length)
{
List<KeyValuePair<string, JsonValue>> myObject = new List<KeyValuePair<string, JsonValue>>();
for (int i = 0; i < length; i++)
{
myObject.Add(CreatePrePopulatedKeyValuePair(seed + i));
}
return myObject;
}
public static JsonPrimitive GetRandomJsonPrimitives(int seed)
{
JsonPrimitive myObject;
Random rndGen = new Random(seed);
int mod = seed % 13;
switch (mod)
{
case 1:
myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfBoolean(rndGen));
break;
case 2:
myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfByte(rndGen));
break;
case 3:
myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfDateTime(rndGen));
break;
case 4:
myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfDecimal(rndGen));
break;
case 5:
myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfInt16(rndGen));
break;
case 6:
myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfInt32(rndGen));
break;
case 7:
myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfInt64(rndGen));
break;
case 8:
myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfSByte(rndGen));
break;
case 9:
myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfSingle(rndGen));
break;
case 10:
string temp;
do
{
temp = PrimitiveCreator.CreateInstanceOfString(rndGen);
}
while (temp == null);
myObject = new JsonPrimitive(temp);
break;
case 11:
myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfUInt16(rndGen));
break;
case 12:
myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfUInt32(rndGen));
break;
default:
myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfUInt64(rndGen));
break;
}
return myObject;
}
public static string GetUniqueNonNullInstanceOfString(int seed, JsonObject sourceJson)
{
string retValue = String.Empty;
Random rndGen = new Random(seed);
do
{
retValue = PrimitiveCreator.CreateInstanceOfString(rndGen);
}
while (retValue == null || sourceJson.Keys.Contains(retValue));
return retValue;
}
public static JsonPrimitive GetUniqueValue(int seed, JsonObject sourceJson)
{
JsonPrimitive newValue;
int i = 0;
do
{
newValue = SpecialJsonValueHelper.GetRandomJsonPrimitives(seed + i);
i++;
}
while (sourceJson.ToString().IndexOf(newValue.ToString()) > 0);
return newValue;
}
private static JsonArray BuildJsonArrayinSequence2(bool myBool, byte myByte, DateTime myDatetime, DateTimeOffset myDateTimeOffset, decimal myDecimal, double myDouble, short myInt16, int myInt32, long myInt64, sbyte mySByte, float mySingle, string myString, ushort myUInt16, uint myUInt32, ulong myUInt64, JsonArray myArray, JsonArray myArrayLevel2, JsonArray myArrayLevel3, JsonArray myArrayLevel4, JsonArray myArrayLevel5, JsonArray myArrayLevel6, JsonArray myArrayLevel7)
{
JsonArray newOrderJson;
newOrderJson = new JsonArray
{
new JsonObject { { "Name", "myArray" }, { "Index", 1 }, { "Obj", myArray } },
new JsonObject { { "Name", "myArrayLevel2" }, { "Index", 2 }, { "Obj", myArrayLevel2 } },
new JsonObject { { "Name", "myArrayLevel2" }, { "Index", 2 }, { "Obj", myArrayLevel2 } },
new JsonObject { { "Name", "myUInt32" }, { "Index", 21 }, { "Obj", myUInt32 } },
new JsonObject { { "Name", "myUInt32" }, { "Index", 21 }, { "Obj", myUInt32 } },
new JsonObject { { "Name", "myArrayLevel3" }, { "Index", 3 }, { "Obj", myArrayLevel3 } },
new JsonObject { { "Name", "myArrayLevel4" }, { "Index", 4 }, { "Obj", myArrayLevel4 } },
new JsonObject { { "Name", "myArrayLevel4" }, { "Index", 4 }, { "Obj", myArrayLevel4 } },
new JsonObject { { "Name", "myArrayLevel5" }, { "Index", 5 }, { "Obj", myArrayLevel5 } },
new JsonObject { { "Name", "myArrayLevel3" }, { "Index", 3 }, { "Obj", myArrayLevel3 } },
new JsonObject { { "Name", "myInt64" }, { "Index", 16 }, { "Obj", myInt64 } },
new JsonObject { { "Name", "myArrayLevel5" }, { "Index", 5 }, { "Obj", myArrayLevel5 } },
new JsonObject { { "Name", "myArrayLevel5" }, { "Index", 5 }, { "Obj", myArrayLevel5 } },
new JsonObject { { "Name", "myArrayLevel4" }, { "Index", 4 }, { "Obj", myArrayLevel4 } },
new JsonObject { { "Name", "myArrayLevel6" }, { "Index", 6 }, { "Obj", myArrayLevel6 } },
new JsonObject { { "Name", "myInt64" }, { "Index", 16 }, { "Obj", myInt64 } },
new JsonObject { { "Name", "myArrayLevel5" }, { "Index", 5 }, { "Obj", myArrayLevel5 } },
new JsonObject { { "Name", "myArrayLevel5" }, { "Index", 5 }, { "Obj", myArrayLevel5 } },
new JsonObject { { "Name", "myArrayLevel7" }, { "Index", 7 }, { "Obj", myArrayLevel7 } },
new JsonObject { { "Name", "myDecimal" }, { "Index", 12 }, { "Obj", myDecimal } },
new JsonObject { { "Name", "myArrayLevel7" }, { "Index", 7 }, { "Obj", myArrayLevel7 } },
new JsonObject { { "Name", "myArrayLevel6" }, { "Index", 6 }, { "Obj", myArrayLevel6 } },
new JsonObject { { "Name", "myArrayLevel4" }, { "Index", 4 }, { "Obj", myArrayLevel4 } },
new JsonObject { { "Name", "myArrayLevel6" }, { "Index", 6 }, { "Obj", myArrayLevel6 } },
new JsonObject { { "Name", "myArrayLevel7" }, { "Index", 7 }, { "Obj", myArrayLevel7 } },
new JsonObject { { "Name", "myBool" }, { "Index", 8 }, { "Obj", myBool } },
new JsonObject { { "Name", "myByte" }, { "Index", 9 }, { "Obj", myByte } },
null,
new JsonObject { { "Name", "myDecimal" }, { "Index", 12 }, { "Obj", myDecimal } },
new JsonObject { { "Name", "myArrayLevel7" }, { "Index", 7 }, { "Obj", myArrayLevel7 } },
new JsonObject { { "Name", "myByte" }, { "Index", 9 }, { "Obj", myByte } },
new JsonObject { { "Name", "myArrayLevel7" }, { "Index", 7 }, { "Obj", myArrayLevel7 } },
new JsonObject { { "Name", "myArrayLevel6" }, { "Index", 6 }, { "Obj", myArrayLevel6 } },
new JsonObject { { "Name", "myDatetime" }, { "Index", 10 }, { "Obj", myDatetime } },
new JsonObject { { "Name", "myArrayLevel6" }, { "Index", 6 }, { "Obj", myArrayLevel6 } },
new JsonObject { { "Name", "myDatetime" }, { "Index", 10 }, { "Obj", myDatetime } },
new JsonObject { { "Name", "myDateTimeOffset" }, { "Index", 11 }, { "Obj", myDateTimeOffset } },
new JsonObject { { "Name", "myArrayLevel7" }, { "Index", 7 }, { "Obj", myArrayLevel7 } },
new JsonObject { { "Name", "myUInt16" }, { "Index", 20 }, { "Obj", myUInt16 } },
new JsonObject { { "Name", "myDateTimeOffset" }, { "Index", 11 }, { "Obj", myDateTimeOffset } },
new JsonObject { { "Name", "myDecimal" }, { "Index", 12 }, { "Obj", myDecimal } },
new JsonObject { { "Name", "myInt32" }, { "Index", 15 }, { "Obj", myInt32 } },
new JsonObject { { "Name", "mySByte" }, { "Index", 17 }, { "Obj", mySByte } },
new JsonObject { { "Name", "myDecimal" }, { "Index", 12 }, { "Obj", myDecimal } },
new JsonObject { { "Name", "myDouble" }, { "Index", 13 }, { "Obj", myDouble } },
new JsonObject { { "Name", "myInt16" }, { "Index", 14 }, { "Obj", myInt16 } },
new JsonObject { { "Name", "myString" }, { "Index", 19 }, { "Obj", myString } },
new JsonObject { { "Name", "myUInt16" }, { "Index", 20 }, { "Obj", myUInt16 } },
new JsonObject { { "Name", "myUInt16" }, { "Index", 20 }, { "Obj", myUInt16 } },
new JsonObject { { "Name", "myArrayLevel7" }, { "Index", 7 }, { "Obj", myArrayLevel7 } },
new JsonObject { { "Name", "myUInt32" }, { "Index", 21 }, { "Obj", myUInt32 } },
new JsonObject { { "Name", "myInt16" }, { "Index", 14 }, { "Obj", myInt16 } },
new JsonObject { { "Name", "myInt32" }, { "Index", 15 }, { "Obj", myInt32 } },
new JsonObject { { "Name", "mySByte" }, { "Index", 17 }, { "Obj", mySByte } },
new JsonObject { { "Name", "myDateTimeOffset" }, { "Index", 11 }, { "Obj", myDateTimeOffset } },
new JsonObject { { "Name", "myArrayLevel6" }, { "Index", 6 }, { "Obj", myArrayLevel6 } },
new JsonObject { { "Name", "myDatetime" }, { "Index", 10 }, { "Obj", myDatetime } },
new JsonObject { { "Name", "mySByte" }, { "Index", 17 }, { "Obj", mySByte } },
new JsonObject { { "Name", "myInt32" }, { "Index", 15 }, { "Obj", myInt32 } },
new JsonObject { { "Name", "myInt64" }, { "Index", 16 }, { "Obj", myInt64 } },
new JsonObject { { "Name", "myUInt32" }, { "Index", 21 }, { "Obj", myUInt32 } },
new JsonObject { { "Name", "myArrayLevel3" }, { "Index", 3 }, { "Obj", myArrayLevel3 } },
new JsonObject { { "Name", "myInt64" }, { "Index", 16 }, { "Obj", myInt64 } },
new JsonObject { { "Name", "mySByte" }, { "Index", 17 }, { "Obj", mySByte } },
new JsonObject { { "Name", "mySByte" }, { "Index", 17 }, { "Obj", mySByte } },
new JsonObject { { "Name", "mySingle" }, { "Index", 18 }, { "Obj", mySingle } },
new JsonObject { { "Name", "myDateTimeOffset" }, { "Index", 11 }, { "Obj", myDateTimeOffset } },
new JsonObject { { "Name", "myDecimal" }, { "Index", 12 }, { "Obj", myDecimal } },
new JsonObject { { "Name", "myString" }, { "Index", 19 }, { "Obj", myString } },
new JsonObject { { "Name", "myUInt64" }, { "Index", 22 }, { "Obj", myUInt64 } }
};
return newOrderJson;
}
private static JsonArray BuildJsonArrayinSequence1(bool myBool, byte myByte, DateTime myDatetime, DateTimeOffset myDateTimeOffset, decimal myDecimal, double myDouble, short myInt16, int myInt32, long myInt64, sbyte mySByte, float mySingle, string myString, ushort myUInt16, uint myUInt32, ulong myUInt64, JsonArray myArray, JsonArray myArrayLevel2, JsonArray myArrayLevel3, JsonArray myArrayLevel4, JsonArray myArrayLevel5, JsonArray myArrayLevel6, JsonArray myArrayLevel7)
{
JsonArray sourceJson = new JsonArray
{
new JsonObject { { "Name", "myArray" }, { "Index", 1 }, { "Obj", myArray } },
new JsonObject { { "Name", "myArrayLevel2" }, { "Index", 2 }, { "Obj", myArrayLevel2 } },
new JsonObject { { "Name", "myArrayLevel2" }, { "Index", 2 }, { "Obj", myArrayLevel2 } },
new JsonObject { { "Name", "myArrayLevel3" }, { "Index", 3 }, { "Obj", myArrayLevel3 } },
new JsonObject { { "Name", "myArrayLevel3" }, { "Index", 3 }, { "Obj", myArrayLevel3 } },
new JsonObject { { "Name", "myArrayLevel3" }, { "Index", 3 }, { "Obj", myArrayLevel3 } },
new JsonObject { { "Name", "myArrayLevel4" }, { "Index", 4 }, { "Obj", myArrayLevel4 } },
new JsonObject { { "Name", "myArrayLevel4" }, { "Index", 4 }, { "Obj", myArrayLevel4 } },
new JsonObject { { "Name", "myArrayLevel4" }, { "Index", 4 }, { "Obj", myArrayLevel4 } },
new JsonObject { { "Name", "myArrayLevel4" }, { "Index", 4 }, { "Obj", myArrayLevel4 } },
new JsonObject { { "Name", "myArrayLevel5" }, { "Index", 5 }, { "Obj", myArrayLevel5 } },
new JsonObject { { "Name", "myArrayLevel5" }, { "Index", 5 }, { "Obj", myArrayLevel5 } },
new JsonObject { { "Name", "myArrayLevel5" }, { "Index", 5 }, { "Obj", myArrayLevel5 } },
new JsonObject { { "Name", "myArrayLevel5" }, { "Index", 5 }, { "Obj", myArrayLevel5 } },
new JsonObject { { "Name", "myArrayLevel5" }, { "Index", 5 }, { "Obj", myArrayLevel5 } },
new JsonObject { { "Name", "myArrayLevel6" }, { "Index", 6 }, { "Obj", myArrayLevel6 } },
new JsonObject { { "Name", "myArrayLevel6" }, { "Index", 6 }, { "Obj", myArrayLevel6 } },
new JsonObject { { "Name", "myArrayLevel6" }, { "Index", 6 }, { "Obj", myArrayLevel6 } },
new JsonObject { { "Name", "myArrayLevel6" }, { "Index", 6 }, { "Obj", myArrayLevel6 } },
new JsonObject { { "Name", "myArrayLevel6" }, { "Index", 6 }, { "Obj", myArrayLevel6 } },
new JsonObject { { "Name", "myArrayLevel6" }, { "Index", 6 }, { "Obj", myArrayLevel6 } },
new JsonObject { { "Name", "myArrayLevel7" }, { "Index", 7 }, { "Obj", myArrayLevel7 } },
new JsonObject { { "Name", "myArrayLevel7" }, { "Index", 7 }, { "Obj", myArrayLevel7 } },
new JsonObject { { "Name", "myArrayLevel7" }, { "Index", 7 }, { "Obj", myArrayLevel7 } },
new JsonObject { { "Name", "myArrayLevel7" }, { "Index", 7 }, { "Obj", myArrayLevel7 } },
new JsonObject { { "Name", "myArrayLevel7" }, { "Index", 7 }, { "Obj", myArrayLevel7 } },
new JsonObject { { "Name", "myArrayLevel7" }, { "Index", 7 }, { "Obj", myArrayLevel7 } },
new JsonObject { { "Name", "myArrayLevel7" }, { "Index", 7 }, { "Obj", myArrayLevel7 } },
new JsonObject { { "Name", "myBool" }, { "Index", 8 }, { "Obj", myBool } },
new JsonObject { { "Name", "myByte" }, { "Index", 9 }, { "Obj", myByte } },
null,
new JsonObject { { "Name", "myByte" }, { "Index", 9 }, { "Obj", myByte } },
new JsonObject { { "Name", "myDatetime" }, { "Index", 10 }, { "Obj", myDatetime } },
new JsonObject { { "Name", "myDatetime" }, { "Index", 10 }, { "Obj", myDatetime } },
new JsonObject { { "Name", "myDatetime" }, { "Index", 10 }, { "Obj", myDatetime } },
new JsonObject { { "Name", "myDateTimeOffset" }, { "Index", 11 }, { "Obj", myDateTimeOffset } },
new JsonObject { { "Name", "myDateTimeOffset" }, { "Index", 11 }, { "Obj", myDateTimeOffset } },
new JsonObject { { "Name", "myDateTimeOffset" }, { "Index", 11 }, { "Obj", myDateTimeOffset } },
new JsonObject { { "Name", "myDateTimeOffset" }, { "Index", 11 }, { "Obj", myDateTimeOffset } },
new JsonObject { { "Name", "myDecimal" }, { "Index", 12 }, { "Obj", myDecimal } },
new JsonObject { { "Name", "myDecimal" }, { "Index", 12 }, { "Obj", myDecimal } },
new JsonObject { { "Name", "myDecimal" }, { "Index", 12 }, { "Obj", myDecimal } },
new JsonObject { { "Name", "myDecimal" }, { "Index", 12 }, { "Obj", myDecimal } },
new JsonObject { { "Name", "myDecimal" }, { "Index", 12 }, { "Obj", myDecimal } },
new JsonObject { { "Name", "myDouble" }, { "Index", 13 }, { "Obj", myDouble } },
new JsonObject { { "Name", "myInt16" }, { "Index", 14 }, { "Obj", myInt16 } },
new JsonObject { { "Name", "myInt16" }, { "Index", 14 }, { "Obj", myInt16 } },
new JsonObject { { "Name", "myInt32" }, { "Index", 15 }, { "Obj", myInt32 } },
new JsonObject { { "Name", "myInt32" }, { "Index", 15 }, { "Obj", myInt32 } },
new JsonObject { { "Name", "myInt32" }, { "Index", 15 }, { "Obj", myInt32 } },
new JsonObject { { "Name", "myInt64" }, { "Index", 16 }, { "Obj", myInt64 } },
new JsonObject { { "Name", "myInt64" }, { "Index", 16 }, { "Obj", myInt64 } },
new JsonObject { { "Name", "myInt64" }, { "Index", 16 }, { "Obj", myInt64 } },
new JsonObject { { "Name", "myInt64" }, { "Index", 16 }, { "Obj", myInt64 } },
new JsonObject { { "Name", "mySByte" }, { "Index", 17 }, { "Obj", mySByte } },
new JsonObject { { "Name", "mySByte" }, { "Index", 17 }, { "Obj", mySByte } },
new JsonObject { { "Name", "mySByte" }, { "Index", 17 }, { "Obj", mySByte } },
new JsonObject { { "Name", "mySByte" }, { "Index", 17 }, { "Obj", mySByte } },
new JsonObject { { "Name", "mySByte" }, { "Index", 17 }, { "Obj", mySByte } },
new JsonObject { { "Name", "mySingle" }, { "Index", 18 }, { "Obj", mySingle } },
new JsonObject { { "Name", "myString" }, { "Index", 19 }, { "Obj", myString } },
new JsonObject { { "Name", "myString" }, { "Index", 19 }, { "Obj", myString } },
new JsonObject { { "Name", "myUInt16" }, { "Index", 20 }, { "Obj", myUInt16 } },
new JsonObject { { "Name", "myUInt16" }, { "Index", 20 }, { "Obj", myUInt16 } },
new JsonObject { { "Name", "myUInt16" }, { "Index", 20 }, { "Obj", myUInt16 } },
new JsonObject { { "Name", "myUInt32" }, { "Index", 21 }, { "Obj", myUInt32 } },
new JsonObject { { "Name", "myUInt32" }, { "Index", 21 }, { "Obj", myUInt32 } },
new JsonObject { { "Name", "myUInt32" }, { "Index", 21 }, { "Obj", myUInt32 } },
new JsonObject { { "Name", "myUInt32" }, { "Index", 21 }, { "Obj", myUInt32 } },
new JsonObject { { "Name", "myUInt64" }, { "Index", 22 }, { "Obj", myUInt64 } }
};
return sourceJson;
}
}
}

Просмотреть файл

@ -1,382 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using Xunit;
using Xunit.Extensions;
namespace System.Json
{
/// <summary>
/// JsonValue unit tests
/// </summary>
public class JsonValueTests
{
public static IEnumerable<object[]> StreamLoadingTestData
{
get
{
bool[] useSeekableStreams = new bool[] { true, false };
Dictionary<string, Encoding> allEncodings = new Dictionary<string, Encoding>
{
{ "UTF8, no BOM", new UTF8Encoding(false) },
{ "Unicode, no BOM", new UnicodeEncoding(false, false) },
{ "BigEndianUnicode, no BOM", new UnicodeEncoding(true, false) },
};
string[] jsonStrings = { "[1, 2, null, false, {\"foo\": 1, \"bar\":true, \"baz\":null}, 1.23e+56]", "4" };
foreach (string jsonString in jsonStrings)
{
foreach (bool useSeekableStream in useSeekableStreams)
{
foreach (var kvp in allEncodings)
{
yield return new object[] { jsonString, useSeekableStream, kvp.Key, kvp.Value };
}
}
}
}
}
/// <summary>
/// Tests for <see cref="JsonValue.Load(Stream)"/>.
/// </summary>
[Theory]
[PropertyData("StreamLoadingTestData")]
public void StreamLoading(string jsonString, bool useSeekableStream, string encodingName, Encoding encoding)
{
using (MemoryStream ms = new MemoryStream())
{
StreamWriter sw = new StreamWriter(ms, encoding);
sw.Write(jsonString);
sw.Flush();
Log.Info("[{0}] {1}: size of the json stream: {2}", useSeekableStream ? "seekable" : "non-seekable", encodingName, ms.Position);
ms.Position = 0;
JsonValue parsed = JsonValue.Parse(jsonString);
JsonValue loaded = useSeekableStream ? JsonValue.Load(ms) : JsonValue.Load(new NonSeekableStream(ms));
using (StringReader sr = new StringReader(jsonString))
{
JsonValue loadedFromTextReader = JsonValue.Load(sr);
Assert.Equal(parsed.ToString(), loaded.ToString());
Assert.Equal(parsed.ToString(), loadedFromTextReader.ToString());
}
}
}
[Fact]
public void ZeroedStreamLoadingThrowsFormatException()
{
ExpectException<FormatException>(delegate
{
using (MemoryStream ms = new MemoryStream(new byte[10]))
{
JsonValue.Load(ms);
}
});
}
/// <summary>
/// Tests for handling with escaped characters.
/// </summary>
[Fact]
public void EscapedCharacters()
{
string str = null;
JsonValue value = null;
str = (string)value;
Assert.Null(str);
value = "abc\b\t\r\u1234\uDC80\uDB11def\\\0ghi";
str = (string)value;
Assert.Equal("\"abc\\u0008\\u0009\\u000d\u1234\\udc80\\udb11def\\\\\\u0000ghi\"", value.ToString());
value = '\u0000';
str = (string)value;
Assert.Equal("\u0000", str);
}
/// <summary>
/// Tests for JSON objects with the special '__type' object member.
/// </summary>
[Fact]
public void TypeHintAttributeTests()
{
string json = "{\"__type\":\"TypeHint\",\"a\":123}";
JsonValue jv = JsonValue.Parse(json);
string newJson = jv.ToString();
Assert.Equal(json, newJson);
json = "{\"b\":567,\"__type\":\"TypeHint\",\"a\":123}";
jv = JsonValue.Parse(json);
newJson = jv.ToString();
Assert.Equal(json, newJson);
json = "[12,{\"__type\":\"TypeHint\",\"a\":123,\"obj\":{\"__type\":\"hint2\",\"b\":333}},null]";
jv = JsonValue.Parse(json);
newJson = jv.ToString();
Assert.Equal(json, newJson);
}
/// <summary>
/// Tests for reading JSON with different member names.
/// </summary>
[Fact]
public void ObjectNameTests()
{
string[] objectNames = new string[]
{
"simple",
"with spaces",
"with<>brackets",
"",
};
foreach (string objectName in objectNames)
{
string json = String.Format(CultureInfo.InvariantCulture, "{{\"{0}\":123}}", objectName);
JsonValue jv = JsonValue.Parse(json);
Assert.Equal(123, jv[objectName].ReadAs<int>());
string newJson = jv.ToString();
Assert.Equal(json, newJson);
JsonObject jo = new JsonObject { { objectName, 123 } };
Assert.Equal(123, jo[objectName].ReadAs<int>());
newJson = jo.ToString();
Assert.Equal(json, newJson);
}
ExpectException<FormatException>(() => JsonValue.Parse("{\"nonXmlChar\u0000\":123}"));
}
/// <summary>
/// Miscellaneous tests for parsing JSON.
/// </summary>
[Fact]
public void ParseMiscellaneousTest()
{
string[] jsonValues =
{
"[]",
"[1]",
"[1,2,3,[4.1,4.2],5]",
"{}",
"{\"a\":1}",
"{\"a\":1,\"b\":2,\"c\":3,\"d\":4}",
"{\"a\":1,\"b\":[2,3],\"c\":3}",
"{\"a\":1,\"b\":2,\"c\":[1,2,3,[4.1,4.2],5],\"d\":4}",
"{\"a\":1,\"b\":[2.1,2.2],\"c\":3,\"d\":4,\"e\":[4.1,4.2,4.3,[4.41,4.42],4.4],\"f\":5}",
"{\"a\":1,\"b\":[2.1,2.2,[[[{\"b1\":2.21}]]],2.3],\"c\":{\"d\":4,\"e\":[4.1,4.2,4.3,[4.41,4.42],4.4],\"f\":5}}"
};
foreach (string json in jsonValues)
{
JsonValue jv = JsonValue.Parse(json);
Log.Info("{0}", jv.ToString());
string jvstr = jv.ToString();
Assert.Equal(json, jvstr);
}
}
/// <summary>
/// Negative tests for parsing "unbalanced" JSON (i.e., JSON documents which aren't properly closed).
/// </summary>
[Fact]
public void ParseUnbalancedJsonTest()
{
string[] jsonValues =
{
"[",
"[1,{]",
"[1,2,3,{{}}",
"}",
"{\"a\":}",
"{\"a\":1,\"b\":[,\"c\":3,\"d\":4}",
"{\"a\":1,\"b\":[2,\"c\":3}",
"{\"a\":1,\"b\":[2.1,2.2,\"c\":3,\"d\":4,\"e\":[4.1,4.2,4.3,[4.41,4.42],4.4],\"f\":5}",
"{\"a\":1,\"b\":[2.1,2.2,[[[[{\"b1\":2.21}]]],\"c\":{\"d\":4,\"e\":[4.1,4.2,4.3,[4.41,4.42],4.4],\"f\":5}}"
};
foreach (string json in jsonValues)
{
Log.Info("Testing unbalanced JSON: {0}", json);
ExpectException<FormatException>(() => JsonValue.Parse(json));
}
}
/// <summary>
/// Test for parsing a deeply nested JSON object.
/// </summary>
[Fact]
public void ParseDeeplyNestedJsonObjectString()
{
StringBuilder builderExpected = new StringBuilder();
builderExpected.Append('{');
int depth = 10000;
for (int i = 0; i < depth; i++)
{
string key = i.ToString(CultureInfo.InvariantCulture);
builderExpected.AppendFormat("\"{0}\":{{", key);
}
for (int i = 0; i < depth + 1; i++)
{
builderExpected.Append('}');
}
string json = builderExpected.ToString();
JsonValue jsonValue = JsonValue.Parse(json);
string jvstr = jsonValue.ToString();
Assert.Equal(json, jvstr);
}
/// <summary>
/// Test for parsing a deeply nested JSON array.
/// </summary>
[Fact]
public void ParseDeeplyNestedJsonArrayString()
{
StringBuilder builderExpected = new StringBuilder();
builderExpected.Append('[');
int depth = 10000;
for (int i = 0; i < depth; i++)
{
builderExpected.Append('[');
}
for (int i = 0; i < depth + 1; i++)
{
builderExpected.Append(']');
}
string json = builderExpected.ToString();
JsonValue jsonValue = JsonValue.Parse(json);
string jvstr = jsonValue.ToString();
Assert.Equal(json, jvstr);
}
/// <summary>
/// Test for parsing a deeply nested JSON graph, containing both objects and arrays.
/// </summary>
[Fact]
public void ParseDeeplyNestedJsonString()
{
StringBuilder builderExpected = new StringBuilder();
builderExpected.Append('{');
int depth = 10000;
for (int i = 0; i < depth; i++)
{
string key = i.ToString(CultureInfo.InvariantCulture);
builderExpected.AppendFormat("\"{0}\":[{{", key);
}
for (int i = 0; i < depth; i++)
{
builderExpected.Append("}]");
}
builderExpected.Append('}');
string json = builderExpected.ToString();
JsonValue jsonValue = JsonValue.Parse(json);
string jvstr = jsonValue.ToString();
Assert.Equal(json, jvstr);
}
internal static void ExpectException<T>(Action action) where T : Exception
{
ExpectException<T>(action, null);
}
internal static void ExpectException<T>(Action action, string partOfExceptionString) where T : Exception
{
try
{
action();
Assert.False(true, "This should have thrown");
}
catch (T e)
{
if (partOfExceptionString != null)
{
Assert.True(e.Message.Contains(partOfExceptionString));
}
}
}
internal class NonSeekableStream : Stream
{
Stream innerStream;
public NonSeekableStream(Stream innerStream)
{
this.innerStream = innerStream;
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return false; }
}
public override long Position
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
public override long Length
{
get
{
throw new NotSupportedException();
}
}
public override void Flush()
{
}
public override int Read(byte[] buffer, int offset, int count)
{
return this.innerStream.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
}
}
}

Просмотреть файл

@ -1,435 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Json
{
/// <summary>
/// Test class for some scenario usages for <see cref="JsonValue"/> types.
/// </summary>
public class JsonValueUsageTest
{
/// <summary>
/// Test for consuming <see cref="JsonValue"/> objects in a Linq query.
/// </summary>
[Fact]
public void JLinqSimpleCreationQueryTest()
{
int seed = 1;
Random rndGen = new Random(seed);
JsonArray sourceJson = new JsonArray
{
new JsonObject { { "Name", "Alex" }, { "Age", 18 }, { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) } },
new JsonObject { { "Name", "Joe" }, { "Age", 19 }, { "Birthday", DateTime.MinValue } },
new JsonObject { { "Name", "Chris" }, { "Age", 20 }, { "Birthday", DateTime.Now } },
new JsonObject { { "Name", "Jeff" }, { "Age", 21 }, { "Birthday", DateTime.MaxValue } },
new JsonObject { { "Name", "Carlos" }, { "Age", 22 }, { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) } },
new JsonObject { { "Name", "Mohammad" }, { "Age", 23 }, { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) } },
new JsonObject { { "Name", "Sara" }, { "Age", 24 }, { "Birthday", new DateTime(1998, 3, 20) } },
new JsonObject { { "Name", "Tomasz" }, { "Age", 25 }, { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) } },
new JsonObject { { "Name", "Suwat" }, { "Age", 26 }, { "Birthday", new DateTime(1500, 12, 20) } },
new JsonObject { { "Name", "Eugene" }, { "Age", 27 }, { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) } }
};
var adults = from JsonValue adult in sourceJson
where (int)adult["Age"] > 21
select adult;
Log.Info("Team contains: ");
int count = 0;
foreach (JsonValue adult in adults)
{
count++;
Log.Info((string)adult["Name"]);
}
Assert.Equal(count, 6);
}
/// <summary>
/// Test for consuming <see cref="JsonValue"/> arrays in a Linq query.
/// </summary>
[Fact]
public void JLinqSimpleQueryTest()
{
JsonArray sourceJson = this.CreateArrayOfPeople();
var adults = from JsonValue adult in sourceJson
where (int)adult["Age"] > 21
select adult;
Log.Info("Team contains: ");
int count = 0;
foreach (JsonValue adult in adults)
{
count++;
Log.Info((string)adult["Name"]);
}
Assert.Equal(count, 6);
}
/// <summary>
/// Test for consuming deep <see cref="JsonValue"/> objects in a Linq query.
/// </summary>
[Fact]
public void JLinqDeepQueryTest()
{
int seed = 1;
JsonArray mixedOrderJsonObj;
JsonArray myJsonObj = SpecialJsonValueHelper.CreateDeepLevelJsonValuePair(seed, out mixedOrderJsonObj);
if (myJsonObj != null && mixedOrderJsonObj != null)
{
bool retValue = true;
var dict = new Dictionary<string, int>
{
{ "myArray", 1 },
{ "myArrayLevel2", 2 },
{ "myArrayLevel3", 3 },
{ "myArrayLevel4", 4 },
{ "myArrayLevel5", 5 },
{ "myArrayLevel6", 6 },
{ "myArrayLevel7", 7 },
{ "myBool", 8 },
{ "myByte", 9 },
{ "myDatetime", 10 },
{ "myDateTimeOffset", 11 },
{ "myDecimal", 12 },
{ "myDouble", 13 },
{ "myInt16", 14 },
{ "myInt32", 15 },
{ "myInt64", 16 },
{ "mySByte", 17 },
{ "mySingle", 18 },
{ "myString", 19 },
{ "myUInt16", 20 },
{ "myUInt32", 21 },
{ "myUInt64", 22 }
};
foreach (string name in dict.Keys)
{
if (!this.InternalVerificationViaLinqQuery(myJsonObj, name, dict[name]))
{
retValue = false;
}
if (!this.InternalVerificationViaLinqQuery(mixedOrderJsonObj, name, dict[name]))
{
retValue = false;
}
if (!this.CrossJsonValueVerificationOnNameViaLinqQuery(myJsonObj, mixedOrderJsonObj, name))
{
retValue = false;
}
if (!this.CrossJsonValueVerificationOnIndexViaLinqQuery(myJsonObj, mixedOrderJsonObj, dict[name]))
{
retValue = false;
}
}
Assert.True(retValue, "The JsonValue did not verify as expected!");
}
else
{
Assert.True(false, "Failed to create the pair of JsonValues!");
}
}
/// <summary>
/// Test for consuming <see cref="JsonValue"/> objects in a Linq query using the dynamic notation.
/// </summary>
[Fact]
public void LinqToDynamicJsonArrayTest()
{
JsonValue people = this.CreateArrayOfPeople();
var match = from person in people select person;
Assert.True(match.Count() == people.Count, "IEnumerable returned different number of elements that JsonArray contains");
int sum = 0;
foreach (KeyValuePair<string, JsonValue> kv in match)
{
sum += Int32.Parse(kv.Key);
}
Assert.True(sum == (people.Count * (people.Count - 1) / 2), "Not all elements of the array were enumerated exactly once");
match = from person in people
where person.Value.AsDynamic().Name.ReadAs<string>().StartsWith("S")
&& person.Value.AsDynamic().Age.ReadAs<int>() > 20
select person;
Assert.True(match.Count() == 2, "Number of matches was expected to be 2 but was " + match.Count());
}
/// <summary>
/// Test for consuming <see cref="JsonValue"/> objects in a Linq query.
/// </summary>
[Fact]
public void LinqToJsonObjectTest()
{
JsonValue person = this.CreateArrayOfPeople()[0];
var match = from nameValue in person select nameValue;
Assert.True(match.Count() == 3, "IEnumerable of JsonObject returned a different number of elements than there are name value pairs in the JsonObject" + match.Count());
List<string> missingNames = new List<string>(new string[] { "Name", "Age", "Birthday" });
foreach (KeyValuePair<string, JsonValue> kv in match)
{
Assert.Equal(person[kv.Key], kv.Value);
missingNames.Remove(kv.Key);
}
Assert.True(missingNames.Count == 0, "Not all JsonObject properties were present in the enumeration");
}
/// <summary>
/// Test for consuming <see cref="JsonValue"/> objects in a Linq query.
/// </summary>
[Fact]
public void LinqToJsonObjectAsAssociativeArrayTest()
{
JsonValue gameScores = new JsonObject(new Dictionary<string, JsonValue>()
{
{ "tomek", 12 },
{ "suwat", 27 },
{ "carlos", 127 },
{ "miguel", 57 },
{ "henrik", 2 },
{ "joe", 15 }
});
var match = from score in gameScores
where score.Key.Contains("o") && score.Value.ReadAs<int>() > 100
select score;
Assert.True(match.Count() == 1, "Incorrect number of matching game scores");
}
/// <summary>
/// Test for consuming <see cref="JsonPrimitive"/> objects in a Linq query.
/// </summary>
[Fact]
public void LinqToJsonPrimitiveTest()
{
JsonValue primitive = 12;
var match = from m in primitive select m;
KeyValuePair<string, JsonValue>[] kv = match.ToArray();
Assert.True(kv.Length == 0);
}
/// <summary>
/// Test for consuming <see cref="JsonValue"/> objects with <see cref="JsonType">JsonType.Default</see> in a Linq query.
/// </summary>
[Fact]
public void LinqToJsonUndefinedTest()
{
JsonValue primitive = 12;
var match = from m in primitive.ValueOrDefault("idontexist")
select m;
Assert.True(match.Count() == 0);
}
/// <summary>
/// Test for consuming calling <see cref="JsonValue.ReadAs{T}(T)"/> in a Linq query.
/// </summary>
[Fact]
public void LinqToDynamicJsonUndefinedWithFallbackTest()
{
JsonValue people = this.CreateArrayOfPeople();
var match = from person in people
where person.Value.AsDynamic().IDontExist.IAlsoDontExist.ReadAs<int>(5) > 2
select person;
Assert.True(match.Count() == people.Count, "Number of matches was expected to be " + people.Count + " but was " + match.Count());
match = from person in people
where person.Value.AsDynamic().Age.ReadAs<int>(1) < 21
select person;
Assert.True(match.Count() == 3);
}
private JsonArray CreateArrayOfPeople()
{
int seed = 1;
Random rndGen = new Random(seed);
return new JsonArray(new List<JsonValue>()
{
new JsonObject(new Dictionary<string, JsonValue>()
{
{ "Name", "Alex" },
{ "Age", 18 },
{ "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) }
}),
new JsonObject(new Dictionary<string, JsonValue>()
{
{ "Name", "Joe" },
{ "Age", 19 },
{ "Birthday", DateTime.MinValue }
}),
new JsonObject(new Dictionary<string, JsonValue>()
{
{ "Name", "Chris" },
{ "Age", 20 },
{ "Birthday", DateTime.Now }
}),
new JsonObject(new Dictionary<string, JsonValue>()
{
{ "Name", "Jeff" },
{ "Age", 21 },
{ "Birthday", DateTime.MaxValue }
}),
new JsonObject(new Dictionary<string, JsonValue>()
{
{ "Name", "Carlos" },
{ "Age", 22 },
{ "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) }
}),
new JsonObject(new Dictionary<string, JsonValue>()
{
{ "Name", "Mohammad" },
{ "Age", 23 },
{ "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) }
}),
new JsonObject(new Dictionary<string, JsonValue>()
{
{ "Name", "Sara" },
{ "Age", 24 },
{ "Birthday", new DateTime(1998, 3, 20) }
}),
new JsonObject(new Dictionary<string, JsonValue>()
{
{ "Name", "Tomasz" },
{ "Age", 25 },
{ "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) }
}),
new JsonObject(new Dictionary<string, JsonValue>()
{
{ "Name", "Suwat" },
{ "Age", 26 },
{ "Birthday", new DateTime(1500, 12, 20) }
}),
new JsonObject(new Dictionary<string, JsonValue>()
{
{ "Name", "Eugene" },
{ "Age", 27 },
{ "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) }
})
});
}
private bool InternalVerificationViaLinqQuery(JsonArray sourceJson, string name, int index)
{
var itemsByName = from JsonValue itemByName in sourceJson
where (itemByName != null && (string)itemByName["Name"] == name)
select itemByName;
int countByName = 0;
foreach (JsonValue a in itemsByName)
{
countByName++;
}
Log.Info("Collection contains: " + countByName + " item By Name " + name);
var itemsByIndex = from JsonValue itemByIndex in sourceJson
where (itemByIndex != null && (int)itemByIndex["Index"] == index)
select itemByIndex;
int countByIndex = 0;
foreach (JsonValue a in itemsByIndex)
{
countByIndex++;
}
Log.Info("Collection contains: " + countByIndex + " item By Index " + index);
if (countByIndex != countByName)
{
Log.Info("Count by Name = " + countByName + "; Count by Index = " + countByIndex);
Log.Info("The number of items matching the provided Name does NOT equal to that matching the provided Index, The two JsonValues are not equal!");
return false;
}
else
{
return true;
}
}
private bool CrossJsonValueVerificationOnNameViaLinqQuery(JsonArray sourceJson, JsonArray newJson, string name)
{
var itemsByName = from JsonValue itemByName in sourceJson
where (itemByName != null && (string)itemByName["Name"] == name)
select itemByName;
int countByName = 0;
foreach (JsonValue a in itemsByName)
{
countByName++;
}
Log.Info("Original Collection contains: " + countByName + " item By Name " + name);
var newItemsByName = from JsonValue newItemByName in newJson
where (newItemByName != null && (string)newItemByName["Name"] == name)
select newItemByName;
int newcountByName = 0;
foreach (JsonValue a in newItemsByName)
{
newcountByName++;
}
Log.Info("New Collection contains: " + newcountByName + " item By Name " + name);
if (countByName != newcountByName)
{
Log.Info("Count by Original JsonValue = " + countByName + "; Count by New JsonValue = " + newcountByName);
Log.Info("The number of items matching the provided Name does NOT equal between these two JsonValues!");
return false;
}
else
{
return true;
}
}
private bool CrossJsonValueVerificationOnIndexViaLinqQuery(JsonArray sourceJson, JsonArray newJson, int index)
{
var itemsByIndex = from JsonValue itemByIndex in sourceJson
where (itemByIndex != null && (int)itemByIndex["Index"] == index)
select itemByIndex;
int countByIndex = 0;
foreach (JsonValue a in itemsByIndex)
{
countByIndex++;
}
Log.Info("Original Collection contains: " + countByIndex + " item By Index " + index);
var newItemsByIndex = from JsonValue newItemByIndex in newJson
where (newItemByIndex != null && (int)newItemByIndex["Index"] == index)
select newItemByIndex;
int newcountByIndex = 0;
foreach (JsonValue a in newItemsByIndex)
{
newcountByIndex++;
}
Log.Info("New Collection contains: " + newcountByIndex + " item By Index " + index);
if (countByIndex != newcountByIndex)
{
Log.Info("Count by Original JsonValue = " + countByIndex + "; Count by New JsonValue = " + newcountByIndex);
Log.Info("The number of items matching the provided Index does NOT equal between these two JsonValues!");
return false;
}
else
{
return true;
}
}
}
}

Просмотреть файл

@ -1,36 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("System.Json.Test.Integration")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("System.Json.Test.Integration")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("750a87c6-d9c9-476b-89ab-b3b3bce96bec")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Просмотреть файл

@ -1,87 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\tools\WebStack.settings.targets" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{A7B1264E-BCE5-42A8-8B5E-001A5360B128}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>System.Json.Test.Integration</RootNamespace>
<AssemblyName>System.Json.Test.Integration</AssemblyName>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>$(WebStackRootPath)\bin\Debug\Test\</OutputPath>
<DefineConstants>TRACE;DEBUG</DefineConstants>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>$(WebStackRootPath)\bin\Release\Test\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'CodeCoverage' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>$(WebStackRootPath)\bin\CodeCoverage\Test\</OutputPath>
<DefineConstants>TRACE;DEBUG</DefineConstants>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="System" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.XML" />
<Reference Include="xunit, Version=1.9.0.1566, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\..\packages\xunit.1.9.0.1566\lib\xunit.dll</HintPath>
</Reference>
<Reference Include="xunit.extensions, Version=1.9.0.1566, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\..\packages\xunit.extensions.1.9.0.1566\lib\xunit.extensions.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Common\InstanceCreator.cs" />
<Compile Include="Common\Log.cs" />
<Compile Include="Common\TypeLibrary.cs" />
<Compile Include="Common\Util.cs" />
<Compile Include="JObjectFunctionalTest.cs" />
<Compile Include="JsonPrimitiveTests.cs" />
<Compile Include="JsonStringRoundTripTests.cs" />
<Compile Include="JsonValueAndComplexTypesTests.cs" />
<Compile Include="JsonValueDynamicTests.cs" />
<Compile Include="JsonValueEventsTests.cs" />
<Compile Include="JsonValueLinqExtensionsIntegrationTest.cs" />
<Compile Include="JsonValuePartialTrustTests.cs" />
<Compile Include="JsonValueTestHelper.cs" />
<Compile Include="JsonValueTests.cs" />
<Compile Include="JsonValueUsageTest.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\System.Json\System.Json.csproj">
<Project>{F0441BE9-BDC0-4629-BE5A-8765FFAA2481}</Project>
<Name>System.Json</Name>
</ProjectReference>
<ProjectReference Include="..\Microsoft.TestCommon\Microsoft.TestCommon.csproj">
<Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>
<Name>Microsoft.TestCommon</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>

Просмотреть файл

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="xunit" version="1.9.0.1566" />
<package id="xunit.extensions" version="1.9.0.1566" />
</packages>

Просмотреть файл

@ -1,222 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Dynamic;
using System.Linq.Expressions;
using System.Reflection;
namespace System.Json
{
public static class AnyInstance
{
public const bool AnyBool = true;
public const string AnyString = "hello";
public const string AnyString2 = "world";
public const char AnyChar = 'c';
public const int AnyInt = 123456789;
[CLSCompliant(false)]
public const uint AnyUInt = 3123456789;
public const long AnyLong = 123456789012345L;
[CLSCompliant(false)]
public const ulong AnyULong = UInt64.MaxValue;
public const short AnyShort = -12345;
[CLSCompliant(false)]
public const ushort AnyUShort = 40000;
public const byte AnyByte = 0xDC;
[CLSCompliant(false)]
public const sbyte AnySByte = -34;
public const double AnyDouble = 123.45;
public const float AnyFloat = 23.4f;
public const decimal AnyDecimal = 1234.5678m;
public static readonly Guid AnyGuid = new Guid(0x11223344, 0x5566, 0x7788, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00);
public static readonly DateTime AnyDateTime = new DateTime(2010, 02, 15, 22, 45, 20, DateTimeKind.Utc);
public static readonly DateTimeOffset AnyDateTimeOffset = new DateTimeOffset(2010, 2, 5, 15, 45, 20, TimeSpan.FromHours(-3));
public static readonly Uri AnyUri = new Uri("http://tempuri.org/");
public static readonly JsonArray AnyJsonArray;
public static readonly JsonObject AnyJsonObject;
public static readonly JsonPrimitive AnyJsonPrimitive = new JsonPrimitive("hello");
public static readonly JsonValue AnyJsonValue1 = AnyJsonPrimitive;
public static readonly JsonValue AnyJsonValue2;
public static readonly JsonValue AnyJsonValue3 = null;
public static readonly JsonValue DefaultJsonValue = GetDefaultJsonValue();
public static readonly Person AnyPerson = Person.CreateSample();
public static readonly Address AnyAddress = Address.CreateSample();
public static readonly dynamic AnyDynamic = TestDynamicObject.CreatePersonAsDynamic(AnyPerson);
public static JsonValue[] AnyJsonValueArray
{
get
{
return new JsonValue[]
{
AnyInstance.AnyJsonArray,
AnyInstance.AnyJsonObject,
AnyInstance.AnyJsonPrimitive,
AnyInstance.DefaultJsonValue
};
}
}
static AnyInstance()
{
AnyJsonArray = new JsonArray { 1, 2, 3 };
AnyJsonObject = new JsonObject { { "one", 1 }, { "two", 2 } };
AnyJsonArray.Changing += new EventHandler<JsonValueChangeEventArgs>(PreventChanging);
AnyJsonObject.Changing += new EventHandler<JsonValueChangeEventArgs>(PreventChanging);
AnyJsonValue2 = AnyJsonArray;
}
private static void PreventChanging(object sender, JsonValueChangeEventArgs e)
{
throw new InvalidOperationException("AnyInstance.AnyJsonArray or AnyJsonObject cannot be modified; please clone the instance if the test needs to change it.");
}
private static JsonValue GetDefaultJsonValue()
{
PropertyInfo propInfo = typeof(JsonValue).GetProperty("DefaultInstance", BindingFlags.Static | BindingFlags.NonPublic);
return propInfo.GetValue(null, null) as JsonValue;
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Address Address { get; set; }
public List<Person> Friends { get; set; }
public static Person CreateSample()
{
Person anyObject = new Person
{
Name = AnyInstance.AnyString,
Age = AnyInstance.AnyInt,
Address = Address.CreateSample(),
Friends = new List<Person> { new Person { Name = "Bill Gates", Age = 23, Address = Address.CreateSample() }, new Person { Name = "Steve Ballmer", Age = 19, Address = Address.CreateSample() } }
};
return anyObject;
}
public string FriendsToString()
{
string s = "";
if (this.Friends != null)
{
foreach (Person p in this.Friends)
{
s += p + ",";
}
}
return s;
}
public override string ToString()
{
return String.Format("{0}, {1}, [{2}], Friends=[{3}]", this.Name, this.Age, this.Address, this.FriendsToString());
}
}
public class Address
{
public const string AnyStreet = "123 1st Ave";
public const string AnyCity = "Springfield";
public const string AnyState = "ZZ";
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public static Address CreateSample()
{
Address address = new Address
{
Street = AnyStreet,
City = AnyCity,
State = AnyState,
};
return address;
}
public override string ToString()
{
return String.Format("{0}, {1}, {2}", this.Street, this.City, this.State);
}
}
public class TestDynamicObject : DynamicObject
{
private IDictionary<string, object> _values = new Dictionary<string, object>();
public bool UseFallbackMethod { get; set; }
public bool UseErrorSuggestion { get; set; }
public string TestProperty { get; set; }
public override IEnumerable<string> GetDynamicMemberNames()
{
return _values.Keys;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_values[binder.Name] = value;
return true;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (this.UseFallbackMethod)
{
DynamicMetaObject target = new DynamicMetaObject(Expression.Parameter(this.GetType()), BindingRestrictions.Empty);
DynamicMetaObject errorSuggestion = null;
if (this.UseErrorSuggestion)
{
errorSuggestion = new DynamicMetaObject(Expression.Throw(Expression.Constant(new TestDynamicObjectException())), BindingRestrictions.Empty);
}
DynamicMetaObject metaObj = binder.FallbackGetMember(target, errorSuggestion);
Expression<Action> lambda = Expression.Lambda<Action>(metaObj.Expression, new ParameterExpression[] { });
lambda.Compile().Invoke();
}
return _values.TryGetValue(binder.Name, out result);
}
public static dynamic CreatePersonAsDynamic(Person person)
{
dynamic dynObj = new TestDynamicObject();
dynObj.Name = person.Name;
dynObj.Age = person.Age;
dynObj.Address = new Address();
dynObj.Address.City = person.Address.City;
dynObj.Address.Street = person.Address.Street;
dynObj.Address.State = person.Address.State;
dynObj.Friends = person.Friends;
return dynObj;
}
public class TestDynamicObjectException : Exception
{
}
}
}

Просмотреть файл

@ -1,29 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using Xunit;
namespace System.Json
{
public static class ExceptionHelper
{
public static void Throws<TException>(Assert.ThrowsDelegate act, Action<TException> exceptionAssert) where TException : Exception
{
Exception ex = Record.Exception(act);
Assert.NotNull(ex);
TException tex = Assert.IsAssignableFrom<TException>(ex);
exceptionAssert(tex);
}
public static void Throws<TException>(Assert.ThrowsDelegate act, string message) where TException : Exception
{
Throws<TException>(act, ex => Assert.Equal(message, ex.Message));
}
public static void Throws<TException>(Assert.ThrowsDelegate act) where TException : Exception
{
Throws<TException>(act, _ => { });
}
}
}

Просмотреть файл

@ -1,478 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using Xunit;
using Xunit.Extensions;
namespace System.Json
{
public class JsonValueExtensionsTest
{
const string DynamicPropertyNotDefined = "'{0}' does not contain a definition for property '{1}'.";
const string OperationNotSupportedOnJsonTypeMsgFormat = "Operation not supported on JsonValue instance of 'JsonType.{0}' type.";
[Fact]
public void CreateFromTypeTest()
{
JsonValue[] values =
{
AnyInstance.AnyJsonObject,
AnyInstance.AnyJsonArray,
AnyInstance.AnyJsonPrimitive,
AnyInstance.DefaultJsonValue
};
foreach (JsonValue value in values)
{
Assert.Same(value, JsonValueExtensions.CreateFrom(value));
}
}
public static IEnumerable<object[]> PrimitiveTestData
{
get
{
yield return new object[] { AnyInstance.AnyBool };
yield return new object[] { AnyInstance.AnyByte };
yield return new object[] { AnyInstance.AnyChar };
yield return new object[] { AnyInstance.AnyDateTime };
yield return new object[] { AnyInstance.AnyDateTimeOffset };
yield return new object[] { AnyInstance.AnyDecimal };
yield return new object[] { AnyInstance.AnyDouble };
yield return new object[] { AnyInstance.AnyFloat };
yield return new object[] { AnyInstance.AnyGuid };
yield return new object[] { AnyInstance.AnyLong };
yield return new object[] { AnyInstance.AnySByte };
yield return new object[] { AnyInstance.AnyShort };
yield return new object[] { AnyInstance.AnyUInt };
yield return new object[] { AnyInstance.AnyULong };
yield return new object[] { AnyInstance.AnyUri };
yield return new object[] { AnyInstance.AnyUShort };
yield return new object[] { AnyInstance.AnyInt };
yield return new object[] { AnyInstance.AnyString };
}
}
[Theory]
[PropertyData("PrimitiveTestData")]
public void CreateFromPrimitiveTest(object value)
{
Type valueType = value.GetType();
Assert.Equal(value, JsonValueExtensions.CreateFrom(value).ReadAs(valueType));
}
[Fact]
public void CreateFromComplexTest()
{
JsonValue target = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);
Assert.Equal(AnyInstance.AnyPerson.Name, (string)target["Name"]);
Assert.Equal(AnyInstance.AnyPerson.Age, (int)target["Age"]);
Assert.Equal(AnyInstance.AnyPerson.Address.City, (string)target.ValueOrDefault("Address", "City"));
}
[Fact]
public void CreateFromDynamicSimpleTest()
{
JsonValue target;
target = JsonValueExtensions.CreateFrom(AnyInstance.AnyDynamic);
Assert.NotNull(target);
string expected = "{\"Name\":\"Bill Gates\",\"Age\":21,\"Grades\":[\"F\",\"B-\",\"C\"]}";
dynamic obj = new TestDynamicObject();
obj.Name = "Bill Gates";
obj.Age = 21;
obj.Grades = new[] { "F", "B-", "C" };
target = JsonValueExtensions.CreateFrom(obj);
Assert.Equal<string>(expected, target.ToString());
target = JsonValueExtensions.CreateFrom(new TestDynamicObject());
Assert.Equal<string>("{}", target.ToString());
}
[Fact]
public void CreateFromDynamicComplextTest()
{
JsonValue target;
Person person = AnyInstance.AnyPerson;
dynamic dyn = TestDynamicObject.CreatePersonAsDynamic(person);
dyn.TestProperty = AnyInstance.AnyString;
target = JsonValueExtensions.CreateFrom(dyn);
Assert.NotNull(target);
Assert.Equal<string>(AnyInstance.AnyString, dyn.TestProperty);
Person jvPerson = target.ReadAsType<Person>();
Assert.Equal(person.ToString(), jvPerson.ToString());
Person p1 = Person.CreateSample();
Person p2 = Person.CreateSample();
p2.Name += "__2";
p2.Age += 10;
p2.Address.City += "__2";
Person[] friends = new Person[] { p1, p2 };
target = JsonValueExtensions.CreateFrom(friends);
Person[] personArr = target.ReadAsType<Person[]>();
Assert.Equal<int>(friends.Length, personArr.Length);
Assert.Equal<string>(friends[0].ToString(), personArr[0].ToString());
Assert.Equal<string>(friends[1].ToString(), personArr[1].ToString());
}
[Fact]
public void CreateFromDynamicBinderFallbackTest()
{
JsonValue target;
Person person = AnyInstance.AnyPerson;
dynamic dyn = new TestDynamicObject();
dyn.Name = AnyInstance.AnyString;
dyn.UseFallbackMethod = true;
string expectedMessage = String.Format(DynamicPropertyNotDefined, dyn.GetType().FullName, "Name");
ExceptionHelper.Throws<InvalidOperationException>(() => target = JsonValueExtensions.CreateFrom(dyn), expectedMessage);
dyn.UseErrorSuggestion = true;
ExceptionHelper.Throws<TestDynamicObject.TestDynamicObjectException>(() => target = JsonValueExtensions.CreateFrom(dyn));
}
[Fact]
public void CreateFromNestedDynamicTest()
{
JsonValue target;
string expected = "{\"Name\":\"Root\",\"Level1\":{\"Name\":\"Level1\",\"Level2\":{\"Name\":\"Level2\"}}}";
dynamic dyn = new TestDynamicObject();
dyn.Name = "Root";
dyn.Level1 = new TestDynamicObject();
dyn.Level1.Name = "Level1";
dyn.Level1.Level2 = new TestDynamicObject();
dyn.Level1.Level2.Name = "Level2";
target = JsonValueExtensions.CreateFrom(dyn);
Assert.NotNull(target);
Assert.Equal<string>(expected, target.ToString());
}
[Fact]
public void CreateFromDynamicWithJsonValueChildrenTest()
{
JsonValue target;
string level3 = "{\"Name\":\"Level3\",\"Null\":null}";
string level2 = "{\"Name\":\"Level2\",\"JsonObject\":" + AnyInstance.AnyJsonObject.ToString() + ",\"JsonArray\":" + AnyInstance.AnyJsonArray.ToString() + ",\"Level3\":" + level3 + "}";
string level1 = "{\"Name\":\"Level1\",\"JsonPrimitive\":" + AnyInstance.AnyJsonPrimitive.ToString() + ",\"Level2\":" + level2 + "}";
string expected = "{\"Name\":\"Root\",\"Level1\":" + level1 + "}";
dynamic dyn = new TestDynamicObject();
dyn.Name = "Root";
dyn.Level1 = new TestDynamicObject();
dyn.Level1.Name = "Level1";
dyn.Level1.JsonPrimitive = AnyInstance.AnyJsonPrimitive;
dyn.Level1.Level2 = new TestDynamicObject();
dyn.Level1.Level2.Name = "Level2";
dyn.Level1.Level2.JsonObject = AnyInstance.AnyJsonObject;
dyn.Level1.Level2.JsonArray = AnyInstance.AnyJsonArray;
dyn.Level1.Level2.Level3 = new TestDynamicObject();
dyn.Level1.Level2.Level3.Name = "Level3";
dyn.Level1.Level2.Level3.Null = null;
target = JsonValueExtensions.CreateFrom(dyn);
Assert.Equal<string>(expected, target.ToString());
}
[Fact]
public void CreateFromDynamicJVTest()
{
JsonValue target;
dynamic[] values = new dynamic[]
{
AnyInstance.AnyJsonArray,
AnyInstance.AnyJsonObject,
AnyInstance.AnyJsonPrimitive,
AnyInstance.DefaultJsonValue
};
foreach (dynamic dyn in values)
{
target = JsonValueExtensions.CreateFrom(dyn);
Assert.Same(dyn, target);
}
}
[Fact]
public void ReadAsTypeFallbackTest()
{
JsonValue jv = AnyInstance.AnyInt;
Person personFallback = Person.CreateSample();
Person personResult = jv.ReadAsType<Person>(personFallback);
Assert.Same(personFallback, personResult);
int intFallback = 45;
int intValue = jv.ReadAsType<int>(intFallback);
Assert.Equal<int>(AnyInstance.AnyInt, intValue);
}
[Fact(Skip = "See bug #228569 in CSDMain")]
public void ReadAsTypeCollectionTest()
{
JsonValue jsonValue;
jsonValue = JsonValue.Parse("[1,2,3]");
List<object> list = jsonValue.ReadAsType<List<object>>();
Array array = jsonValue.ReadAsType<Array>();
object[] objArr = jsonValue.ReadAsType<object[]>();
IList[] collections =
{
list, array, objArr
};
foreach (IList collection in collections)
{
Assert.Equal<int>(jsonValue.Count, collection.Count);
for (int i = 0; i < jsonValue.Count; i++)
{
Assert.Equal<int>((int)jsonValue[i], (int)collection[i]);
}
}
jsonValue = JsonValue.Parse("{\"A\":1,\"B\":2,\"C\":3}");
Dictionary<string, object> dictionary = jsonValue.ReadAsType<Dictionary<string, object>>();
Assert.Equal<int>(jsonValue.Count, dictionary.Count);
foreach (KeyValuePair<string, JsonValue> pair in jsonValue)
{
Assert.Equal((int)jsonValue[pair.Key], (int)dictionary[pair.Key]);
}
}
[Fact]
public void TryReadAsInvalidCollectionTest()
{
JsonValue jo = AnyInstance.AnyJsonObject;
JsonValue ja = AnyInstance.AnyJsonArray;
JsonValue jp = AnyInstance.AnyJsonPrimitive;
JsonValue jd = AnyInstance.DefaultJsonValue;
JsonValue[] invalidArrays =
{
jo, jp, jd
};
JsonValue[] invalidDictionaries =
{
ja, jp, jd
};
bool success;
object[] array;
Dictionary<string, object> dictionary;
foreach (JsonValue value in invalidArrays)
{
success = value.TryReadAsType<object[]>(out array);
Console.WriteLine("Try reading {0} as object[]; success = {1}", value.ToString(), success);
Assert.False(success);
Assert.Null(array);
}
foreach (JsonValue value in invalidDictionaries)
{
success = value.TryReadAsType<Dictionary<string, object>>(out dictionary);
Console.WriteLine("Try reading {0} as Dictionary<string, object>; success = {1}", value.ToString(), success);
Assert.False(success);
Assert.Null(dictionary);
}
}
[Fact]
public void ReadAsExtensionsOnDynamicTest()
{
dynamic jv = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);
bool success;
object obj;
success = jv.TryReadAsType(typeof(Person), out obj);
Assert.True(success);
Assert.NotNull(obj);
Assert.Equal<string>(AnyInstance.AnyPerson.ToString(), obj.ToString());
obj = jv.ReadAsType(typeof(Person));
Assert.NotNull(obj);
Assert.Equal<string>(AnyInstance.AnyPerson.ToString(), obj.ToString());
}
#if CODEPLEX
[Fact]
public void ToCollectionTest()
{
JsonValue target;
object[] array;
target = AnyInstance.AnyJsonArray;
array = target.ToObjectArray();
Assert.Equal(target.Count, array.Length);
for (int i = 0; i < target.Count; i++)
{
Assert.Equal(array[i], target[i].ReadAs(array[i].GetType()));
}
target = AnyInstance.AnyJsonObject;
IDictionary<string, object> dictionary = target.ToDictionary();
Assert.Equal(target.Count, dictionary.Count);
foreach (KeyValuePair<string, JsonValue> pair in target)
{
Assert.True(dictionary.ContainsKey(pair.Key));
Assert.Equal<string>(target[pair.Key].ToString(), dictionary[pair.Key].ToString());
}
}
[Fact]
public void ToCollectionsNestedTest()
{
JsonArray ja = JsonValue.Parse("[1, {\"A\":[1,2,3]}, 5]") as JsonArray;
JsonObject jo = JsonValue.Parse("{\"A\":1,\"B\":[1,2,3]}") as JsonObject;
object[] objArray = ja.ToObjectArray();
Assert.NotNull(objArray);
Assert.Equal<int>(ja.Count, objArray.Length);
Assert.Equal((int)ja[0], (int)objArray[0]);
Assert.Equal((int)ja[2], (int)objArray[2]);
IDictionary<string, object> dict = objArray[1] as IDictionary<string, object>;
Assert.NotNull(dict);
objArray = dict["A"] as object[];
Assert.NotNull(objArray);
for (int i = 0; i < 3; i++)
{
Assert.Equal(i + 1, (int)objArray[i]);
}
dict = jo.ToDictionary();
Assert.NotNull(dict);
Assert.Equal<int>(jo.Count, dict.Count);
Assert.Equal<int>(1, (int)dict["A"]);
objArray = dict["B"] as object[];
Assert.NotNull(objArray);
for (int i = 1; i < 3; i++)
{
Assert.Equal(i + 1, (int)objArray[i]);
}
}
[Fact]
public void ToCollectionsInvalidTest()
{
JsonValue jo = AnyInstance.AnyJsonObject;
JsonValue ja = AnyInstance.AnyJsonArray;
JsonValue jp = AnyInstance.AnyJsonPrimitive;
JsonValue jd = AnyInstance.DefaultJsonValue;
ExceptionTestHelper.ExpectException<NotSupportedException>(delegate { var ret = jd.ToObjectArray(); }, String.Format(OperationNotSupportedOnJsonTypeMsgFormat, jd.JsonType));
ExceptionTestHelper.ExpectException<NotSupportedException>(delegate { var ret = jd.ToDictionary(); }, String.Format(OperationNotSupportedOnJsonTypeMsgFormat, jd.JsonType));
ExceptionTestHelper.ExpectException<NotSupportedException>(delegate { var ret = jp.ToObjectArray(); }, String.Format(OperationNotSupportedOnJsonTypeMsgFormat, jp.JsonType));
ExceptionTestHelper.ExpectException<NotSupportedException>(delegate { var ret = jp.ToDictionary(); }, String.Format(OperationNotSupportedOnJsonTypeMsgFormat, jp.JsonType));
ExceptionTestHelper.ExpectException<NotSupportedException>(delegate { var ret = jo.ToObjectArray(); }, String.Format(OperationNotSupportedOnJsonTypeMsgFormat, jo.JsonType));
ExceptionTestHelper.ExpectException<NotSupportedException>(delegate { var ret = ja.ToDictionary(); }, String.Format(OperationNotSupportedOnJsonTypeMsgFormat, ja.JsonType));
}
// 195843 JsonValue to support generic extension methods defined in JsonValueExtensions.
// 195867 Consider creating extension point for allowing new extension methods to be callable via dynamic interface
//[Fact] This requires knowledge of the C# binder to be able to get the generic call parameters.
public void ReadAsGenericExtensionsOnDynamicTest()
{
dynamic jv = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);
Person person;
bool success;
person = jv.ReadAsType<Person>();
Assert.NotNull(person);
Assert.Equal<string>(AnyInstance.AnyPerson.ToString(), person.ToString());
success = jv.TryReadAsType<Person>(out person);
Assert.True(success);
Assert.NotNull(person);
Assert.Equal<string>(AnyInstance.AnyPerson.ToString(), person.ToString());
}
#else
[Fact(Skip = "See bug #228569 in CSDMain")]
public void TestDataContractJsonSerializerSettings()
{
TestTypeForSerializerSettings instance = new TestTypeForSerializerSettings
{
BaseRef = new DerivedType(),
Date = AnyInstance.AnyDateTime,
Dict = new Dictionary<string, object>
{
{ "one", 1 },
{ "two", 2 },
{ "two point five", 2.5 },
}
};
JsonObject dict = new JsonObject
{
{ "one", 1 },
{ "two", 2 },
{ "two point five", 2.5 },
};
JsonObject equivalentJsonObject = new JsonObject
{
{ "BaseRef", new JsonObject { { "__type", "DerivedType:NS" } } },
{ "Date", AnyInstance.AnyDateTime },
{ "Dict", dict },
};
JsonObject createdFromType = JsonValueExtensions.CreateFrom(instance) as JsonObject;
Assert.Equal(equivalentJsonObject.ToString(), createdFromType.ToString());
TestTypeForSerializerSettings newInstance = equivalentJsonObject.ReadAsType<TestTypeForSerializerSettings>();
// DISABLED, 198487 - Assert.Equal(instance.Date, newInstance.Date);
Assert.Equal(instance.BaseRef.GetType().FullName, newInstance.BaseRef.GetType().FullName);
Assert.Equal(3, newInstance.Dict.Count);
Assert.Equal(1, newInstance.Dict["one"]);
Assert.Equal(2, newInstance.Dict["two"]);
Assert.Equal(2.5, Convert.ToDouble(newInstance.Dict["two point five"], CultureInfo.InvariantCulture));
}
[DataContract]
public class TestTypeForSerializerSettings
{
[DataMember]
public BaseType BaseRef { get; set; }
[DataMember]
public DateTime Date { get; set; }
[DataMember]
public Dictionary<string, object> Dict { get; set; }
}
[DataContract(Name = "BaseType", Namespace = "NS")]
[KnownType(typeof(DerivedType))]
public class BaseType
{
}
[DataContract(Name = "DerivedType", Namespace = "NS")]
public class DerivedType : BaseType
{
}
#endif
}
}

Просмотреть файл

@ -1,606 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization.Json;
using Xunit;
namespace System.Json
{
public class JsonArrayTest
{
[Fact]
public void JsonArrayConstructorParamsTest()
{
JsonArray target;
target = new JsonArray();
Assert.Equal(0, target.Count);
target = new JsonArray(null);
Assert.Equal(0, target.Count);
List<JsonValue> items = new List<JsonValue> { AnyInstance.AnyJsonValue1, AnyInstance.AnyJsonValue2 };
target = new JsonArray(items.ToArray());
ValidateJsonArrayItems(target, items);
target = new JsonArray(items[0], items[1]);
ValidateJsonArrayItems(target, items);
// Invalide tests
items.Add(AnyInstance.DefaultJsonValue);
ExceptionHelper.Throws<ArgumentException>(() => new JsonArray(items.ToArray()));
ExceptionHelper.Throws<ArgumentException>(() => new JsonArray(items[0], items[1], items[2]));
}
[Fact]
public void JsonArrayConstructorEnumTest()
{
List<JsonValue> items = new List<JsonValue> { AnyInstance.AnyJsonValue1, AnyInstance.AnyJsonValue2, AnyInstance.AnyJsonValue3 };
JsonArray target;
target = new JsonArray(items);
ValidateJsonArrayItems(target, items);
ExceptionHelper.Throws<ArgumentNullException>(() => new JsonArray((IEnumerable<JsonValue>)null));
items.Add(AnyInstance.DefaultJsonValue);
ExceptionHelper.Throws<ArgumentException>(() => new JsonArray(items));
}
[Fact]
public void AddTest()
{
JsonArray target = new JsonArray();
JsonValue item = AnyInstance.AnyJsonValue1;
Assert.False(target.Contains(item));
target.Add(item);
Assert.Equal(1, target.Count);
Assert.Equal(item, target[0]);
Assert.True(target.Contains(item));
ExceptionHelper.Throws<ArgumentException>(() => target.Add(AnyInstance.DefaultJsonValue));
}
[Fact]
public void AddRangeEnumTest()
{
List<JsonValue> items = new List<JsonValue> { AnyInstance.AnyJsonValue1, AnyInstance.AnyJsonValue2 };
JsonArray target = new JsonArray();
target.AddRange(items);
ValidateJsonArrayItems(target, items);
ExceptionHelper.Throws<ArgumentNullException>(() => new JsonArray().AddRange((IEnumerable<JsonValue>)null));
items.Add(AnyInstance.DefaultJsonValue);
ExceptionHelper.Throws<ArgumentException>(() => new JsonArray().AddRange(items));
}
[Fact]
public void AddRangeParamsTest()
{
List<JsonValue> items = new List<JsonValue> { AnyInstance.AnyJsonValue1, AnyInstance.AnyJsonValue2, AnyInstance.AnyJsonValue3 };
JsonArray target;
target = new JsonArray();
target.AddRange(items[0], items[1], items[2]);
ValidateJsonArrayItems(target, items);
target = new JsonArray();
target.AddRange(items.ToArray());
ValidateJsonArrayItems(target, items);
target.AddRange();
ValidateJsonArrayItems(target, items);
items.Add(AnyInstance.DefaultJsonValue);
ExceptionHelper.Throws<ArgumentException>(() => new JsonArray().AddRange(items[items.Count - 1]));
ExceptionHelper.Throws<ArgumentException>(() => new JsonArray().AddRange(items));
}
[Fact]
public void ClearTest()
{
JsonArray target = new JsonArray(AnyInstance.AnyJsonValue1, AnyInstance.AnyJsonValue2);
Assert.Equal(2, target.Count);
target.Clear();
Assert.Equal(0, target.Count);
}
[Fact]
public void ContainsTest()
{
JsonValue item1 = AnyInstance.AnyJsonValue1;
JsonValue item2 = AnyInstance.AnyJsonValue2;
JsonArray target = new JsonArray(item1);
Assert.True(target.Contains(item1));
Assert.False(target.Contains(item2));
target.Add(item2);
Assert.True(target.Contains(item1));
Assert.True(target.Contains(item2));
target.Remove(item1);
Assert.False(target.Contains(item1));
Assert.True(target.Contains(item2));
}
[Fact]
public void ReadAsComplexTypeTest()
{
JsonArray target = new JsonArray(AnyInstance.AnyInt, AnyInstance.AnyInt + 1, AnyInstance.AnyInt + 2);
int[] intArray1 = (int[])target.ReadAsType(typeof(int[]));
int[] intArray2 = target.ReadAsType<int[]>();
Assert.Equal(((JsonArray)target).Count, intArray1.Length);
Assert.Equal(((JsonArray)target).Count, intArray2.Length);
for (int i = 0; i < intArray1.Length; i++)
{
Assert.Equal(AnyInstance.AnyInt + i, intArray1[i]);
Assert.Equal(AnyInstance.AnyInt + i, intArray2[i]);
}
}
[Fact]
public void CopyToTest()
{
JsonValue item1 = AnyInstance.AnyJsonValue1;
JsonValue item2 = AnyInstance.AnyJsonValue2;
JsonArray target = new JsonArray(item1, item2);
JsonValue[] array = new JsonValue[target.Count + 1];
target.CopyTo(array, 0);
Assert.Equal(item1, array[0]);
Assert.Equal(item2, array[1]);
target.CopyTo(array, 1);
Assert.Equal(item1, array[1]);
Assert.Equal(item2, array[2]);
ExceptionHelper.Throws<ArgumentNullException>(() => target.CopyTo(null, 0));
ExceptionHelper.Throws<ArgumentOutOfRangeException>(() => target.CopyTo(array, -1));
ExceptionHelper.Throws<ArgumentException>(() => target.CopyTo(array, array.Length - target.Count + 1));
}
[Fact]
public void IndexOfTest()
{
JsonValue item1 = AnyInstance.AnyJsonValue1;
JsonValue item2 = AnyInstance.AnyJsonValue2;
JsonValue item3 = AnyInstance.AnyJsonValue3;
JsonArray target = new JsonArray(item1, item2);
Assert.Equal(0, target.IndexOf(item1));
Assert.Equal(1, target.IndexOf(item2));
Assert.Equal(-1, target.IndexOf(item3));
}
[Fact]
public void InsertTest()
{
JsonValue item1 = AnyInstance.AnyJsonValue1;
JsonValue item2 = AnyInstance.AnyJsonValue2;
JsonValue item3 = AnyInstance.AnyJsonValue3;
JsonArray target = new JsonArray(item1);
Assert.Equal(1, target.Count);
target.Insert(0, item2);
Assert.Equal(2, target.Count);
Assert.Equal(item2, target[0]);
Assert.Equal(item1, target[1]);
target.Insert(1, item3);
Assert.Equal(3, target.Count);
Assert.Equal(item2, target[0]);
Assert.Equal(item3, target[1]);
Assert.Equal(item1, target[2]);
target.Insert(target.Count, item2);
Assert.Equal(4, target.Count);
Assert.Equal(item2, target[0]);
Assert.Equal(item3, target[1]);
Assert.Equal(item1, target[2]);
Assert.Equal(item2, target[3]);
ExceptionHelper.Throws<ArgumentOutOfRangeException>(() => target.Insert(-1, item3));
ExceptionHelper.Throws<ArgumentOutOfRangeException>(() => target.Insert(target.Count + 1, item1));
ExceptionHelper.Throws<ArgumentException>(() => target.Insert(0, AnyInstance.DefaultJsonValue));
}
[Fact]
public void RemoveTest()
{
JsonValue item1 = AnyInstance.AnyJsonValue1;
JsonValue item2 = AnyInstance.AnyJsonValue2;
JsonValue item3 = AnyInstance.AnyJsonValue3;
JsonArray target = new JsonArray(item1, item2, item3);
Assert.True(target.Remove(item2));
Assert.Equal(2, target.Count);
Assert.Equal(item1, target[0]);
Assert.Equal(item3, target[1]);
Assert.False(target.Remove(item2));
Assert.Equal(2, target.Count);
}
[Fact]
public void RemoveAtTest()
{
JsonValue item1 = AnyInstance.AnyJsonValue1;
JsonValue item2 = AnyInstance.AnyJsonValue2;
JsonValue item3 = AnyInstance.AnyJsonValue3;
JsonArray target = new JsonArray(item1, item2, item3);
target.RemoveAt(1);
Assert.Equal(2, target.Count);
Assert.Equal(item1, target[0]);
Assert.Equal(item3, target[1]);
ExceptionHelper.Throws<ArgumentOutOfRangeException>(() => target.RemoveAt(-1));
ExceptionHelper.Throws<ArgumentOutOfRangeException>(() => target.RemoveAt(target.Count));
}
[Fact]
public void ToStringTest()
{
JsonArray target;
JsonValue item1 = AnyInstance.AnyJsonValue1;
JsonValue item2 = null;
JsonValue item3 = AnyInstance.AnyJsonValue2;
target = new JsonArray(item1, item2, item3);
string expected = String.Format(CultureInfo.InvariantCulture, "[{0},null,{1}]", item1.ToString(), item3.ToString());
Assert.Equal(expected, target.ToString());
string json = "[\r\n \"hello\",\r\n null,\r\n [\r\n 1,\r\n 2,\r\n 3\r\n ]\r\n]";
target = JsonValue.Parse(json) as JsonArray;
Assert.Equal<string>(json.Replace("\r\n", "").Replace(" ", ""), target.ToString());
}
[Fact]
public void GetEnumeratorTest()
{
JsonValue item1 = AnyInstance.AnyJsonValue1;
JsonValue item2 = AnyInstance.AnyJsonValue2;
IEnumerable<JsonValue> target = new JsonArray(item1, item2);
IEnumerator<JsonValue> enumerator = target.GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.Equal(item1, enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(item2, enumerator.Current);
Assert.False(enumerator.MoveNext());
}
[Fact]
public void GetEnumeratorTest1()
{
JsonValue item1 = AnyInstance.AnyJsonValue1;
JsonValue item2 = AnyInstance.AnyJsonValue2;
IEnumerable target = new JsonArray(item1, item2);
IEnumerator enumerator = target.GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.Equal(item1, enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(item2, enumerator.Current);
Assert.False(enumerator.MoveNext());
}
[Fact]
public void CountTest()
{
JsonValue item1 = AnyInstance.AnyJsonValue1;
JsonValue item2 = AnyInstance.AnyJsonValue2;
JsonArray target = new JsonArray();
Assert.Equal(0, target.Count);
target.Add(item1);
Assert.Equal(1, target.Count);
target.Add(item2);
Assert.Equal(2, target.Count);
target.Remove(item1);
Assert.Equal(1, target.Count);
}
[Fact]
public void IsReadOnlyTest()
{
JsonArray target = AnyInstance.AnyJsonArray;
Assert.False(target.IsReadOnly);
}
[Fact]
public void ItemTest()
{
JsonValue item1 = AnyInstance.AnyJsonValue1;
JsonValue item2 = AnyInstance.AnyJsonValue2;
JsonArray target = new JsonArray(item1);
Assert.Equal(item1, target[0]);
target[0] = item2;
Assert.Equal(item2, target[0]);
Assert.Equal(item2, target[(short)0]);
Assert.Equal(item2, target[(ushort)0]);
Assert.Equal(item2, target[(byte)0]);
Assert.Equal(item2, target[(sbyte)0]);
Assert.Equal(item2, target[(char)0]);
ExceptionHelper.Throws<ArgumentOutOfRangeException>(delegate { var i = target[-1]; });
ExceptionHelper.Throws<ArgumentOutOfRangeException>(delegate { var i = target[target.Count]; });
ExceptionHelper.Throws<ArgumentOutOfRangeException>(delegate { target[-1] = AnyInstance.AnyJsonValue1; });
ExceptionHelper.Throws<ArgumentOutOfRangeException>(delegate { target[target.Count] = AnyInstance.AnyJsonValue2; });
ExceptionHelper.Throws<ArgumentException>(delegate { target[0] = AnyInstance.DefaultJsonValue; });
}
[Fact]
public void ChangingEventsTest()
{
JsonArray ja = new JsonArray(AnyInstance.AnyInt, AnyInstance.AnyBool, null);
TestEvents(
ja,
arr => arr.Add(1),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(1, JsonValueChange.Add, 3)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(1, JsonValueChange.Add, 3)),
});
TestEvents(
ja,
arr => arr.AddRange(AnyInstance.AnyString, AnyInstance.AnyDouble),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(AnyInstance.AnyString, JsonValueChange.Add, 4)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(AnyInstance.AnyDouble, JsonValueChange.Add, 5)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(AnyInstance.AnyString, JsonValueChange.Add, 4)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(AnyInstance.AnyDouble, JsonValueChange.Add, 5)),
});
TestEvents(
ja,
arr => arr[1] = 2,
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(2, JsonValueChange.Replace, 1)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(AnyInstance.AnyBool, JsonValueChange.Replace, 1)),
});
ja = new JsonArray { 1, 2, 3 };
TestEvents(
ja,
arr => arr.Insert(1, "new value"),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs("new value", JsonValueChange.Add, 1)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs("new value", JsonValueChange.Add, 1)),
});
TestEvents(
ja,
arr => arr.RemoveAt(1),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs("new value", JsonValueChange.Remove, 1)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs("new value", JsonValueChange.Remove, 1)),
});
TestEvents(
ja,
arr => arr.Clear(),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(null, JsonValueChange.Clear, 0)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(null, JsonValueChange.Clear, 0)),
});
ja = new JsonArray(1, 2, 3);
TestEvents(
ja,
arr => arr.Remove(new JsonPrimitive("Not there")),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>());
JsonValue elementInArray = ja[1];
TestEvents(
ja,
arr => arr.Remove(elementInArray),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, ja, new JsonValueChangeEventArgs(elementInArray, JsonValueChange.Remove, 1)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, ja, new JsonValueChangeEventArgs(elementInArray, JsonValueChange.Remove, 1)),
});
}
[Fact]
public void NestedChangingEventTest()
{
JsonArray target = new JsonArray { new JsonArray { 1, 2 }, new JsonArray { 3, 4 } };
JsonArray child = target[1] as JsonArray;
TestEvents(
target,
arr => ((JsonArray)arr[1]).Add(5),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>());
target = new JsonArray();
child = new JsonArray(1, 2);
TestEvents(
target,
arr =>
{
arr.Add(child);
((JsonArray)arr[0]).Add(5);
},
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, target, new JsonValueChangeEventArgs(child, JsonValueChange.Add, 0)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, target, new JsonValueChangeEventArgs(child, JsonValueChange.Add, 0)),
});
}
[Fact]
public void MultipleListenersTest()
{
for (int changingListeners = 0; changingListeners <= 2; changingListeners++)
{
for (int changedListeners = 0; changedListeners <= 2; changedListeners++)
{
MultipleListenersTestHelper<JsonArray>(
() => new JsonArray(1, 2),
delegate(JsonArray arr)
{
arr[1] = "hello";
arr.RemoveAt(0);
arr.Add("world");
arr.Clear();
},
new List<JsonValueChangeEventArgs>
{
new JsonValueChangeEventArgs("hello", JsonValueChange.Replace, 1),
new JsonValueChangeEventArgs(1, JsonValueChange.Remove, 0),
new JsonValueChangeEventArgs("world", JsonValueChange.Add, 1),
new JsonValueChangeEventArgs(null, JsonValueChange.Clear, 0),
},
new List<JsonValueChangeEventArgs>
{
new JsonValueChangeEventArgs(2, JsonValueChange.Replace, 1),
new JsonValueChangeEventArgs(1, JsonValueChange.Remove, 0),
new JsonValueChangeEventArgs("world", JsonValueChange.Add, 1),
new JsonValueChangeEventArgs(null, JsonValueChange.Clear, 0),
},
changingListeners,
changedListeners);
}
}
}
[Fact]
public void JsonTypeTest()
{
JsonArray target = AnyInstance.AnyJsonArray;
Assert.Equal(JsonType.Array, target.JsonType);
}
internal static void TestEvents<JsonValueType>(JsonValueType target, Action<JsonValueType> actionToTriggerEvent, List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>> expectedEvents) where JsonValueType : JsonValue
{
List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>> actualEvents = new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>();
EventHandler<JsonValueChangeEventArgs> changingHandler = delegate(object sender, JsonValueChangeEventArgs e)
{
actualEvents.Add(new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, sender as JsonValue, e));
};
EventHandler<JsonValueChangeEventArgs> changedHandler = delegate(object sender, JsonValueChangeEventArgs e)
{
actualEvents.Add(new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, sender as JsonValue, e));
};
target.Changing += new EventHandler<JsonValueChangeEventArgs>(changingHandler);
target.Changed += new EventHandler<JsonValueChangeEventArgs>(changedHandler);
actionToTriggerEvent(target);
target.Changing -= new EventHandler<JsonValueChangeEventArgs>(changingHandler);
target.Changed -= new EventHandler<JsonValueChangeEventArgs>(changedHandler);
ValidateExpectedEvents(expectedEvents, actualEvents);
}
private static void TestEvents(JsonArray array, Action<JsonArray> actionToTriggerEvent, List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>> expectedEvents)
{
TestEvents<JsonArray>(array, actionToTriggerEvent, expectedEvents);
}
private static void ValidateExpectedEvents(List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>> expectedEvents, List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>> actualEvents)
{
Assert.Equal(expectedEvents.Count, actualEvents.Count);
for (int i = 0; i < expectedEvents.Count; i++)
{
bool expectedIsChanging = expectedEvents[i].Item1;
bool actualIsChanging = expectedEvents[i].Item1;
Assert.Equal(expectedIsChanging, actualIsChanging);
JsonValue expectedSender = expectedEvents[i].Item2;
JsonValue actualSender = actualEvents[i].Item2;
Assert.Same(expectedSender, actualSender);
JsonValueChangeEventArgs expectedEventArgs = expectedEvents[i].Item3;
JsonValueChangeEventArgs actualEventArgs = actualEvents[i].Item3;
Assert.Equal(expectedEventArgs.Change, actualEventArgs.Change);
Assert.Equal(expectedEventArgs.Index, actualEventArgs.Index);
Assert.Equal(expectedEventArgs.Key, actualEventArgs.Key);
string expectedChild = expectedEventArgs.Child == null ? "null" : expectedEventArgs.Child.ToString();
string actualChild = actualEventArgs.Child == null ? "null" : actualEventArgs.Child.ToString();
Assert.Equal(expectedChild, actualChild);
}
}
internal static void MultipleListenersTestHelper<JsonValueType>(
Func<JsonValueType> createTarget,
Action<JsonValueType> actionToTriggerEvents,
List<JsonValueChangeEventArgs> expectedChangingEventArgs,
List<JsonValueChangeEventArgs> expectedChangedEventArgs,
int changingListeners,
int changedListeners) where JsonValueType : JsonValue
{
Console.WriteLine("Testing events on a {0} for {1} changING listeners and {2} changED listeners", typeof(JsonValueType).Name, changingListeners, changedListeners);
JsonValueType target = createTarget();
List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>[] actualChangingEvents = new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>[changingListeners];
List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>[] actualChangedEvents = new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>[changedListeners];
List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>> expectedChangingEvents = new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>(
expectedChangingEventArgs.Select((args) => new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, target, args)));
List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>> expectedChangedEvents = new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>(
expectedChangedEventArgs.Select((args) => new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, target, args)));
for (int i = 0; i < changingListeners; i++)
{
actualChangingEvents[i] = new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>();
int index = i;
target.Changing += delegate(object sender, JsonValueChangeEventArgs e)
{
actualChangingEvents[index].Add(new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, sender as JsonValue, e));
};
}
for (int i = 0; i < changedListeners; i++)
{
actualChangedEvents[i] = new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>();
int index = i;
target.Changed += delegate(object sender, JsonValueChangeEventArgs e)
{
actualChangedEvents[index].Add(new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, sender as JsonValue, e));
};
}
actionToTriggerEvents(target);
for (int i = 0; i < changingListeners; i++)
{
Console.WriteLine("Validating Changing events for listener {0}", i);
ValidateExpectedEvents(expectedChangingEvents, actualChangingEvents[i]);
}
for (int i = 0; i < changedListeners; i++)
{
Console.WriteLine("Validating Changed events for listener {0}", i);
ValidateExpectedEvents(expectedChangedEvents, actualChangedEvents[i]);
}
}
private static void ValidateJsonArrayItems(JsonArray jsonArray, IEnumerable<JsonValue> expectedItems)
{
List<JsonValue> expected = new List<JsonValue>(expectedItems);
Assert.Equal(expected.Count, jsonArray.Count);
for (int i = 0; i < expected.Count; i++)
{
Assert.Equal(expected[i], jsonArray[i]);
}
}
}
}

Просмотреть файл

@ -1,155 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.IO;
using System.Runtime.Serialization.Json;
using Xunit;
namespace System.Json
{
public class JsonDefaultTest
{
const string IndexerNotSupportedMsgFormat = "'{0}' type indexer is not supported on JsonValue of 'JsonType.Default' type.";
const string OperationNotAllowedOnDefaultMsgFormat = "Operation not supported on JsonValue instances of 'JsonType.Default' type.";
[Fact]
public void PropertiesTest()
{
JsonValue target = AnyInstance.DefaultJsonValue;
Assert.Equal(JsonType.Default, target.JsonType);
Assert.Equal(0, target.Count);
Assert.Equal(false, target.ContainsKey("hello"));
Assert.Equal(false, target.ContainsKey(String.Empty));
}
[Fact]
public void SaveTest()
{
JsonValue target = AnyInstance.DefaultJsonValue;
using (MemoryStream ms = new MemoryStream())
{
ExceptionHelper.Throws<InvalidOperationException>(() => target.Save(ms), "Operation not supported on JsonValue instances of 'JsonType.Default' type.");
}
}
[Fact]
public void ToStringTest()
{
JsonValue target;
target = AnyInstance.DefaultJsonValue;
Assert.Equal(target.ToString(), "Default");
}
[Fact(Skip = "See bug #228569 in CSDMain")]
public void ReadAsTests()
{
JsonValue target = AnyInstance.DefaultJsonValue;
string typeName = target.GetType().FullName;
string errorMsgFormat = "Cannot read '{0}' as '{1}' type.";
ExceptionHelper.Throws<NotSupportedException>(delegate { target.ReadAs(typeof(bool)); }, String.Format(errorMsgFormat, typeName, typeof(bool)));
ExceptionHelper.Throws<NotSupportedException>(delegate { target.ReadAs(typeof(string)); }, String.Format(errorMsgFormat, typeName, typeof(string)));
ExceptionHelper.Throws<NotSupportedException>(delegate { target.ReadAs(typeof(JsonObject)); }, String.Format(errorMsgFormat, typeName, typeof(JsonObject)));
ExceptionHelper.Throws<NotSupportedException>(delegate { target.ReadAs<bool>(); }, String.Format(errorMsgFormat, typeName, typeof(bool)));
ExceptionHelper.Throws<NotSupportedException>(delegate { target.ReadAs<string>(); }, String.Format(errorMsgFormat, typeName, typeof(string)));
ExceptionHelper.Throws<NotSupportedException>(delegate { target.ReadAs<JsonObject>(); }, String.Format(errorMsgFormat, typeName, typeof(JsonObject)));
bool boolValue;
string stringValue;
JsonObject objValue;
object value;
Assert.False(target.TryReadAs(typeof(bool), out value), "TryReadAs expected to return false");
Assert.Null(value);
Assert.False(target.TryReadAs(typeof(string), out value), "TryReadAs expected to return false");
Assert.Null(value);
Assert.False(target.TryReadAs(typeof(JsonObject), out value), "TryReadAs expected to return false");
Assert.Null(value);
Assert.False(target.TryReadAs<bool>(out boolValue), "TryReadAs expected to return false");
Assert.False(boolValue);
Assert.False(target.TryReadAs<string>(out stringValue), "TryReadAs expected to return false");
Assert.Null(stringValue);
Assert.False(target.TryReadAs<JsonObject>(out objValue), "TryReadAs expected to return false");
Assert.Null(objValue);
}
[Fact]
public void ItemTests()
{
JsonValue target = AnyInstance.DefaultJsonValue;
ExceptionHelper.Throws<InvalidOperationException>(delegate { var v = target["MissingProperty"]; }, String.Format(IndexerNotSupportedMsgFormat, typeof(string).FullName));
ExceptionHelper.Throws<InvalidOperationException>(delegate { target["NewProperty"] = AnyInstance.AnyJsonValue1; }, String.Format(IndexerNotSupportedMsgFormat, typeof(string).FullName));
}
[Fact]
public void DynamicItemTests()
{
dynamic target = AnyInstance.DefaultJsonValue;
var getByKey = target["SomeKey"];
Assert.Same(getByKey, AnyInstance.DefaultJsonValue);
var getByIndex = target[10];
Assert.Same(getByIndex, AnyInstance.DefaultJsonValue);
ExceptionHelper.Throws<InvalidOperationException>(delegate { target["SomeKey"] = AnyInstance.AnyJsonObject; }, String.Format(IndexerNotSupportedMsgFormat, typeof(string).FullName));
ExceptionHelper.Throws<InvalidOperationException>(delegate { target[10] = AnyInstance.AnyJsonObject; }, String.Format(IndexerNotSupportedMsgFormat, typeof(int).FullName));
}
[Fact(Skip = "See bug #228569 in CSDMain")]
public void InvalidAssignmentValueTest()
{
JsonValue target;
JsonValue value = AnyInstance.DefaultJsonValue;
target = AnyInstance.AnyJsonArray;
ExceptionHelper.Throws<ArgumentException>(delegate { target[0] = value; }, OperationNotAllowedOnDefaultMsgFormat);
target = AnyInstance.AnyJsonObject;
ExceptionHelper.Throws<ArgumentException>(delegate { target["key"] = value; }, OperationNotAllowedOnDefaultMsgFormat);
}
[Fact]
public void DefaultConcatTest()
{
JsonValue jv = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);
dynamic target = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);
Person person = AnyInstance.AnyPerson;
Assert.Equal(JsonType.Default, target.Friends[100000].Name.JsonType);
Assert.Equal(JsonType.Default, target.Friends[0].Age.Minutes.JsonType);
JsonValue jv1 = target.MissingProperty as JsonValue;
Assert.NotNull(jv1);
JsonValue jv2 = target.MissingProperty1.MissingProperty2 as JsonValue;
Assert.NotNull(jv2);
Assert.Same(jv1, jv2);
Assert.Same(target.Person.Name.MissingProperty, AnyInstance.DefaultJsonValue);
}
[Fact]
public void CastingDefaultValueTest()
{
JsonValue jv = AnyInstance.DefaultJsonValue;
dynamic d = jv;
ExceptionHelper.Throws<InvalidCastException>(delegate { float p = (float)d; });
ExceptionHelper.Throws<InvalidCastException>(delegate { byte p = (byte)d; });
ExceptionHelper.Throws<InvalidCastException>(delegate { int p = (int)d; });
Assert.Null((string)d);
}
}
}

Просмотреть файл

@ -1,789 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Serialization.Json;
using Xunit;
namespace System.Json
{
public class JsonObjectTest
{
[Fact]
public void JsonObjectConstructorEnumTest()
{
string key1 = AnyInstance.AnyString;
string key2 = AnyInstance.AnyString2;
JsonValue value1 = AnyInstance.AnyJsonValue1;
JsonValue value2 = AnyInstance.AnyJsonValue2;
List<KeyValuePair<string, JsonValue>> items = new List<KeyValuePair<string, JsonValue>>()
{
new KeyValuePair<string, JsonValue>(key1, value1),
new KeyValuePair<string, JsonValue>(key2, value2),
};
JsonObject target = new JsonObject(null);
Assert.Equal(0, target.Count);
target = new JsonObject(items);
Assert.Equal(2, target.Count);
ValidateJsonObjectItems(target, key1, value1, key2, value2);
// Invalid tests
items.Add(new KeyValuePair<string, JsonValue>(key1, AnyInstance.DefaultJsonValue));
ExceptionHelper.Throws<ArgumentException>(delegate { new JsonObject(items); });
}
[Fact]
public void JsonObjectConstructorParmsTest()
{
JsonObject target = new JsonObject();
Assert.Equal(0, target.Count);
string key1 = AnyInstance.AnyString;
string key2 = AnyInstance.AnyString2;
JsonValue value1 = AnyInstance.AnyJsonValue1;
JsonValue value2 = AnyInstance.AnyJsonValue2;
List<KeyValuePair<string, JsonValue>> items = new List<KeyValuePair<string, JsonValue>>()
{
new KeyValuePair<string, JsonValue>(key1, value1),
new KeyValuePair<string, JsonValue>(key2, value2),
};
target = new JsonObject(items[0], items[1]);
Assert.Equal(2, target.Count);
ValidateJsonObjectItems(target, key1, value1, key2, value2);
target = new JsonObject(items.ToArray());
Assert.Equal(2, target.Count);
ValidateJsonObjectItems(target, key1, value1, key2, value2);
// Invalid tests
items.Add(new KeyValuePair<string, JsonValue>(key1, AnyInstance.DefaultJsonValue));
ExceptionHelper.Throws<ArgumentException>(delegate { new JsonObject(items[0], items[1], items[2]); });
ExceptionHelper.Throws<ArgumentException>(delegate { new JsonObject(items.ToArray()); });
}
[Fact]
public void AddTest()
{
string key1 = AnyInstance.AnyString;
string key2 = AnyInstance.AnyString2;
JsonValue value1 = AnyInstance.AnyJsonValue1;
JsonValue value2 = AnyInstance.AnyJsonValue2;
JsonObject target;
target = new JsonObject();
target.Add(new KeyValuePair<string, JsonValue>(key1, value1));
Assert.Equal(1, target.Count);
Assert.True(target.ContainsKey(key1));
Assert.Equal(value1, target[key1]);
target.Add(key2, value2);
Assert.Equal(2, target.Count);
Assert.True(target.ContainsKey(key2));
Assert.Equal(value2, target[key2]);
ExceptionHelper.Throws<ArgumentNullException>(delegate { new JsonObject().Add(null, value1); });
ExceptionHelper.Throws<ArgumentNullException>(delegate { new JsonObject().Add(new KeyValuePair<string, JsonValue>(null, value1)); });
ExceptionHelper.Throws<ArgumentException>(delegate { new JsonObject().Add(key1, AnyInstance.DefaultJsonValue); });
ExceptionHelper.Throws<ArgumentException>(delegate { new JsonArray().Add(AnyInstance.DefaultJsonValue); });
}
[Fact]
public void AddRangeParamsTest()
{
string key1 = AnyInstance.AnyString;
string key2 = AnyInstance.AnyString2;
JsonValue value1 = AnyInstance.AnyJsonValue1;
JsonValue value2 = AnyInstance.AnyJsonValue2;
List<KeyValuePair<string, JsonValue>> items = new List<KeyValuePair<string, JsonValue>>()
{
new KeyValuePair<string, JsonValue>(key1, value1),
new KeyValuePair<string, JsonValue>(key2, value2),
};
JsonObject target;
target = new JsonObject();
target.AddRange(items[0], items[1]);
Assert.Equal(2, target.Count);
ValidateJsonObjectItems(target, key1, value1, key2, value2);
target = new JsonObject();
target.AddRange(items.ToArray());
Assert.Equal(2, target.Count);
ValidateJsonObjectItems(target, key1, value1, key2, value2);
ExceptionHelper.Throws<ArgumentNullException>(delegate { new JsonObject().AddRange((KeyValuePair<string, JsonValue>[])null); });
ExceptionHelper.Throws<ArgumentNullException>(delegate { new JsonObject().AddRange((IEnumerable<KeyValuePair<string, JsonValue>>)null); });
items[1] = new KeyValuePair<string, JsonValue>(key2, AnyInstance.DefaultJsonValue);
ExceptionHelper.Throws<ArgumentException>(delegate { new JsonObject().AddRange(items.ToArray()); });
ExceptionHelper.Throws<ArgumentException>(delegate { new JsonObject().AddRange(items[0], items[1]); });
}
[Fact]
public void AddRangeEnumTest()
{
string key1 = AnyInstance.AnyString;
string key2 = AnyInstance.AnyString2;
JsonValue value1 = AnyInstance.AnyJsonValue1;
JsonValue value2 = AnyInstance.AnyJsonValue2;
List<KeyValuePair<string, JsonValue>> items = new List<KeyValuePair<string, JsonValue>>()
{
new KeyValuePair<string, JsonValue>(key1, value1),
new KeyValuePair<string, JsonValue>(key2, value2),
};
JsonObject target;
target = new JsonObject();
target.AddRange(items);
Assert.Equal(2, target.Count);
ValidateJsonObjectItems(target, key1, value1, key2, value2);
ExceptionHelper.Throws<ArgumentNullException>(delegate { new JsonObject().AddRange(null); });
items[1] = new KeyValuePair<string, JsonValue>(key2, AnyInstance.DefaultJsonValue);
ExceptionHelper.Throws<ArgumentException>(delegate { new JsonObject().AddRange(items); });
}
[Fact]
public void ClearTest()
{
string key1 = AnyInstance.AnyString;
string key2 = AnyInstance.AnyString2;
JsonValue value1 = AnyInstance.AnyJsonValue1;
JsonValue value2 = AnyInstance.AnyJsonValue2;
JsonObject target = new JsonObject();
target.Add(key1, value1);
target.Clear();
Assert.Equal(0, target.Count);
Assert.False(target.ContainsKey(key1));
target.Add(key2, value2);
Assert.Equal(1, target.Count);
Assert.False(target.ContainsKey(key1));
Assert.True(target.ContainsKey(key2));
}
[Fact]
public void ContainsKeyTest()
{
string key1 = AnyInstance.AnyString;
JsonValue value1 = AnyInstance.AnyJsonValue1;
JsonObject target = new JsonObject();
Assert.False(target.ContainsKey(key1));
target.Add(key1, value1);
Assert.True(target.ContainsKey(key1));
target.Clear();
Assert.False(target.ContainsKey(key1));
ExceptionHelper.Throws<ArgumentNullException>(delegate { new JsonObject().ContainsKey(null); });
}
[Fact]
public void CopyToTest()
{
string key1 = AnyInstance.AnyString;
string key2 = AnyInstance.AnyString2;
JsonValue value1 = AnyInstance.AnyJsonValue1;
JsonValue value2 = AnyInstance.AnyJsonValue2;
JsonObject target = new JsonObject { { key1, value1 }, { key2, value2 } };
KeyValuePair<string, JsonValue>[] array = new KeyValuePair<string, JsonValue>[target.Count + 1];
target.CopyTo(array, 1);
int index1 = key1 == array[1].Key ? 1 : 2;
int index2 = index1 == 1 ? 2 : 1;
Assert.Equal(key1, array[index1].Key);
Assert.Equal(value1, array[index1].Value);
Assert.Equal(key2, array[index2].Key);
Assert.Equal(value2, array[index2].Value);
ExceptionHelper.Throws<ArgumentNullException>(() => target.CopyTo(null, 0));
ExceptionHelper.Throws<ArgumentOutOfRangeException>(() => target.CopyTo(array, -1));
ExceptionHelper.Throws<ArgumentException>(() => target.CopyTo(array, array.Length - target.Count + 1));
}
[Fact]
public void CreateFromComplexTypeTest()
{
Assert.Null(JsonValueExtensions.CreateFrom(null));
Person anyObject = AnyInstance.AnyPerson;
JsonObject jv = JsonValueExtensions.CreateFrom(anyObject) as JsonObject;
Assert.NotNull(jv);
Assert.Equal(4, jv.Count);
foreach (string key in "Name Age Address".Split())
{
Assert.True(jv.ContainsKey(key));
}
Assert.Equal(AnyInstance.AnyString, (string)jv["Name"]);
Assert.Equal(AnyInstance.AnyInt, (int)jv["Age"]);
JsonObject nestedObject = jv["Address"] as JsonObject;
Assert.NotNull(nestedObject);
Assert.Equal(3, nestedObject.Count);
foreach (string key in "Street City State".Split())
{
Assert.True(nestedObject.ContainsKey(key));
}
Assert.Equal(Address.AnyStreet, (string)nestedObject["Street"]);
Assert.Equal(Address.AnyCity, (string)nestedObject["City"]);
Assert.Equal(Address.AnyState, (string)nestedObject["State"]);
}
[Fact]
public void ReadAsComplexTypeTest()
{
JsonObject target = new JsonObject
{
{ "Name", AnyInstance.AnyString },
{ "Age", AnyInstance.AnyInt },
{ "Address", new JsonObject { { "Street", Address.AnyStreet }, { "City", Address.AnyCity }, { "State", Address.AnyState } } },
};
Person person = target.ReadAsType<Person>();
Assert.Equal(AnyInstance.AnyString, person.Name);
Assert.Equal(AnyInstance.AnyInt, person.Age);
Assert.NotNull(person.Address);
Assert.Equal(Address.AnyStreet, person.Address.Street);
Assert.Equal(Address.AnyCity, person.Address.City);
Assert.Equal(Address.AnyState, person.Address.State);
}
[Fact]
public void GetEnumeratorTest()
{
string key1 = AnyInstance.AnyString;
string key2 = AnyInstance.AnyString2;
JsonValue value1 = AnyInstance.AnyJsonValue1;
JsonValue value2 = AnyInstance.AnyJsonValue2;
JsonObject target = new JsonObject { { key1, value1 }, { key2, value2 } };
IEnumerator<KeyValuePair<string, JsonValue>> enumerator = target.GetEnumerator();
Assert.True(enumerator.MoveNext());
bool key1IsFirst = key1 == enumerator.Current.Key;
if (key1IsFirst)
{
Assert.Equal(key1, enumerator.Current.Key);
Assert.Equal(value1, enumerator.Current.Value);
}
else
{
Assert.Equal(key2, enumerator.Current.Key);
Assert.Equal(value2, enumerator.Current.Value);
}
Assert.True(enumerator.MoveNext());
if (key1IsFirst)
{
Assert.Equal(key2, enumerator.Current.Key);
Assert.Equal(value2, enumerator.Current.Value);
}
else
{
Assert.Equal(key1, enumerator.Current.Key);
Assert.Equal(value1, enumerator.Current.Value);
}
Assert.False(enumerator.MoveNext());
}
[Fact]
public void RemoveTest()
{
string key1 = AnyInstance.AnyString;
string key2 = AnyInstance.AnyString2;
JsonValue value1 = AnyInstance.AnyJsonValue1;
JsonValue value2 = AnyInstance.AnyJsonValue2;
JsonObject target = new JsonObject { { key1, value1 }, { key2, value2 } };
Assert.True(target.ContainsKey(key1));
Assert.True(target.ContainsKey(key2));
Assert.Equal(2, target.Count);
Assert.True(target.Remove(key2));
Assert.True(target.ContainsKey(key1));
Assert.False(target.ContainsKey(key2));
Assert.Equal(1, target.Count);
Assert.False(target.Remove(key2));
Assert.True(target.ContainsKey(key1));
Assert.False(target.ContainsKey(key2));
Assert.Equal(1, target.Count);
}
[Fact]
public void ToStringTest()
{
JsonObject target = new JsonObject();
JsonValue item1 = AnyInstance.AnyJsonValue1 ?? "not null";
JsonValue item2 = null;
JsonValue item3 = AnyInstance.AnyJsonValue2 ?? "not null";
JsonValue item4 = AnyInstance.AnyJsonValue3 ?? "not null";
target.Add("item1", item1);
target.Add("item2", item2);
target.Add("item3", item3);
target.Add("", item4);
string expected = String.Format(CultureInfo.InvariantCulture, "{{\"item1\":{0},\"item2\":null,\"item3\":{1},\"\":{2}}}", item1.ToString(), item3.ToString(), item4.ToString());
Assert.Equal<string>(expected, target.ToString());
string json = "{\r\n \"item1\": \"hello\",\r\n \"item2\": null,\r\n \"item3\": [\r\n 1,\r\n 2,\r\n 3\r\n ],\r\n \"\": \"notnull\"\r\n}";
target = JsonValue.Parse(json) as JsonObject;
Assert.Equal<string>(json.Replace("\r\n", "").Replace(" ", ""), target.ToString());
}
[Fact]
public void ContainsKVPTest()
{
JsonObject target = new JsonObject();
KeyValuePair<string, JsonValue> item = new KeyValuePair<string, JsonValue>(AnyInstance.AnyString, AnyInstance.AnyJsonValue1);
KeyValuePair<string, JsonValue> item2 = new KeyValuePair<string, JsonValue>(AnyInstance.AnyString2, AnyInstance.AnyJsonValue2);
target.Add(item);
Assert.True(((ICollection<KeyValuePair<string, JsonValue>>)target).Contains(item));
Assert.False(((ICollection<KeyValuePair<string, JsonValue>>)target).Contains(item2));
}
[Fact]
public void RemoveKVPTest()
{
JsonObject target = new JsonObject();
KeyValuePair<string, JsonValue> item1 = new KeyValuePair<string, JsonValue>(AnyInstance.AnyString, AnyInstance.AnyJsonValue1);
KeyValuePair<string, JsonValue> item2 = new KeyValuePair<string, JsonValue>(AnyInstance.AnyString2, AnyInstance.AnyJsonValue2);
target.AddRange(item1, item2);
Assert.Equal(2, target.Count);
Assert.True(((ICollection<KeyValuePair<string, JsonValue>>)target).Contains(item1));
Assert.True(((ICollection<KeyValuePair<string, JsonValue>>)target).Contains(item2));
Assert.True(((ICollection<KeyValuePair<string, JsonValue>>)target).Remove(item1));
Assert.Equal(1, target.Count);
Assert.False(((ICollection<KeyValuePair<string, JsonValue>>)target).Contains(item1));
Assert.True(((ICollection<KeyValuePair<string, JsonValue>>)target).Contains(item2));
Assert.False(((ICollection<KeyValuePair<string, JsonValue>>)target).Remove(item1));
Assert.Equal(1, target.Count);
Assert.False(((ICollection<KeyValuePair<string, JsonValue>>)target).Contains(item1));
Assert.True(((ICollection<KeyValuePair<string, JsonValue>>)target).Contains(item2));
}
[Fact]
public void GetEnumeratorTest1()
{
string key1 = AnyInstance.AnyString;
string key2 = AnyInstance.AnyString2;
JsonValue value1 = AnyInstance.AnyJsonValue1;
JsonValue value2 = AnyInstance.AnyJsonValue2;
JsonObject target = new JsonObject { { key1, value1 }, { key2, value2 } };
IEnumerator enumerator = ((IEnumerable)target).GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.IsType<KeyValuePair<string, JsonValue>>(enumerator.Current);
KeyValuePair<string, JsonValue> current = (KeyValuePair<string, JsonValue>)enumerator.Current;
bool key1IsFirst = key1 == current.Key;
if (key1IsFirst)
{
Assert.Equal(key1, current.Key);
Assert.Equal(value1, current.Value);
}
else
{
Assert.Equal(key2, current.Key);
Assert.Equal(value2, current.Value);
}
Assert.True(enumerator.MoveNext());
Assert.IsType<KeyValuePair<string, JsonValue>>(enumerator.Current);
current = (KeyValuePair<string, JsonValue>)enumerator.Current;
if (key1IsFirst)
{
Assert.Equal(key2, current.Key);
Assert.Equal(value2, current.Value);
}
else
{
Assert.Equal(key1, current.Key);
Assert.Equal(value1, current.Value);
}
Assert.False(enumerator.MoveNext());
}
[Fact]
public void TryGetValueTest()
{
string key1 = AnyInstance.AnyString;
string key2 = AnyInstance.AnyString2;
JsonValue value1 = AnyInstance.AnyJsonValue1;
JsonValue value2 = AnyInstance.AnyJsonValue2;
JsonObject target = new JsonObject { { key1, value1 }, { key2, value2 } };
JsonValue value;
Assert.True(target.TryGetValue(key2, out value));
Assert.Equal(value2, value);
Assert.False(target.TryGetValue("not a key", out value));
Assert.Null(value);
}
[Fact]
public void GetValueOrDefaultTest()
{
bool boolValue;
JsonValue target;
JsonValue jsonValue;
Person person = AnyInstance.AnyPerson;
JsonObject jo = JsonValueExtensions.CreateFrom(person) as JsonObject;
Assert.Equal<int>(person.Age, jo.ValueOrDefault("Age").ReadAs<int>()); // JsonPrimitive
Assert.Equal<string>(person.Address.ToString(), jo.ValueOrDefault("Address").ReadAsType<Address>().ToString()); // JsonObject
Assert.Equal<int>(person.Friends.Count, jo.ValueOrDefault("Friends").Count); // JsonArray
target = jo.ValueOrDefault("Address").ValueOrDefault("City"); // JsonPrimitive
Assert.NotNull(target);
Assert.Equal<string>(person.Address.City, target.ReadAs<string>());
target = jo.ValueOrDefault("Address", "City"); // JsonPrimitive
Assert.NotNull(target);
Assert.Equal<string>(person.Address.City, target.ReadAs<string>());
target = jo.ValueOrDefault("Address").ValueOrDefault("NonExistentProp").ValueOrDefault("NonExistentProp2"); // JsonObject
Assert.Equal(JsonType.Default, target.JsonType);
Assert.NotNull(target);
Assert.False(target.TryReadAs<bool>(out boolValue));
Assert.True(target.TryReadAs<JsonValue>(out jsonValue));
target = jo.ValueOrDefault("Address", "NonExistentProp", "NonExistentProp2"); // JsonObject
Assert.Equal(JsonType.Default, target.JsonType);
Assert.NotNull(target);
Assert.False(target.TryReadAs<bool>(out boolValue));
Assert.True(target.TryReadAs<JsonValue>(out jsonValue));
Assert.Same(target, jsonValue);
}
[Fact]
public void CountTest()
{
string key1 = AnyInstance.AnyString;
string key2 = AnyInstance.AnyString2;
JsonValue value1 = AnyInstance.AnyJsonValue1;
JsonValue value2 = AnyInstance.AnyJsonValue2;
JsonObject target = new JsonObject();
Assert.Equal(0, target.Count);
target.Add(key1, value1);
Assert.Equal(1, target.Count);
target.Add(key2, value2);
Assert.Equal(2, target.Count);
target.Remove(key2);
Assert.Equal(1, target.Count);
}
[Fact]
public void ItemTest()
{
string key1 = AnyInstance.AnyString;
string key2 = AnyInstance.AnyString2;
JsonValue value1 = AnyInstance.AnyJsonValue1;
JsonValue value2 = AnyInstance.AnyJsonValue2;
JsonValue value3 = AnyInstance.AnyJsonValue3;
JsonObject target;
target = new JsonObject { { key1, value1 }, { key2, value2 } };
Assert.Equal(value1, target[key1]);
Assert.Equal(value2, target[key2]);
target[key1] = value3;
Assert.Equal(value3, target[key1]);
Assert.Equal(value2, target[key2]);
ExceptionHelper.Throws<KeyNotFoundException>(delegate { var o = target["not a key"]; });
ExceptionHelper.Throws<ArgumentNullException>(delegate { var o = target[null]; });
ExceptionHelper.Throws<ArgumentNullException>(delegate { target[null] = 123; });
ExceptionHelper.Throws<ArgumentException>(delegate { target[key1] = AnyInstance.DefaultJsonValue; });
}
[Fact]
public void ChangingEventsTest()
{
const string key1 = "first";
const string key2 = "second";
const string key3 = "third";
const string key4 = "fourth";
const string key5 = "fifth";
JsonObject jo = new JsonObject
{
{ key1, AnyInstance.AnyString },
{ key2, AnyInstance.AnyBool },
{ key3, null },
};
TestEvents(
jo,
obj => obj.Add(key4, 1),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(1, JsonValueChange.Add, key4)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(1, JsonValueChange.Add, key4)),
});
TestEvents(
jo,
obj => obj[key2] = 2,
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(2, JsonValueChange.Replace, key2)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(AnyInstance.AnyBool, JsonValueChange.Replace, key2)),
});
TestEvents(
jo,
obj => obj[key5] = 3,
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(3, JsonValueChange.Add, key5)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(3, JsonValueChange.Add, key5)),
});
jo.Remove(key4);
jo.Remove(key5);
TestEvents(
jo,
obj => obj.AddRange(new JsonObject { { key4, AnyInstance.AnyString }, { key5, AnyInstance.AnyDouble } }),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(AnyInstance.AnyString, JsonValueChange.Add, key4)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(AnyInstance.AnyDouble, JsonValueChange.Add, key5)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(AnyInstance.AnyString, JsonValueChange.Add, key4)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(AnyInstance.AnyDouble, JsonValueChange.Add, key5)),
});
TestEvents(
jo,
obj => obj.Remove(key5),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(AnyInstance.AnyDouble, JsonValueChange.Remove, key5)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(AnyInstance.AnyDouble, JsonValueChange.Remove, key5)),
});
TestEvents(
jo,
obj => obj.Remove("not there"),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>());
jo = new JsonObject { { key1, 1 }, { key2, 2 }, { key3, 3 } };
TestEvents(
jo,
obj => obj.Clear(),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(null, JsonValueChange.Clear, null)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(null, JsonValueChange.Clear, null)),
});
jo = new JsonObject { { key1, 1 }, { key2, 2 }, { key3, 3 } };
TestEvents(
jo,
obj => ((IDictionary<string, JsonValue>)obj).Remove(new KeyValuePair<string, JsonValue>(key2, jo[key2])),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, jo, new JsonValueChangeEventArgs(2, JsonValueChange.Remove, key2)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, jo, new JsonValueChangeEventArgs(2, JsonValueChange.Remove, key2)),
});
TestEvents(
jo,
obj => ((IDictionary<string, JsonValue>)obj).Remove(new KeyValuePair<string, JsonValue>("key not in object", jo[key1])),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
});
TestEvents(
jo,
obj => ((IDictionary<string, JsonValue>)obj).Remove(new KeyValuePair<string, JsonValue>(key1, "different object")),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
});
ExceptionHelper.Throws<ArgumentNullException>(() => new JsonValueChangeEventArgs(1, JsonValueChange.Add, null));
}
[Fact]
public void NestedChangingEventTest()
{
const string key1 = "first";
JsonObject target = new JsonObject { { key1, new JsonArray { 1, 2 } } };
JsonArray child = target[key1] as JsonArray;
TestEvents(
target,
obj => ((JsonArray)obj[key1]).Add(5),
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>());
target = new JsonObject();
child = new JsonArray(1, 2);
TestEvents(
target,
obj =>
{
obj.Add(key1, child);
((JsonArray)obj[key1]).Add(5);
},
new List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>>
{
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(true, target, new JsonValueChangeEventArgs(child, JsonValueChange.Add, key1)),
new Tuple<bool, JsonValue, JsonValueChangeEventArgs>(false, target, new JsonValueChangeEventArgs(child, JsonValueChange.Add, key1)),
});
}
[Fact]
public void MultipleListenersTest()
{
const string key1 = "first";
const string key2 = "second";
const string key3 = "third";
for (int changingListeners = 0; changingListeners <= 2; changingListeners++)
{
for (int changedListeners = 0; changedListeners <= 2; changedListeners++)
{
JsonArrayTest.MultipleListenersTestHelper<JsonObject>(
() => new JsonObject { { key1, 1 }, { key2, 2 } },
delegate(JsonObject obj)
{
obj[key2] = "hello";
obj.Remove(key1);
obj.Add(key3, "world");
obj.Clear();
},
new List<JsonValueChangeEventArgs>
{
new JsonValueChangeEventArgs("hello", JsonValueChange.Replace, key2),
new JsonValueChangeEventArgs(1, JsonValueChange.Remove, key1),
new JsonValueChangeEventArgs("world", JsonValueChange.Add, key3),
new JsonValueChangeEventArgs(null, JsonValueChange.Clear, null),
},
new List<JsonValueChangeEventArgs>
{
new JsonValueChangeEventArgs(2, JsonValueChange.Replace, key2),
new JsonValueChangeEventArgs(1, JsonValueChange.Remove, key1),
new JsonValueChangeEventArgs("world", JsonValueChange.Add, key3),
new JsonValueChangeEventArgs(null, JsonValueChange.Clear, null),
},
changingListeners,
changedListeners);
}
}
}
[Fact]
public void JsonTypeTest()
{
JsonObject target = AnyInstance.AnyJsonObject;
Assert.Equal(JsonType.Object, target.JsonType);
}
[Fact]
public void KeysTest()
{
string key1 = AnyInstance.AnyString;
string key2 = AnyInstance.AnyString2;
JsonValue value1 = AnyInstance.AnyJsonValue1;
JsonValue value2 = AnyInstance.AnyJsonValue2;
JsonObject target = new JsonObject { { key1, value1 }, { key2, value2 } };
List<string> expected = new List<string> { key1, key2 };
List<string> actual = new List<string>(target.Keys);
Assert.Equal(expected.Count, actual.Count);
expected.Sort();
actual.Sort();
for (int i = 0; i < expected.Count; i++)
{
Assert.Equal(expected[i], actual[i]);
}
}
[Fact]
public void IsReadOnlyTest()
{
JsonObject target = AnyInstance.AnyJsonObject;
Assert.False(((ICollection<KeyValuePair<string, JsonValue>>)target).IsReadOnly);
}
[Fact]
public void ValuesTest()
{
string key1 = AnyInstance.AnyString;
string key2 = AnyInstance.AnyString2;
JsonValue value1 = AnyInstance.AnyJsonValue1;
JsonValue value2 = AnyInstance.AnyJsonValue2;
JsonObject target = new JsonObject { { key1, value1 }, { key2, value2 } };
List<JsonValue> values = new List<JsonValue>(target.Values);
Assert.Equal(2, values.Count);
bool value1IsFirst = value1 == values[0];
Assert.True(value1IsFirst || value1 == values[1]);
Assert.Equal(value2, values[value1IsFirst ? 1 : 0]);
}
private static void ValidateJsonObjectItems(JsonObject jsonObject, params object[] keyValuePairs)
{
Dictionary<string, JsonValue> expected = new Dictionary<string, JsonValue>();
Assert.True((keyValuePairs.Length % 2) == 0, "Test error");
for (int i = 0; i < keyValuePairs.Length; i += 2)
{
Assert.IsType<String>(keyValuePairs[i]);
Assert.IsAssignableFrom<JsonValue>(keyValuePairs[i + 1]);
expected.Add((string)keyValuePairs[i], (JsonValue)keyValuePairs[i + 1]);
}
}
private static void ValidateJsonObjectItems(JsonObject jsonObject, Dictionary<string, JsonValue> expected)
{
Assert.Equal(expected.Count, jsonObject.Count);
foreach (string key in expected.Keys)
{
Assert.True(jsonObject.ContainsKey(key));
Assert.Equal(expected[key], jsonObject[key]);
}
}
private static void TestEvents(JsonObject obj, Action<JsonObject> actionToTriggerEvent, List<Tuple<bool, JsonValue, JsonValueChangeEventArgs>> expectedEvents)
{
JsonArrayTest.TestEvents<JsonObject>(obj, actionToTriggerEvent, expectedEvents);
}
}
}

Просмотреть файл

@ -1,412 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using Xunit;
namespace System.Json
{
public class JsonPrimitiveTest
{
const string DateTimeFormat = "yyyy-MM-ddTHH:mm:ss.fffK";
[Fact]
public void JsonPrimitiveConstructorTest()
{
Assert.Equal(AnyInstance.AnyString, (string)(new JsonPrimitive(AnyInstance.AnyString)));
Assert.Equal(AnyInstance.AnyChar, (char)(new JsonPrimitive(AnyInstance.AnyChar)));
Assert.Equal(AnyInstance.AnyUri, (Uri)(new JsonPrimitive(AnyInstance.AnyUri)));
Assert.Equal(AnyInstance.AnyGuid, (Guid)(new JsonPrimitive(AnyInstance.AnyGuid)));
Assert.Equal(AnyInstance.AnyDateTime, (DateTime)(new JsonPrimitive(AnyInstance.AnyDateTime)));
Assert.Equal(AnyInstance.AnyDateTimeOffset, (DateTimeOffset)(new JsonPrimitive(AnyInstance.AnyDateTimeOffset)));
Assert.Equal(AnyInstance.AnyBool, (bool)(new JsonPrimitive(AnyInstance.AnyBool)));
Assert.Equal(AnyInstance.AnyByte, (byte)(new JsonPrimitive(AnyInstance.AnyByte)));
Assert.Equal(AnyInstance.AnyShort, (short)(new JsonPrimitive(AnyInstance.AnyShort)));
Assert.Equal(AnyInstance.AnyInt, (int)(new JsonPrimitive(AnyInstance.AnyInt)));
Assert.Equal(AnyInstance.AnyLong, (long)(new JsonPrimitive(AnyInstance.AnyLong)));
Assert.Equal(AnyInstance.AnySByte, (sbyte)(new JsonPrimitive(AnyInstance.AnySByte)));
Assert.Equal(AnyInstance.AnyUShort, (ushort)(new JsonPrimitive(AnyInstance.AnyUShort)));
Assert.Equal(AnyInstance.AnyUInt, (uint)(new JsonPrimitive(AnyInstance.AnyUInt)));
Assert.Equal(AnyInstance.AnyULong, (ulong)(new JsonPrimitive(AnyInstance.AnyULong)));
Assert.Equal(AnyInstance.AnyDecimal, (decimal)(new JsonPrimitive(AnyInstance.AnyDecimal)));
Assert.Equal(AnyInstance.AnyFloat, (float)(new JsonPrimitive(AnyInstance.AnyFloat)));
Assert.Equal(AnyInstance.AnyDouble, (double)(new JsonPrimitive(AnyInstance.AnyDouble)));
}
[Fact]
public void ValueTest()
{
object[] values =
{
AnyInstance.AnyInt, AnyInstance.AnyString, AnyInstance.AnyGuid, AnyInstance.AnyDecimal, AnyInstance.AnyBool, AnyInstance.AnyDateTime
};
foreach (object value in values)
{
JsonPrimitive jp;
bool success = JsonPrimitive.TryCreate(value, out jp);
Assert.True(success);
Assert.Equal(value, jp.Value);
}
}
[Fact]
public void TryCreateTest()
{
object[] numberValues =
{
AnyInstance.AnyByte, AnyInstance.AnySByte, AnyInstance.AnyShort, AnyInstance.AnyDecimal,
AnyInstance.AnyDouble, AnyInstance.AnyShort, AnyInstance.AnyInt, AnyInstance.AnyLong,
AnyInstance.AnyUShort, AnyInstance.AnyUInt, AnyInstance.AnyULong, AnyInstance.AnyFloat
};
object[] booleanValues =
{
true, false
};
object[] stringValues =
{
AnyInstance.AnyString, AnyInstance.AnyChar,
AnyInstance.AnyDateTime, AnyInstance.AnyDateTimeOffset,
AnyInstance.AnyGuid, AnyInstance.AnyUri
};
CheckValues(numberValues, JsonType.Number);
CheckValues(booleanValues, JsonType.Boolean);
CheckValues(stringValues, JsonType.String);
}
[Fact]
public void TryCreateInvalidTest()
{
bool success;
JsonPrimitive target;
object[] values =
{
AnyInstance.AnyJsonArray, AnyInstance.AnyJsonObject, AnyInstance.AnyJsonPrimitive,
null, AnyInstance.DefaultJsonValue, AnyInstance.AnyDynamic, AnyInstance.AnyAddress,
AnyInstance.AnyPerson
};
foreach (object value in values)
{
success = JsonPrimitive.TryCreate(value, out target);
Assert.False(success);
Assert.Null(target);
}
}
[Fact]
public void NumberToNumberConversionTest()
{
long longValue;
Assert.Equal((long)AnyInstance.AnyInt, (long)(new JsonPrimitive(AnyInstance.AnyInt)));
Assert.Equal((long)AnyInstance.AnyUInt, (long)(new JsonPrimitive(AnyInstance.AnyUInt)));
Assert.True(new JsonPrimitive(AnyInstance.AnyInt).TryReadAs<long>(out longValue));
Assert.Equal((long)AnyInstance.AnyInt, longValue);
int intValue;
Assert.Equal((int)AnyInstance.AnyShort, (int)(new JsonPrimitive(AnyInstance.AnyShort)));
Assert.Equal((int)AnyInstance.AnyUShort, (int)(new JsonPrimitive(AnyInstance.AnyUShort)));
Assert.True(new JsonPrimitive(AnyInstance.AnyUShort).TryReadAs<int>(out intValue));
Assert.Equal((int)AnyInstance.AnyUShort, intValue);
short shortValue;
Assert.Equal((short)AnyInstance.AnyByte, (short)(new JsonPrimitive(AnyInstance.AnyByte)));
Assert.Equal((short)AnyInstance.AnySByte, (short)(new JsonPrimitive(AnyInstance.AnySByte)));
Assert.True(new JsonPrimitive(AnyInstance.AnyByte).TryReadAs<short>(out shortValue));
Assert.Equal((short)AnyInstance.AnyByte, shortValue);
double dblValue;
Assert.Equal((double)AnyInstance.AnyFloat, (double)(new JsonPrimitive(AnyInstance.AnyFloat)));
Assert.Equal((double)AnyInstance.AnyDecimal, (double)(new JsonPrimitive(AnyInstance.AnyDecimal)));
Assert.True(new JsonPrimitive(AnyInstance.AnyFloat).TryReadAs<double>(out dblValue));
Assert.Equal((double)AnyInstance.AnyFloat, dblValue);
ExceptionHelper.Throws<OverflowException>(delegate { int i = (int)(new JsonPrimitive(1L << 32)); });
Assert.False(new JsonPrimitive(1L << 32).TryReadAs<int>(out intValue));
Assert.Equal(default(int), intValue);
byte byteValue;
ExceptionHelper.Throws<OverflowException>(delegate { byte b = (byte)(new JsonPrimitive(1L << 32)); });
ExceptionHelper.Throws<OverflowException>(delegate { byte b = (byte)(new JsonPrimitive(SByte.MinValue)); });
Assert.False(new JsonPrimitive(SByte.MinValue).TryReadAs<byte>(out byteValue));
Assert.Equal(default(byte), byteValue);
}
[Fact]
public void NumberToStringConverstionTest()
{
Dictionary<string, JsonPrimitive> allNumbers = new Dictionary<string, JsonPrimitive>
{
{ AnyInstance.AnyByte.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyByte) },
{ AnyInstance.AnySByte.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnySByte) },
{ AnyInstance.AnyShort.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyShort) },
{ AnyInstance.AnyUShort.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyUShort) },
{ AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyInt) },
{ AnyInstance.AnyUInt.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyUInt) },
{ AnyInstance.AnyLong.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyLong) },
{ AnyInstance.AnyULong.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyULong) },
{ AnyInstance.AnyDecimal.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyDecimal) },
{ AnyInstance.AnyDouble.ToString("R", CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyDouble) },
{ AnyInstance.AnyFloat.ToString("R", CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyFloat) },
};
foreach (string stringRepresentation in allNumbers.Keys)
{
JsonPrimitive jp = allNumbers[stringRepresentation];
Assert.Equal(stringRepresentation, (string)jp);
Assert.Equal(stringRepresentation, jp.ReadAs<string>());
}
}
[Fact]
public void NonNumberToStringConversionTest()
{
Dictionary<string, JsonPrimitive> allValues = new Dictionary<string, JsonPrimitive>
{
{ new string(AnyInstance.AnyChar, 1), new JsonPrimitive(AnyInstance.AnyChar) },
{ AnyInstance.AnyBool.ToString(CultureInfo.InvariantCulture).ToLowerInvariant(), new JsonPrimitive(AnyInstance.AnyBool) },
{ AnyInstance.AnyGuid.ToString("D", CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyGuid) },
{ AnyInstance.AnyDateTime.ToString(DateTimeFormat, CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyDateTime) },
{ AnyInstance.AnyDateTimeOffset.ToString(DateTimeFormat, CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyDateTimeOffset) },
};
foreach (char escapedChar in "\r\n\t\u0000\uffff\u001f\\\"")
{
allValues.Add(new string(escapedChar, 1), new JsonPrimitive(escapedChar));
}
foreach (string stringRepresentation in allValues.Keys)
{
JsonPrimitive jp = allValues[stringRepresentation];
Assert.Equal(stringRepresentation, (string)jp);
Assert.Equal(stringRepresentation, jp.ReadAs<string>());
}
}
[Fact]
public void NonNumberToNumberConversionTest()
{
Assert.Equal(1, new JsonPrimitive('1').ReadAs<int>());
Assert.Equal<byte>(AnyInstance.AnyByte, new JsonPrimitive(AnyInstance.AnyByte.ToString(CultureInfo.InvariantCulture)).ReadAs<byte>());
Assert.Equal<sbyte>(AnyInstance.AnySByte, (sbyte)(new JsonPrimitive(AnyInstance.AnySByte.ToString(CultureInfo.InvariantCulture))));
Assert.Equal<short>(AnyInstance.AnyShort, (short)(new JsonPrimitive(AnyInstance.AnyShort.ToString(CultureInfo.InvariantCulture))));
Assert.Equal<ushort>(AnyInstance.AnyUShort, new JsonPrimitive(AnyInstance.AnyUShort.ToString(CultureInfo.InvariantCulture)).ReadAs<ushort>());
Assert.Equal<int>(AnyInstance.AnyInt, new JsonPrimitive(AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture)).ReadAs<int>());
Assert.Equal<uint>(AnyInstance.AnyUInt, (uint)(new JsonPrimitive(AnyInstance.AnyUInt.ToString(CultureInfo.InvariantCulture))));
Assert.Equal<long>(AnyInstance.AnyLong, (long)(new JsonPrimitive(AnyInstance.AnyLong.ToString(CultureInfo.InvariantCulture))));
Assert.Equal<ulong>(AnyInstance.AnyULong, new JsonPrimitive(AnyInstance.AnyULong.ToString(CultureInfo.InvariantCulture)).ReadAs<ulong>());
Assert.Equal<decimal>(AnyInstance.AnyDecimal, (decimal)(new JsonPrimitive(AnyInstance.AnyDecimal.ToString(CultureInfo.InvariantCulture))));
Assert.Equal<float>(AnyInstance.AnyFloat, new JsonPrimitive(AnyInstance.AnyFloat.ToString(CultureInfo.InvariantCulture)).ReadAs<float>());
Assert.Equal<double>(AnyInstance.AnyDouble, (double)(new JsonPrimitive(AnyInstance.AnyDouble.ToString(CultureInfo.InvariantCulture))));
Assert.Equal<byte>(Convert.ToByte(1.23, CultureInfo.InvariantCulture), new JsonPrimitive("1.23").ReadAs<byte>());
Assert.Equal<int>(Convert.ToInt32(12345.6789, CultureInfo.InvariantCulture), new JsonPrimitive("12345.6789").ReadAs<int>());
Assert.Equal<short>(Convert.ToInt16(1.23e2), (short)new JsonPrimitive("1.23e2"));
Assert.Equal<float>(Convert.ToSingle(1.23e40), (float)new JsonPrimitive("1.23e40"));
Assert.Equal<float>(Convert.ToSingle(1.23e-38), (float)new JsonPrimitive("1.23e-38"));
ExceptionHelper.Throws<InvalidCastException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyBool).ReadAs<sbyte>(); });
ExceptionHelper.Throws<InvalidCastException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyBool).ReadAs<short>(); });
ExceptionHelper.Throws<InvalidCastException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyBool).ReadAs<uint>(); });
ExceptionHelper.Throws<InvalidCastException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyBool).ReadAs<long>(); });
ExceptionHelper.Throws<InvalidCastException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyBool).ReadAs<double>(); });
ExceptionHelper.Throws<FormatException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyUri).ReadAs<int>(); });
ExceptionHelper.Throws<FormatException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyDateTime).ReadAs<float>(); });
ExceptionHelper.Throws<InvalidCastException>(delegate { var n = (decimal)(new JsonPrimitive('c')); });
ExceptionHelper.Throws<InvalidCastException>(delegate { var n = (byte)(new JsonPrimitive("0xFF")); });
ExceptionHelper.Throws<InvalidCastException>(delegate { var n = (sbyte)(new JsonPrimitive(AnyInstance.AnyDateTimeOffset)); });
ExceptionHelper.Throws<FormatException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyUri).ReadAs<uint>(); });
ExceptionHelper.Throws<FormatException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyDateTime).ReadAs<double>(); });
ExceptionHelper.Throws<InvalidCastException>(delegate { var n = (long)(new JsonPrimitive('c')); });
ExceptionHelper.Throws<InvalidCastException>(delegate { var n = (ulong)(new JsonPrimitive("0xFF")); });
ExceptionHelper.Throws<InvalidCastException>(delegate { var n = (short)(new JsonPrimitive(AnyInstance.AnyDateTimeOffset)); });
ExceptionHelper.Throws<InvalidCastException>(delegate { var n = (ushort)(new JsonPrimitive('c')); });
ExceptionHelper.Throws<OverflowException>(delegate { int i = (int)new JsonPrimitive((1L << 32).ToString(CultureInfo.InvariantCulture)); });
ExceptionHelper.Throws<OverflowException>(delegate { byte b = (byte)new JsonPrimitive("-1"); });
}
[Fact]
public void StringToNonNumberConversionTest()
{
const string DateTimeWithOffsetFormat = "yyyy-MM-ddTHH:mm:sszzz";
const string DateTimeWithOffsetFormat2 = "yyy-MM-ddTHH:mm:ss.fffK";
const string DateTimeWithoutOffsetWithoutTimeFormat = "yyy-MM-dd";
const string DateTimeWithoutOffsetFormat = "yyy-MM-ddTHH:mm:ss";
const string DateTimeWithoutOffsetFormat2 = "yyy-MM-ddTHH:mm:ss.fff";
const string TimeWithoutOffsetFormat = "HH:mm:ss";
const string TimeWithoutOffsetFormat2 = "HH:mm";
Assert.Equal(false, new JsonPrimitive("false").ReadAs<bool>());
Assert.Equal(false, (bool)(new JsonPrimitive("False")));
Assert.Equal(true, (bool)(new JsonPrimitive("true")));
Assert.Equal(true, new JsonPrimitive("True").ReadAs<bool>());
Assert.Equal<Uri>(AnyInstance.AnyUri, new JsonPrimitive(AnyInstance.AnyUri.ToString()).ReadAs<Uri>());
Assert.Equal<char>(AnyInstance.AnyChar, (char)(new JsonPrimitive(new string(AnyInstance.AnyChar, 1))));
Assert.Equal<Guid>(AnyInstance.AnyGuid, (Guid)(new JsonPrimitive(AnyInstance.AnyGuid.ToString("D", CultureInfo.InvariantCulture))));
DateTime anyLocalDateTime = AnyInstance.AnyDateTime.ToLocalTime();
DateTime anyUtcDateTime = AnyInstance.AnyDateTime.ToUniversalTime();
Assert.Equal<DateTime>(anyUtcDateTime, (DateTime)(new JsonPrimitive(anyUtcDateTime.ToString(DateTimeFormat, CultureInfo.InvariantCulture))));
Assert.Equal<DateTime>(anyLocalDateTime, new JsonPrimitive(anyLocalDateTime.ToString(DateTimeWithOffsetFormat2, CultureInfo.InvariantCulture)).ReadAs<DateTime>());
Assert.Equal<DateTime>(anyUtcDateTime, new JsonPrimitive(anyUtcDateTime.ToString(DateTimeWithOffsetFormat2, CultureInfo.InvariantCulture)).ReadAs<DateTime>());
Assert.Equal<DateTime>(anyLocalDateTime.Date, (DateTime)(new JsonPrimitive(anyLocalDateTime.ToString(DateTimeWithoutOffsetWithoutTimeFormat, CultureInfo.InvariantCulture))));
Assert.Equal<DateTime>(anyLocalDateTime, new JsonPrimitive(anyLocalDateTime.ToString(DateTimeWithoutOffsetFormat, CultureInfo.InvariantCulture)).ReadAs<DateTime>());
Assert.Equal<DateTime>(anyLocalDateTime, new JsonPrimitive(anyLocalDateTime.ToString(DateTimeWithoutOffsetFormat2, CultureInfo.InvariantCulture)).ReadAs<DateTime>());
DateTime dt = new JsonPrimitive(anyLocalDateTime.ToString(TimeWithoutOffsetFormat, CultureInfo.InvariantCulture)).ReadAs<DateTime>();
Assert.Equal(anyLocalDateTime.Hour, dt.Hour);
Assert.Equal(anyLocalDateTime.Minute, dt.Minute);
Assert.Equal(anyLocalDateTime.Second, dt.Second);
dt = new JsonPrimitive(anyLocalDateTime.ToString(TimeWithoutOffsetFormat2, CultureInfo.InvariantCulture)).ReadAs<DateTime>();
Assert.Equal(anyLocalDateTime.Hour, dt.Hour);
Assert.Equal(anyLocalDateTime.Minute, dt.Minute);
Assert.Equal(0, dt.Second);
Assert.Equal<DateTimeOffset>(AnyInstance.AnyDateTimeOffset, new JsonPrimitive(AnyInstance.AnyDateTimeOffset.ToString(DateTimeFormat, CultureInfo.InvariantCulture)).ReadAs<DateTimeOffset>());
Assert.Equal<DateTimeOffset>(AnyInstance.AnyDateTimeOffset, new JsonPrimitive(AnyInstance.AnyDateTimeOffset.ToString(DateTimeWithOffsetFormat, CultureInfo.InvariantCulture)).ReadAs<DateTimeOffset>());
Assert.Equal<DateTimeOffset>(AnyInstance.AnyDateTimeOffset, new JsonPrimitive(AnyInstance.AnyDateTimeOffset.ToString(DateTimeWithOffsetFormat2, CultureInfo.InvariantCulture)).ReadAs<DateTimeOffset>());
Assert.Equal<DateTimeOffset>(AnyInstance.AnyDateTimeOffset.ToLocalTime(), (DateTimeOffset)(new JsonPrimitive(AnyInstance.AnyDateTimeOffset.ToLocalTime().ToString(DateTimeWithoutOffsetFormat, CultureInfo.InvariantCulture))));
Assert.Equal<DateTimeOffset>(AnyInstance.AnyDateTimeOffset.ToLocalTime(), (DateTimeOffset)(new JsonPrimitive(AnyInstance.AnyDateTimeOffset.ToLocalTime().ToString(DateTimeWithoutOffsetFormat2, CultureInfo.InvariantCulture))));
DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(DateTime));
MemoryStream ms = new MemoryStream();
dcjs.WriteObject(ms, AnyInstance.AnyDateTime);
string dcjsSerializedDateTime = Encoding.UTF8.GetString(ms.ToArray());
Assert.Equal(AnyInstance.AnyDateTime, JsonValue.Parse(dcjsSerializedDateTime).ReadAs<DateTime>());
ExceptionHelper.Throws<InvalidCastException>(delegate { var b = (bool)(new JsonPrimitive("notBool")); });
ExceptionHelper.Throws<UriFormatException>(delegate { var u = new JsonPrimitive("not an uri - " + new string('r', 100000)).ReadAs<Uri>(); });
ExceptionHelper.Throws<FormatException>(delegate { var date = new JsonPrimitive("not a date time").ReadAs<DateTime>(); });
ExceptionHelper.Throws<InvalidCastException>(delegate { var dto = (DateTimeOffset)(new JsonPrimitive("not a date time offset")); });
ExceptionHelper.Throws<InvalidCastException>(delegate { var c = (char)new JsonPrimitive(""); });
ExceptionHelper.Throws<InvalidCastException>(delegate { var c = (char)new JsonPrimitive("cc"); });
ExceptionHelper.Throws<FormatException>(delegate { var g = new JsonPrimitive("not a guid").ReadAs<Guid>(); });
}
[Fact]
public void AspNetDateTimeFormatConversionTest()
{
DateTime unixEpochUtc = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime unixEpochLocal = unixEpochUtc.ToLocalTime();
Assert.Equal(unixEpochUtc, new JsonPrimitive("/Date(0)/").ReadAs<DateTime>());
Assert.Equal(unixEpochLocal, new JsonPrimitive("/Date(0-0900)/").ReadAs<DateTime>());
Assert.Equal(unixEpochLocal, new JsonPrimitive("/Date(0+1000)/").ReadAs<DateTime>());
}
[Fact]
public void ToStringTest()
{
char anyUnescapedChar = 'c';
string anyUnescapedString = "hello";
Dictionary<string, JsonPrimitive> toStringResults = new Dictionary<string, JsonPrimitive>
{
// Boolean types
{ AnyInstance.AnyBool.ToString(CultureInfo.InvariantCulture).ToLowerInvariant(), new JsonPrimitive(AnyInstance.AnyBool) },
// Numeric types
{ AnyInstance.AnyByte.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyByte) },
{ AnyInstance.AnySByte.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnySByte) },
{ AnyInstance.AnyShort.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyShort) },
{ AnyInstance.AnyUShort.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyUShort) },
{ AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyInt) },
{ AnyInstance.AnyUInt.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyUInt) },
{ AnyInstance.AnyLong.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyLong) },
{ AnyInstance.AnyULong.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyULong) },
{ AnyInstance.AnyFloat.ToString("R", CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyFloat) },
{ AnyInstance.AnyDouble.ToString("R", CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyDouble) },
{ AnyInstance.AnyDecimal.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyDecimal) },
// String types
{ "\"" + new string(anyUnescapedChar, 1) + "\"", new JsonPrimitive(anyUnescapedChar) },
{ "\"" + anyUnescapedString + "\"", new JsonPrimitive(anyUnescapedString) },
{ "\"" + AnyInstance.AnyDateTime.ToString(DateTimeFormat, CultureInfo.InvariantCulture) + "\"", new JsonPrimitive(AnyInstance.AnyDateTime) },
{ "\"" + AnyInstance.AnyDateTimeOffset.ToString(DateTimeFormat, CultureInfo.InvariantCulture) + "\"", new JsonPrimitive(AnyInstance.AnyDateTimeOffset) },
{ "\"" + AnyInstance.AnyUri.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped).Replace("/", "\\/") + "\"", new JsonPrimitive(AnyInstance.AnyUri) },
{ "\"" + AnyInstance.AnyGuid.ToString("D", CultureInfo.InvariantCulture) + "\"", new JsonPrimitive(AnyInstance.AnyGuid) },
};
foreach (string stringRepresentation in toStringResults.Keys)
{
string actualResult = toStringResults[stringRepresentation].ToString();
Assert.Equal(stringRepresentation, actualResult);
}
Dictionary<string, JsonPrimitive> escapedValues = new Dictionary<string, JsonPrimitive>
{
{ "\"\\u000d\"", new JsonPrimitive('\r') },
{ "\"\\u000a\"", new JsonPrimitive('\n') },
{ "\"\\\\\"", new JsonPrimitive('\\') },
{ "\"\\/\"", new JsonPrimitive('/') },
{ "\"\\u000b\"", new JsonPrimitive('\u000b') },
{ "\"\\\"\"", new JsonPrimitive('\"') },
{ "\"slash-r-\\u000d-fffe-\\ufffe-ffff-\\uffff-tab-\\u0009\"", new JsonPrimitive("slash-r-\r-fffe-\ufffe-ffff-\uffff-tab-\t") },
};
foreach (string stringRepresentation in escapedValues.Keys)
{
string actualResult = escapedValues[stringRepresentation].ToString();
Assert.Equal(stringRepresentation, actualResult);
}
}
[Fact]
public void JsonTypeTest()
{
Assert.Equal(JsonType.Boolean, new JsonPrimitive(AnyInstance.AnyBool).JsonType);
Assert.Equal(JsonType.Number, new JsonPrimitive(AnyInstance.AnyByte).JsonType);
Assert.Equal(JsonType.Number, new JsonPrimitive(AnyInstance.AnySByte).JsonType);
Assert.Equal(JsonType.Number, new JsonPrimitive(AnyInstance.AnyShort).JsonType);
Assert.Equal(JsonType.Number, new JsonPrimitive(AnyInstance.AnyUShort).JsonType);
Assert.Equal(JsonType.Number, new JsonPrimitive(AnyInstance.AnyInt).JsonType);
Assert.Equal(JsonType.Number, new JsonPrimitive(AnyInstance.AnyUInt).JsonType);
Assert.Equal(JsonType.Number, new JsonPrimitive(AnyInstance.AnyLong).JsonType);
Assert.Equal(JsonType.Number, new JsonPrimitive(AnyInstance.AnyULong).JsonType);
Assert.Equal(JsonType.Number, new JsonPrimitive(AnyInstance.AnyDecimal).JsonType);
Assert.Equal(JsonType.Number, new JsonPrimitive(AnyInstance.AnyDouble).JsonType);
Assert.Equal(JsonType.Number, new JsonPrimitive(AnyInstance.AnyFloat).JsonType);
Assert.Equal(JsonType.String, new JsonPrimitive(AnyInstance.AnyChar).JsonType);
Assert.Equal(JsonType.String, new JsonPrimitive(AnyInstance.AnyString).JsonType);
Assert.Equal(JsonType.String, new JsonPrimitive(AnyInstance.AnyUri).JsonType);
Assert.Equal(JsonType.String, new JsonPrimitive(AnyInstance.AnyGuid).JsonType);
Assert.Equal(JsonType.String, new JsonPrimitive(AnyInstance.AnyDateTime).JsonType);
Assert.Equal(JsonType.String, new JsonPrimitive(AnyInstance.AnyDateTimeOffset).JsonType);
}
[Fact]
public void InvalidPropertyTest()
{
JsonValue target = AnyInstance.AnyJsonPrimitive;
Assert.True(target.Count == 0);
Assert.False(target.ContainsKey(String.Empty));
Assert.False(target.ContainsKey(AnyInstance.AnyString));
}
private void CheckValues(object[] values, JsonType expectedType)
{
JsonPrimitive target;
bool success;
foreach (object value in values)
{
success = JsonPrimitive.TryCreate(value, out target);
Assert.True(success);
Assert.NotNull(target);
Assert.Equal(expectedType, target.JsonType);
}
}
}
}

Просмотреть файл

@ -1,28 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Json
{
public class JsonTypeTest
{
[Fact]
public void JsonTypeValues()
{
string[] allJsonTypeExpectedValues = new string[] { "Array", "Boolean", "Default", "Number", "Object", "String" };
JsonType[] allJsonTypeActualValues = (JsonType[])Enum.GetValues(typeof(JsonType));
Assert.Equal(allJsonTypeExpectedValues.Length, allJsonTypeActualValues.Length);
List<string> allJsonTypeActualStringValues = new List<string>(allJsonTypeActualValues.Select((x) => x.ToString()));
allJsonTypeActualStringValues.Sort(StringComparer.Ordinal);
for (int i = 0; i < allJsonTypeExpectedValues.Length; i++)
{
Assert.Equal(allJsonTypeExpectedValues[i], allJsonTypeActualStringValues[i]);
}
}
}
}

Просмотреть файл

@ -1,536 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Dynamic;
using System.Linq.Expressions;
using Xunit;
namespace System.Json
{
/// <summary>
///This is a test class for JsonValueDynamicMetaObjectTest and is intended to perform sanity tests on this class.
///Extended tests are performed by the JsonValue dynamic feature tests.
///</summary>
public class JsonValueDynamicMetaObjectTest
{
const string NonSingleNonNullIndexNotSupported = "Null index or multidimensional indexing is not supported by this indexer; use 'System.Int32' or 'System.String' for array and object indexing respectively.";
/// <summary>
/// A test for GetMetaObject
///</summary>
[Fact]
public void GetMetaObjectTest()
{
ExceptionHelper.Throws<ArgumentNullException>(() => { var target = GetJsonValueDynamicMetaObject(AnyInstance.AnyJsonObject, null); });
}
/// <summary>
/// A test for BindInvokeMember
///</summary>
[Fact]
public void BindInvokeMemberTest()
{
JsonValue value = AnyInstance.AnyJsonValue1;
DynamicMetaObject target = GetJsonValueDynamicMetaObject(value);
TestInvokeMemberBinder.TestBindParams(target);
string methodName;
object[] arguments;
object result = null;
methodName = "ToString";
arguments = new object[] { };
TestInvokeMemberBinder.TestMetaObject(target, methodName, arguments);
methodName = "TryReadAs";
arguments = new object[] { typeof(int), result };
TestInvokeMemberBinder.TestMetaObject(target, methodName, arguments);
methodName = "TryReadAsType";
arguments = new object[] { typeof(Person), result };
TestInvokeMemberBinder.TestMetaObject(target, methodName, arguments, true);
}
/// <summary>
/// A test for BindConvert
///</summary>
[Fact]
public void BindConvertTest()
{
JsonValue value;
DynamicMetaObject target;
value = (JsonValue)AnyInstance.AnyInt;
target = GetJsonValueDynamicMetaObject(value);
TestConvertBinder.TestBindParams(target);
Type[] intTypes = { typeof(int), typeof(uint), typeof(long), };
foreach (Type type in intTypes)
{
TestConvertBinder.TestMetaObject(target, type);
}
value = (JsonValue)AnyInstance.AnyString;
target = GetJsonValueDynamicMetaObject(value);
TestConvertBinder.TestMetaObject(target, typeof(string));
value = (JsonValue)AnyInstance.AnyJsonValue1;
target = GetJsonValueDynamicMetaObject(value);
TestConvertBinder.TestMetaObject(target, typeof(JsonValue));
TestConvertBinder.TestMetaObject(target, typeof(IEnumerable<KeyValuePair<string, JsonValue>>));
TestConvertBinder.TestMetaObject(target, typeof(IDynamicMetaObjectProvider));
TestConvertBinder.TestMetaObject(target, typeof(object));
TestConvertBinder.TestMetaObject(target, typeof(Person), false);
}
/// <summary>
/// A test for BindGetIndex
///</summary>
[Fact]
public void BindGetIndexTest()
{
JsonValue value = AnyInstance.AnyJsonArray;
DynamicMetaObject target = GetJsonValueDynamicMetaObject(value);
TestGetIndexBinder.TestBindParams(target);
foreach (KeyValuePair<string, JsonValue> pair in value)
{
TestGetIndexBinder.TestMetaObject(target, Int32.Parse(pair.Key));
}
}
/// <summary>
/// A test for BindSetIndex
///</summary>
[Fact]
public void BindSetIndexTest()
{
JsonValue jsonValue = AnyInstance.AnyJsonArray;
DynamicMetaObject target = GetJsonValueDynamicMetaObject(jsonValue);
TestSetIndexBinder.TestBindParams(target);
int value = 0;
foreach (KeyValuePair<string, JsonValue> pair in jsonValue)
{
TestSetIndexBinder.TestMetaObject(target, Int32.Parse(pair.Key), value++);
}
}
/// <summary>
/// A test for BindGetMember.
///</summary>
[Fact]
public void BindGetMemberTest()
{
JsonValue value = AnyInstance.AnyJsonObject;
DynamicMetaObject target = GetJsonValueDynamicMetaObject(value);
TestGetMemberBinder.TestBindParams(target);
foreach (KeyValuePair<string, JsonValue> pair in value)
{
TestGetMemberBinder.TestMetaObject(target, pair.Key);
}
}
/// <summary>
/// A test for BindSetMember.
///</summary>
[Fact]
public void BindSetMemberTest()
{
JsonValue value = AnyInstance.AnyJsonObject;
string expectedMethodSignature = "System.Json.JsonValue SetValue(System.String, System.Object)";
DynamicMetaObject target = GetJsonValueDynamicMetaObject(value);
DynamicMetaObject arg = new DynamicMetaObject(Expression.Parameter(typeof(int)), BindingRestrictions.Empty, AnyInstance.AnyInt);
TestSetMemberBinder.TestBindParams(target, arg);
foreach (KeyValuePair<string, JsonValue> pair in value)
{
TestSetMemberBinder.TestMetaObject(target, pair.Key, arg, expectedMethodSignature);
}
}
/// <summary>
/// A test for GetDynamicMemberNames
///</summary>
[Fact]
public void GetDynamicMemberNamesTest()
{
JsonValue[] values = AnyInstance.AnyJsonValueArray;
foreach (JsonValue value in values)
{
DynamicMetaObject target = GetJsonValueDynamicMetaObject(value);
List<string> expected = new List<string>();
foreach (KeyValuePair<string, JsonValue> pair in value)
{
expected.Add(pair.Key);
}
IEnumerable<string> retEnumerable = target.GetDynamicMemberNames();
Assert.NotNull(retEnumerable);
List<string> actual = new List<string>(retEnumerable);
Assert.Equal(expected.Count, actual.Count);
for (int i = 0; i < expected.Count; i++)
{
Assert.Equal<string>(expected[i], actual[i]);
}
}
}
/// <summary>
/// Helper method for getting a <see cref="JsonValueDynamicMetaObject"/>.
/// </summary>
/// <param name="jsonValue">The <see cref="JsonValue"/> instance to get the dynamic meta-object from.</param>
/// <returns></returns>
private static DynamicMetaObject GetJsonValueDynamicMetaObject(JsonValue jsonValue)
{
return GetJsonValueDynamicMetaObject(jsonValue, Expression.Parameter(typeof(object)));
}
private static DynamicMetaObject GetJsonValueDynamicMetaObject(JsonValue jsonValue, Expression expression)
{
return ((IDynamicMetaObjectProvider)jsonValue).GetMetaObject(expression);
}
/// <summary>
/// Test binder for method call operation.
/// </summary>
private class TestInvokeMemberBinder : InvokeMemberBinder
{
public TestInvokeMemberBinder(string name, int argCount)
: base(name, false, new CallInfo(argCount, new string[] { }))
{
}
public static void TestBindParams(DynamicMetaObject target)
{
string methodName = "ToString";
object[] arguments = new object[] { };
InvokeMemberBinder binder = new TestInvokeMemberBinder(methodName, arguments.Length);
DynamicMetaObject[] args = new DynamicMetaObject[arguments.Length];
ExceptionHelper.Throws<ArgumentNullException>(() => { var result = target.BindInvokeMember(null, args); });
ExceptionHelper.Throws<ArgumentNullException>(() => { var result = target.BindInvokeMember(binder, null); });
}
public static void TestMetaObject(DynamicMetaObject target, string methodName, object[] arguments, bool isExtension = false)
{
InvokeMemberBinder binder = new TestInvokeMemberBinder(methodName, arguments.Length);
DynamicMetaObject[] args = new DynamicMetaObject[arguments.Length];
for (int idx = 0; idx < args.Length; idx++)
{
object value = arguments[idx];
Type valueType = value != null ? value.GetType() : typeof(object);
args[idx] = new DynamicMetaObject(Expression.Parameter(valueType), BindingRestrictions.Empty, value);
}
DynamicMetaObject result = target.BindInvokeMember(binder, args);
Assert.NotNull(result);
if (isExtension)
{
UnaryExpression expression = result.Expression as UnaryExpression;
Assert.NotNull(expression);
MethodCallExpression callExpression = expression.Operand as MethodCallExpression;
Assert.NotNull(callExpression);
Assert.True(callExpression.Method.ToString().Contains(methodName));
}
else
{
Assert.Same(target, result.Value);
}
}
public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion)
{
throw new NotImplementedException();
}
public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion)
{
// This is where the C# binder does the actual binding.
return new DynamicMetaObject(Expression.Constant("FallbackInvokeMember called"), BindingRestrictions.Empty, target);
}
}
/// <summary>
/// The binder for the cast operation.
/// </summary>
private class TestConvertBinder : ConvertBinder
{
public TestConvertBinder(Type type)
: base(type, false)
{
}
public static void TestBindParams(DynamicMetaObject target)
{
ConvertBinder binder = new TestConvertBinder(typeof(int));
ExceptionHelper.Throws<ArgumentNullException>(() => { var result = target.BindConvert(null); });
}
public static void TestMetaObject(DynamicMetaObject target, Type type, bool isValid = true)
{
ConvertBinder binder = new TestConvertBinder(type);
DynamicMetaObject result = target.BindConvert(binder);
Assert.NotNull(result);
// Convert expression
UnaryExpression expression = result.Expression as UnaryExpression;
Assert.NotNull(expression);
Assert.Equal<Type>(binder.Type, expression.Type);
if (isValid)
{
MethodCallExpression methodCallExp = expression.Operand as MethodCallExpression;
if (methodCallExp != null)
{
Assert.True(methodCallExp.Method.ToString().Contains("CastValue"));
}
else
{
ParameterExpression paramExpression = expression.Operand as ParameterExpression;
Assert.NotNull(paramExpression);
}
}
else
{
Expression<Action> throwExp = Expression.Lambda<Action>(Expression.Block(expression), new ParameterExpression[] { });
ExceptionHelper.Throws<InvalidCastException>(() => throwExp.Compile().Invoke());
}
}
public override DynamicMetaObject FallbackConvert(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
{
throw new NotImplementedException();
}
}
/// <summary>
/// Test binder for int indexer getter operation.
/// </summary>
private class TestGetIndexBinder : GetIndexBinder
{
public TestGetIndexBinder()
: base(new CallInfo(0, new string[] { }))
{
}
public static void TestBindParams(DynamicMetaObject target)
{
GetIndexBinder binder = new TestGetIndexBinder();
Expression typeExpression = Expression.Parameter(typeof(int));
DynamicMetaObject[] indexes =
{
new DynamicMetaObject(typeExpression, BindingRestrictions.Empty, 0),
new DynamicMetaObject(typeExpression, BindingRestrictions.Empty, 1),
new DynamicMetaObject(typeExpression, BindingRestrictions.Empty, 2)
};
ExceptionHelper.Throws<ArgumentNullException>(() => { var result = target.BindGetIndex(null, indexes); });
ExceptionHelper.Throws<ArgumentNullException>(() => { var result = target.BindGetIndex(binder, null); });
DynamicMetaObject[][] invalidIndexesParam =
{
indexes,
new DynamicMetaObject[] { new DynamicMetaObject(typeExpression, BindingRestrictions.Empty, null) },
new DynamicMetaObject[] { null },
new DynamicMetaObject[] { }
};
foreach (DynamicMetaObject[] indexesParam in invalidIndexesParam)
{
DynamicMetaObject metaObj = target.BindGetIndex(binder, indexesParam);
Expression<Action> expression = Expression.Lambda<Action>(Expression.Block(metaObj.Expression), new ParameterExpression[] { });
ExceptionHelper.Throws<ArgumentException>(() => { expression.Compile().Invoke(); }, NonSingleNonNullIndexNotSupported);
}
}
public static void TestMetaObject(DynamicMetaObject target, int index, bool isValid = true)
{
string expectedMethodSignature = "System.Json.JsonValue GetValue(Int32)";
GetIndexBinder binder = new TestGetIndexBinder();
DynamicMetaObject[] indexes = { new DynamicMetaObject(Expression.Parameter(typeof(int)), BindingRestrictions.Empty, index) };
DynamicMetaObject result = target.BindGetIndex(binder, indexes);
Assert.NotNull(result);
MethodCallExpression expression = result.Expression as MethodCallExpression;
Assert.NotNull(expression);
Assert.Equal<string>(expectedMethodSignature, expression.Method.ToString());
}
public override DynamicMetaObject FallbackGetIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject errorSuggestion)
{
throw new NotImplementedException();
}
}
/// <summary>
/// Test binder for int indexer setter operation.
/// </summary>
private class TestSetIndexBinder : SetIndexBinder
{
public TestSetIndexBinder()
: base(new CallInfo(0, new string[] { }))
{
}
public static void TestBindParams(DynamicMetaObject target)
{
SetIndexBinder binder = new TestSetIndexBinder();
Expression typeExpression = Expression.Parameter(typeof(int));
DynamicMetaObject[] indexes = new DynamicMetaObject[] { new DynamicMetaObject(typeExpression, BindingRestrictions.Empty, 0) };
DynamicMetaObject value = new DynamicMetaObject(typeExpression, BindingRestrictions.Empty, (JsonValue)10);
ExceptionHelper.Throws<ArgumentNullException>(() => { var result = target.BindSetIndex(null, indexes, value); });
ExceptionHelper.Throws<ArgumentNullException>(() => { var result = target.BindSetIndex(binder, null, value); });
ExceptionHelper.Throws<ArgumentNullException>(() => { var result = target.BindSetIndex(binder, indexes, null); });
DynamicMetaObject[][] invalidIndexesParam =
{
new DynamicMetaObject[]
{
new DynamicMetaObject(typeExpression, BindingRestrictions.Empty, 0),
new DynamicMetaObject(typeExpression, BindingRestrictions.Empty, 1),
new DynamicMetaObject(typeExpression, BindingRestrictions.Empty, 2)
},
new DynamicMetaObject[]
{
new DynamicMetaObject(typeExpression, BindingRestrictions.Empty, null)
},
new DynamicMetaObject[]
{
}
};
foreach (DynamicMetaObject[] indexesParam in invalidIndexesParam)
{
DynamicMetaObject metaObj = target.BindSetIndex(binder, indexesParam, value);
Expression<Action> expression = Expression.Lambda<Action>(Expression.Block(metaObj.Expression), new ParameterExpression[] { });
ExceptionHelper.Throws<ArgumentException>(() => { expression.Compile().Invoke(); }, NonSingleNonNullIndexNotSupported);
}
}
public static void TestMetaObject(DynamicMetaObject target, int index, JsonValue jsonValue, bool isValid = true)
{
string expectedMethodSignature = "System.Json.JsonValue SetValue(Int32, System.Object)";
SetIndexBinder binder = new TestSetIndexBinder();
DynamicMetaObject[] indexes = { new DynamicMetaObject(Expression.Parameter(typeof(int)), BindingRestrictions.Empty, index) };
DynamicMetaObject value = new DynamicMetaObject(Expression.Parameter(jsonValue.GetType()), BindingRestrictions.Empty, jsonValue);
DynamicMetaObject result = target.BindSetIndex(binder, indexes, value);
Assert.NotNull(result);
MethodCallExpression expression = result.Expression as MethodCallExpression;
Assert.NotNull(expression);
Assert.Equal<string>(expectedMethodSignature, expression.Method.ToString());
}
public override DynamicMetaObject FallbackSetIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject value, DynamicMetaObject errorSuggestion)
{
throw new NotImplementedException();
}
}
/// <summary>
/// Test binder for key indexer getter.
/// </summary>
private class TestGetMemberBinder : GetMemberBinder
{
public TestGetMemberBinder(string name)
: base(name, false)
{
}
public static void TestBindParams(DynamicMetaObject target)
{
GetMemberBinder binder = new TestGetMemberBinder("AnyProperty");
ExceptionHelper.Throws<ArgumentNullException>(() => { var result = target.BindGetMember(null); });
}
public static void TestMetaObject(DynamicMetaObject target, string name, bool isValid = true)
{
string expectedMethodSignature = "System.Json.JsonValue GetValue(System.String)";
GetMemberBinder binder = new TestGetMemberBinder(name);
DynamicMetaObject result = target.BindGetMember(binder);
Assert.NotNull(result);
MethodCallExpression expression = result.Expression as MethodCallExpression;
Assert.NotNull(expression);
Assert.Equal<string>(expectedMethodSignature, expression.Method.ToString());
}
public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
{
throw new NotImplementedException();
}
}
/// <summary>
/// Test binder for key indexer setter.
/// </summary>
private class TestSetMemberBinder : SetMemberBinder
{
public TestSetMemberBinder(string name)
: base(name, false)
{
}
public static void TestBindParams(DynamicMetaObject target, DynamicMetaObject value)
{
SetMemberBinder binder = new TestSetMemberBinder("AnyProperty");
ExceptionHelper.Throws<ArgumentNullException>(() => { var result = target.BindSetMember(null, value); });
ExceptionHelper.Throws<ArgumentNullException>(() => { var result = target.BindSetMember(binder, null); });
}
public static void TestMetaObject(DynamicMetaObject target, string name, DynamicMetaObject value, string expectedMethodSignature, bool isValid = true)
{
SetMemberBinder binder = new TestSetMemberBinder(name);
DynamicMetaObject result = target.BindSetMember(binder, value);
Assert.NotNull(result);
MethodCallExpression expression = result.Expression as MethodCallExpression;
Assert.NotNull(expression);
Assert.Equal<string>(expectedMethodSignature, expression.Method.ToString());
}
public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, DynamicMetaObject value, DynamicMetaObject errorSuggestion)
{
throw new NotImplementedException();
}
}
}
}

Просмотреть файл

@ -1,470 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Dynamic;
using System.Runtime.Serialization.Json;
using Xunit;
namespace System.Json
{
public class JsonValueDynamicTest
{
const string InvalidIndexType = "Invalid '{0}' index type; only 'System.String' and non-negative 'System.Int32' types are supported.";
const string NonSingleNonNullIndexNotSupported = "Null index or multidimensional indexing is not supported by this indexer; use 'System.Int32' or 'System.String' for array and object indexing respectively.";
[Fact]
public void SettingDifferentValueTypes()
{
dynamic dyn = new JsonObject();
dyn.boolean = AnyInstance.AnyBool;
dyn.int16 = AnyInstance.AnyShort;
dyn.int32 = AnyInstance.AnyInt;
dyn.int64 = AnyInstance.AnyLong;
dyn.uint16 = AnyInstance.AnyUShort;
dyn.uint32 = AnyInstance.AnyUInt;
dyn.uint64 = AnyInstance.AnyULong;
dyn.@char = AnyInstance.AnyChar;
dyn.dbl = AnyInstance.AnyDouble;
dyn.flt = AnyInstance.AnyFloat;
dyn.dec = AnyInstance.AnyDecimal;
dyn.str = AnyInstance.AnyString;
dyn.uri = AnyInstance.AnyUri;
dyn.@byte = AnyInstance.AnyByte;
dyn.@sbyte = AnyInstance.AnySByte;
dyn.guid = AnyInstance.AnyGuid;
dyn.dateTime = AnyInstance.AnyDateTime;
dyn.dateTimeOffset = AnyInstance.AnyDateTimeOffset;
dyn.JsonArray = AnyInstance.AnyJsonArray;
dyn.JsonPrimitive = AnyInstance.AnyJsonPrimitive;
dyn.JsonObject = AnyInstance.AnyJsonObject;
JsonObject jo = (JsonObject)dyn;
Assert.Equal(AnyInstance.AnyBool, (bool)jo["boolean"]);
Assert.Equal(AnyInstance.AnyShort, (short)jo["int16"]);
Assert.Equal(AnyInstance.AnyUShort, (ushort)jo["uint16"]);
Assert.Equal(AnyInstance.AnyInt, (int)jo["int32"]);
Assert.Equal(AnyInstance.AnyUInt, (uint)jo["uint32"]);
Assert.Equal(AnyInstance.AnyLong, (long)jo["int64"]);
Assert.Equal(AnyInstance.AnyULong, (ulong)jo["uint64"]);
Assert.Equal(AnyInstance.AnySByte, (sbyte)jo["sbyte"]);
Assert.Equal(AnyInstance.AnyByte, (byte)jo["byte"]);
Assert.Equal(AnyInstance.AnyChar, (char)jo["char"]);
Assert.Equal(AnyInstance.AnyDouble, (double)jo["dbl"]);
Assert.Equal(AnyInstance.AnyFloat, (float)jo["flt"]);
Assert.Equal(AnyInstance.AnyDecimal, (decimal)jo["dec"]);
Assert.Equal(AnyInstance.AnyString, (string)jo["str"]);
Assert.Equal(AnyInstance.AnyUri, (Uri)jo["uri"]);
Assert.Equal(AnyInstance.AnyGuid, (Guid)jo["guid"]);
Assert.Equal(AnyInstance.AnyDateTime, (DateTime)jo["dateTime"]);
Assert.Equal(AnyInstance.AnyDateTimeOffset, (DateTimeOffset)jo["dateTimeOffset"]);
Assert.Same(AnyInstance.AnyJsonArray, jo["JsonArray"]);
Assert.Equal(AnyInstance.AnyJsonPrimitive, jo["JsonPrimitive"]);
Assert.Same(AnyInstance.AnyJsonObject, jo["JsonObject"]);
Assert.Equal(AnyInstance.AnyBool, (bool)dyn.boolean);
Assert.Equal(AnyInstance.AnyShort, (short)dyn.int16);
Assert.Equal(AnyInstance.AnyUShort, (ushort)dyn.uint16);
Assert.Equal(AnyInstance.AnyInt, (int)dyn.int32);
Assert.Equal(AnyInstance.AnyUInt, (uint)dyn.uint32);
Assert.Equal(AnyInstance.AnyLong, (long)dyn.int64);
Assert.Equal(AnyInstance.AnyULong, (ulong)dyn.uint64);
Assert.Equal(AnyInstance.AnySByte, (sbyte)dyn.@sbyte);
Assert.Equal(AnyInstance.AnyByte, (byte)dyn.@byte);
Assert.Equal(AnyInstance.AnyChar, (char)dyn.@char);
Assert.Equal(AnyInstance.AnyDouble, (double)dyn.dbl);
Assert.Equal(AnyInstance.AnyFloat, (float)dyn.flt);
Assert.Equal(AnyInstance.AnyDecimal, (decimal)dyn.dec);
Assert.Equal(AnyInstance.AnyString, (string)dyn.str);
Assert.Equal(AnyInstance.AnyUri, (Uri)dyn.uri);
Assert.Equal(AnyInstance.AnyGuid, (Guid)dyn.guid);
Assert.Equal(AnyInstance.AnyDateTime, (DateTime)dyn.dateTime);
Assert.Equal(AnyInstance.AnyDateTimeOffset, (DateTimeOffset)dyn.dateTimeOffset);
Assert.Same(AnyInstance.AnyJsonArray, dyn.JsonArray);
Assert.Equal(AnyInstance.AnyJsonPrimitive, dyn.JsonPrimitive);
Assert.Same(AnyInstance.AnyJsonObject, dyn.JsonObject);
ExceptionHelper.Throws<ArgumentException>(delegate { dyn.other = Console.Out; });
ExceptionHelper.Throws<ArgumentException>(delegate { dyn.other = dyn.NonExistentProp; });
}
[Fact]
public void NullTests()
{
dynamic dyn = new JsonObject();
JsonObject jo = (JsonObject)dyn;
dyn.@null = null;
Assert.Same(dyn.@null, AnyInstance.DefaultJsonValue);
jo["@null"] = null;
Assert.Null(jo["@null"]);
}
[Fact]
public void DynamicNotationTest()
{
bool boolValue;
JsonValue jsonValue;
Person person = Person.CreateSample();
dynamic jo = JsonValueExtensions.CreateFrom(person);
dynamic target = jo;
Assert.Equal<int>(person.Age, target.Age.ReadAs<int>()); // JsonPrimitive
Assert.Equal<string>(person.Address.ToString(), ((JsonObject)target.Address).ReadAsType<Address>().ToString()); // JsonObject
target = jo.Address.City; // JsonPrimitive
Assert.NotNull(target);
Assert.Equal<string>(target.ReadAs<string>(), person.Address.City);
target = jo.Friends; // JsonArray
Assert.NotNull(target);
jsonValue = target as JsonValue;
Assert.Equal<int>(person.Friends.Count, jsonValue.ReadAsType<List<Person>>().Count);
target = jo.Friends[1].Address.City;
Assert.NotNull(target);
Assert.Equal<string>(target.ReadAs<string>(), person.Address.City);
target = jo.Address.NonExistentProp.NonExistentProp2; // JsonObject (default)
Assert.NotNull(target);
Assert.True(jo is JsonObject);
Assert.False(target.TryReadAs<bool>(out boolValue));
Assert.True(target.TryReadAs<JsonValue>(out jsonValue));
Assert.Same(target, jsonValue);
Assert.Same(jo.Address.NonExistent, AnyInstance.DefaultJsonValue);
Assert.Same(jo.Friends[1000], AnyInstance.DefaultJsonValue);
Assert.Same(jo.Age.NonExistentProp, AnyInstance.DefaultJsonValue);
Assert.Same(jo.Friends.NonExistentProp, AnyInstance.DefaultJsonValue);
}
[Fact]
public void PropertyAccessTest()
{
Person p = AnyInstance.AnyPerson;
JsonObject jo = JsonValueExtensions.CreateFrom(p) as JsonObject;
JsonArray ja = JsonValueExtensions.CreateFrom(p.Friends) as JsonArray;
JsonPrimitive jp = AnyInstance.AnyJsonPrimitive;
JsonValue jv = AnyInstance.DefaultJsonValue;
dynamic jod = jo;
dynamic jad = ja;
dynamic jpd = jp;
dynamic jvd = jv;
Assert.Equal(jo.Count, jod.Count);
Assert.Equal(jo.JsonType, jod.JsonType);
Assert.Equal(jo.Keys.Count, jod.Keys.Count);
Assert.Equal(jo.Values.Count, jod.Values.Count);
Assert.Equal(p.Age, (int)jod.Age);
Assert.Equal(p.Age, (int)jod["Age"]);
Assert.Equal(p.Age, (int)jo["Age"]);
Assert.Equal(p.Address.City, (string)jo["Address"]["City"]);
Assert.Equal(p.Address.City, (string)jod["Address"]["City"]);
Assert.Equal(p.Address.City, (string)jod.Address.City);
Assert.Equal(p.Friends.Count, ja.Count);
Assert.Equal(ja.Count, jad.Count);
Assert.Equal(ja.IsReadOnly, jad.IsReadOnly);
Assert.Equal(ja.JsonType, jad.JsonType);
Assert.Equal(p.Friends[0].Age, (int)ja[0]["Age"]);
Assert.Equal(p.Friends[0].Age, (int)jad[0].Age);
Assert.Equal(jp.JsonType, jpd.JsonType);
}
[Fact]
public void ConcatDynamicAssignmentTest()
{
string value = "MyValue";
dynamic dynArray = JsonValue.Parse(AnyInstance.AnyJsonArray.ToString());
dynamic dynObj = JsonValue.Parse(AnyInstance.AnyJsonObject.ToString());
JsonValue target;
target = dynArray[0] = dynArray[1] = dynArray[2] = value;
Assert.Equal((string)target, value);
Assert.Equal((string)dynArray[0], value);
Assert.Equal((string)dynArray[1], value);
Assert.Equal((string)dynArray[2], value);
target = dynObj["key0"] = dynObj["key1"] = dynObj["key2"] = value;
Assert.Equal((string)target, value);
Assert.Equal((string)dynObj["key0"], value);
Assert.Equal((string)dynObj["key1"], value);
Assert.Equal((string)dynObj["key2"], value);
foreach (KeyValuePair<string, JsonValue> pair in AnyInstance.AnyJsonObject)
{
Assert.Equal<string>(AnyInstance.AnyJsonObject[pair.Key].ToString(), dynObj[pair.Key].ToString());
}
}
[Fact]
public void IndexConversionTest()
{
dynamic target = AnyInstance.AnyJsonArray;
dynamic expected = AnyInstance.AnyJsonArray[0];
dynamic result;
dynamic[] zero_indexes =
{
(short)0,
(ushort)0,
(byte)0,
(sbyte)0,
(char)0,
(int)0
};
result = target[(short)0];
Assert.Same(expected, result);
result = target[(ushort)0];
Assert.Same(expected, result);
result = target[(byte)0];
Assert.Same(expected, result);
result = target[(sbyte)0];
Assert.Same(expected, result);
result = target[(char)0];
Assert.Same(expected, result);
foreach (dynamic zero_index in zero_indexes)
{
result = target[zero_index];
Assert.Same(expected, result);
}
}
[Fact]
public void InvalidIndexTest()
{
object index1 = new object();
bool index2 = true;
Person index3 = AnyInstance.AnyPerson;
JsonObject jo = AnyInstance.AnyJsonObject;
dynamic target;
object ret;
JsonValue[] values = { AnyInstance.AnyJsonObject, AnyInstance.AnyJsonArray };
foreach (JsonValue value in values)
{
target = value;
ExceptionHelper.Throws<ArgumentException>(delegate { ret = target[index1]; }, String.Format(InvalidIndexType, index1.GetType().FullName));
ExceptionHelper.Throws<ArgumentException>(delegate { ret = target[index2]; }, String.Format(InvalidIndexType, index2.GetType().FullName));
ExceptionHelper.Throws<ArgumentException>(delegate { ret = target[index3]; }, String.Format(InvalidIndexType, index3.GetType().FullName));
ExceptionHelper.Throws<ArgumentException>(delegate { ret = target[null]; }, NonSingleNonNullIndexNotSupported);
ExceptionHelper.Throws<ArgumentException>(delegate { ret = target[0, 1]; }, NonSingleNonNullIndexNotSupported);
ExceptionHelper.Throws<ArgumentException>(delegate { ret = target["key1", "key2"]; }, NonSingleNonNullIndexNotSupported);
ExceptionHelper.Throws<ArgumentException>(delegate { ret = target[true]; }, String.Format(InvalidIndexType, true.GetType().FullName));
ExceptionHelper.Throws<ArgumentException>(delegate { target[index1] = jo; }, String.Format(InvalidIndexType, index1.GetType().FullName));
ExceptionHelper.Throws<ArgumentException>(delegate { target[index2] = jo; }, String.Format(InvalidIndexType, index2.GetType().FullName));
ExceptionHelper.Throws<ArgumentException>(delegate { target[index3] = jo; }, String.Format(InvalidIndexType, index3.GetType().FullName));
ExceptionHelper.Throws<ArgumentException>(delegate { target[null] = jo; }, NonSingleNonNullIndexNotSupported);
ExceptionHelper.Throws<ArgumentException>(delegate { target[0, 1] = jo; }, NonSingleNonNullIndexNotSupported);
ExceptionHelper.Throws<ArgumentException>(delegate { target["key1", "key2"] = jo; }, NonSingleNonNullIndexNotSupported);
ExceptionHelper.Throws<ArgumentException>(delegate { target[true] = jo; }, String.Format(InvalidIndexType, true.GetType().FullName));
}
}
[Fact]
public void InvalidCastingTests()
{
dynamic dyn;
string value = "NameValue";
dyn = AnyInstance.AnyJsonPrimitive;
ExceptionHelper.Throws<InvalidOperationException>(delegate { dyn.name = value; });
dyn = AnyInstance.AnyJsonArray;
ExceptionHelper.Throws<InvalidOperationException>(delegate { dyn.name = value; });
dyn = new JsonObject(AnyInstance.AnyJsonObject);
dyn.name = value;
Assert.Equal((string)dyn.name, value);
dyn = AnyInstance.DefaultJsonValue;
ExceptionHelper.Throws<InvalidOperationException>(delegate { dyn.name = value; });
}
[Fact]
public void CastTests()
{
dynamic dyn = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson) as JsonObject;
string city = dyn.Address.City;
Assert.Equal<string>(AnyInstance.AnyPerson.Address.City, dyn.Address.City.ReadAs<string>());
Assert.Equal<string>(AnyInstance.AnyPerson.Address.City, city);
JsonValue[] values =
{
AnyInstance.AnyInt,
AnyInstance.AnyString,
AnyInstance.AnyDateTime,
AnyInstance.AnyJsonObject,
AnyInstance.AnyJsonArray,
AnyInstance.DefaultJsonValue
};
int loopCount = 2;
bool explicitCast = true;
while (loopCount > 0)
{
loopCount--;
foreach (JsonValue jv in values)
{
EvaluateNoExceptions<JsonValue>(null, explicitCast);
EvaluateNoExceptions<JsonValue>(jv, explicitCast);
EvaluateNoExceptions<object>(jv, explicitCast);
EvaluateNoExceptions<IDynamicMetaObjectProvider>(jv, explicitCast);
EvaluateNoExceptions<IEnumerable<KeyValuePair<string, JsonValue>>>(jv, explicitCast);
EvaluateNoExceptions<string>(null, explicitCast);
EvaluateExpectExceptions<int>(null, explicitCast);
EvaluateExpectExceptions<Person>(jv, explicitCast);
EvaluateExpectExceptions<Exception>(jv, explicitCast);
EvaluateIgnoreExceptions<JsonObject>(jv, explicitCast);
EvaluateIgnoreExceptions<int>(jv, explicitCast);
EvaluateIgnoreExceptions<string>(jv, explicitCast);
EvaluateIgnoreExceptions<DateTime>(jv, explicitCast);
EvaluateIgnoreExceptions<JsonArray>(jv, explicitCast);
EvaluateIgnoreExceptions<JsonPrimitive>(jv, explicitCast);
}
explicitCast = false;
}
EvaluateNoExceptions<IDictionary<string, JsonValue>>(AnyInstance.AnyJsonObject, false);
EvaluateNoExceptions<IList<JsonValue>>(AnyInstance.AnyJsonArray, false);
}
static void EvaluateNoExceptions<T>(JsonValue value, bool cast)
{
Evaluate<T>(value, cast, false, true);
}
static void EvaluateExpectExceptions<T>(JsonValue value, bool cast)
{
Evaluate<T>(value, cast, true, true);
}
static void EvaluateIgnoreExceptions<T>(JsonValue value, bool cast)
{
Evaluate<T>(value, cast, true, false);
}
static void Evaluate<T>(JsonValue value, bool cast, bool throwExpected, bool assertExceptions)
{
T ret2;
object obj = null;
bool exceptionThrown = false;
string retstr2, retstr1;
Console.WriteLine("Test info: expected:[{0}], explicitCast type:[{1}]", value, typeof(T));
try
{
if (typeof(int) == typeof(T))
{
obj = ((int)value);
}
else if (typeof(string) == typeof(T))
{
obj = ((string)value);
}
else if (typeof(DateTime) == typeof(T))
{
obj = ((DateTime)value);
}
else if (typeof(IList<JsonValue>) == typeof(T))
{
obj = (IList<JsonValue>)value;
}
else if (typeof(IDictionary<string, JsonValue>) == typeof(T))
{
obj = (IDictionary<string, JsonValue>)value;
}
else if (typeof(JsonValue) == typeof(T))
{
obj = (JsonValue)value;
}
else if (typeof(JsonObject) == typeof(T))
{
obj = (JsonObject)value;
}
else if (typeof(JsonArray) == typeof(T))
{
obj = (JsonArray)value;
}
else if (typeof(JsonPrimitive) == typeof(T))
{
obj = (JsonPrimitive)value;
}
else
{
obj = (T)(object)value;
}
retstr1 = obj == null ? "null" : obj.ToString();
}
catch (Exception ex)
{
exceptionThrown = true;
retstr1 = ex.Message;
}
if (assertExceptions)
{
Assert.Equal<bool>(throwExpected, exceptionThrown);
}
exceptionThrown = false;
try
{
dynamic dyn = value as dynamic;
if (cast)
{
ret2 = (T)dyn;
}
else
{
ret2 = dyn;
}
retstr2 = ret2 != null ? ret2.ToString() : "null";
}
catch (Exception ex)
{
exceptionThrown = true;
retstr2 = ex.Message;
}
if (assertExceptions)
{
Assert.Equal<bool>(throwExpected, exceptionThrown);
}
// fixup string
retstr1 = retstr1.Replace("\'Person\'", String.Format("\'{0}\'", typeof(Person).FullName));
if (retstr1.EndsWith(".")) retstr1 = retstr1.Substring(0, retstr1.Length - 1);
// fixup string
retstr2 = retstr2.Replace("\'string\'", String.Format("\'{0}\'", typeof(string).FullName));
retstr2 = retstr2.Replace("\'int\'", String.Format("\'{0}\'", typeof(int).FullName));
if (retstr2.EndsWith(".")) retstr2 = retstr2.Substring(0, retstr2.Length - 1);
Assert.Equal<string>(retstr1, retstr2);
}
}
}

Просмотреть файл

@ -1,37 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Json
{
public class JsonValueLinqExtensionsTest
{
[Fact]
public void ToJsonArrayTest()
{
var target = (new List<int>(new[] { 1, 2, 3 }).Select(i => (JsonValue)i).ToJsonArray());
Assert.Equal("[1,2,3]", target.ToString());
}
[Fact]
public void ToJsonObjectTest()
{
JsonValue jv = new JsonObject { { "one", 1 }, { "two", 2 }, { "three", 3 } };
var result = from n in jv
where n.Value.ReadAs<int>() > 1
select n;
Assert.Equal("{\"two\":2,\"three\":3}", result.ToJsonObject().ToString());
}
[Fact]
public void ToJsonObjectFromArray()
{
JsonArray ja = new JsonArray("first", "second");
JsonObject jo = ja.ToJsonObject();
Assert.Equal("{\"0\":\"first\",\"1\":\"second\"}", jo.ToString());
}
}
}

Просмотреть файл

@ -1,567 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using Xunit;
namespace System.Json
{
public class JsonValueTest
{
const string IndexerNotSupportedOnJsonType = "'{0}' type indexer is not supported on JsonValue of 'JsonType.{1}' type.";
const string InvalidIndexType = "Invalid '{0}' index type; only 'System.String' and non-negative 'System.Int32' types are supported.\r\nParameter name: indexes";
[Fact]
public void ContainsKeyTest()
{
JsonObject target = new JsonObject { { AnyInstance.AnyString, AnyInstance.AnyString } };
Assert.True(target.ContainsKey(AnyInstance.AnyString));
}
[Fact]
public void LoadTest()
{
string json = "{\"a\":123,\"b\":[false,null,12.34]}";
foreach (bool useLoadTextReader in new bool[] { false, true })
{
JsonValue jv;
if (useLoadTextReader)
{
using (StringReader sr = new StringReader(json))
{
jv = JsonValue.Load(sr);
}
}
else
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
jv = JsonValue.Load(ms);
}
}
Assert.Equal(json, jv.ToString());
}
ExceptionHelper.Throws<ArgumentNullException>(() => JsonValue.Load((Stream)null));
ExceptionHelper.Throws<ArgumentNullException>(() => JsonValue.Load((TextReader)null));
}
[Fact]
public void ParseTest()
{
JsonValue target;
string indentedJson = "{\r\n \"a\": 123,\r\n \"b\": [\r\n false,\r\n null,\r\n 12.34\r\n ],\r\n \"with space\": \"hello\",\r\n \"\": \"empty key\",\r\n \"withTypeHint\": {\r\n \"__type\": \"typeHint\"\r\n }\r\n}";
string plainJson = indentedJson.Replace("\r\n", "").Replace(" ", "").Replace("emptykey", "empty key").Replace("withspace", "with space");
target = JsonValue.Parse(indentedJson);
Assert.Equal(plainJson, target.ToString());
target = JsonValue.Parse(plainJson);
Assert.Equal(plainJson, target.ToString());
ExceptionHelper.Throws<ArgumentNullException>(() => JsonValue.Parse(null));
ExceptionHelper.Throws<ArgumentException>(() => JsonValue.Parse(""));
}
[Fact]
public void ParseNumbersTest()
{
string json = "{\"long\":12345678901234,\"zero\":0.0,\"double\":1.23e+200}";
string expectedJson = "{\"long\":12345678901234,\"zero\":0,\"double\":1.23E+200}";
JsonValue jv = JsonValue.Parse(json);
Assert.Equal(expectedJson, jv.ToString());
Assert.Equal(12345678901234L, (long)jv["long"]);
Assert.Equal<double>(0, jv["zero"].ReadAs<double>());
Assert.Equal<double>(1.23e200, jv["double"].ReadAs<double>());
ExceptionHelper.Throws<ArgumentException>(() => JsonValue.Parse("[1.2e+400]"));
}
[Fact]
public void ReadAsTest()
{
JsonValue target = new JsonPrimitive(AnyInstance.AnyInt);
Assert.Equal(AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture), target.ReadAs(typeof(string)));
Assert.Equal(AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture), target.ReadAs<string>());
object value;
double dblValue;
Assert.True(target.TryReadAs(typeof(double), out value));
Assert.True(target.TryReadAs<double>(out dblValue));
Assert.Equal(Convert.ToDouble(AnyInstance.AnyInt, CultureInfo.InvariantCulture), (double)value);
Assert.Equal(Convert.ToDouble(AnyInstance.AnyInt, CultureInfo.InvariantCulture), dblValue);
Assert.False(target.TryReadAs(typeof(Guid), out value), "TryReadAs should have failed to read a double as a Guid");
Assert.Null(value);
}
[Fact(Skip = "See bug #228569 in CSDMain")]
public void SaveTest()
{
JsonObject jo = new JsonObject
{
{ "first", 1 },
{ "second", 2 },
};
JsonValue jv = new JsonArray(123, null, jo);
string indentedJson = "[\r\n 123,\r\n null,\r\n {\r\n \"first\": 1,\r\n \"second\": 2\r\n }\r\n]";
string plainJson = indentedJson.Replace("\r\n", "").Replace(" ", "");
SaveJsonValue(jv, plainJson, false);
SaveJsonValue(jv, plainJson, true);
JsonValue target = AnyInstance.DefaultJsonValue;
using (MemoryStream ms = new MemoryStream())
{
ExceptionHelper.Throws<InvalidOperationException>(() => target.Save(ms));
}
}
private static void SaveJsonValue(JsonValue jv, string expectedJson, bool useStream)
{
string json;
if (useStream)
{
using (MemoryStream ms = new MemoryStream())
{
jv.Save(ms);
json = Encoding.UTF8.GetString(ms.ToArray());
}
}
else
{
StringBuilder sb = new StringBuilder();
using (TextWriter writer = new StringWriter(sb))
{
jv.Save(writer);
json = sb.ToString();
}
}
Assert.Equal(expectedJson, json);
}
[Fact]
public void GetEnumeratorTest()
{
IEnumerable target = new JsonArray(AnyInstance.AnyGuid);
IEnumerator enumerator = target.GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.Equal(AnyInstance.AnyGuid, (Guid)(JsonValue)enumerator.Current);
Assert.False(enumerator.MoveNext());
target = new JsonObject();
enumerator = target.GetEnumerator();
Assert.False(enumerator.MoveNext());
}
[Fact]
public void IEnumerableTest()
{
JsonValue target = AnyInstance.AnyJsonArray;
// Test IEnumerable<JsonValue> on JsonArray
int count = 0;
foreach (JsonValue value in ((JsonArray)target))
{
Assert.Same(target[count], value);
count++;
}
Assert.Equal<int>(target.Count, count);
// Test IEnumerable<KeyValuePair<string, JsonValue>> on JsonValue
count = 0;
foreach (KeyValuePair<string, JsonValue> pair in target)
{
int index = Int32.Parse(pair.Key);
Assert.Equal(count, index);
Assert.Same(target[index], pair.Value);
count++;
}
Assert.Equal<int>(target.Count, count);
target = AnyInstance.AnyJsonObject;
count = 0;
foreach (KeyValuePair<string, JsonValue> pair in target)
{
count++;
Assert.Same(AnyInstance.AnyJsonObject[pair.Key], pair.Value);
}
Assert.Equal<int>(AnyInstance.AnyJsonObject.Count, count);
}
[Fact]
public void GetJsonPrimitiveEnumeratorTest()
{
JsonValue target = AnyInstance.AnyJsonPrimitive;
IEnumerator<KeyValuePair<string, JsonValue>> enumerator = target.GetEnumerator();
Assert.False(enumerator.MoveNext());
}
[Fact]
public void GetJsonUndefinedEnumeratorTest()
{
JsonValue target = AnyInstance.AnyJsonPrimitive.AsDynamic().IDontExist;
IEnumerator<KeyValuePair<string, JsonValue>> enumerator = target.GetEnumerator();
Assert.False(enumerator.MoveNext());
}
[Fact]
public void ToStringTest()
{
JsonObject jo = new JsonObject
{
{ "first", 1 },
{ "second", 2 },
{ "third", new JsonObject { { "inner_one", 4 }, { "", null }, { "inner_3", "" } } },
{ "fourth", new JsonArray { "Item1", 2, false } },
{ "fifth", null }
};
JsonValue jv = new JsonArray(123, null, jo);
string expectedJson = "[\r\n 123,\r\n null,\r\n {\r\n \"first\": 1,\r\n \"second\": 2,\r\n \"third\": {\r\n \"inner_one\": 4,\r\n \"\": null,\r\n \"inner_3\": \"\"\r\n },\r\n \"fourth\": [\r\n \"Item1\",\r\n 2,\r\n false\r\n ],\r\n \"fifth\": null\r\n }\r\n]";
Assert.Equal<string>(expectedJson.Replace("\r\n", "").Replace(" ", ""), jv.ToString());
}
[Fact]
public void CastTests()
{
int value = 10;
JsonValue target = new JsonPrimitive(value);
int v1 = JsonValue.CastValue<int>(target);
Assert.Equal<int>(value, v1);
v1 = (int)target;
Assert.Equal<int>(value, v1);
long v2 = JsonValue.CastValue<long>(target);
Assert.Equal<long>(value, v2);
v2 = (long)target;
Assert.Equal<long>(value, v2);
string s = JsonValue.CastValue<string>(target);
Assert.Equal<string>(value.ToString(), s);
s = (string)target;
Assert.Equal<string>(value.ToString(), s);
object obj = JsonValue.CastValue<object>(target);
Assert.Equal(target, obj);
obj = (object)target;
Assert.Equal(target, obj);
object nill = JsonValue.CastValue<object>(null);
Assert.Null(nill);
dynamic dyn = target;
JsonValue defaultJv = dyn.IamDefault;
nill = JsonValue.CastValue<string>(defaultJv);
Assert.Null(nill);
nill = (string)defaultJv;
Assert.Null(nill);
obj = JsonValue.CastValue<object>(defaultJv);
Assert.Same(defaultJv, obj);
obj = (object)defaultJv;
Assert.Same(defaultJv, obj);
JsonValue jv = JsonValue.CastValue<JsonValue>(target);
Assert.Equal<JsonValue>(target, jv);
jv = JsonValue.CastValue<JsonValue>(defaultJv);
Assert.Equal<JsonValue>(defaultJv, jv);
jv = JsonValue.CastValue<JsonPrimitive>(target);
Assert.Equal<JsonValue>(target, jv);
ExceptionHelper.Throws<InvalidCastException>(delegate { int i = JsonValue.CastValue<int>(null); });
ExceptionHelper.Throws<InvalidCastException>(delegate { int i = JsonValue.CastValue<int>(defaultJv); });
ExceptionHelper.Throws<InvalidCastException>(delegate { int i = JsonValue.CastValue<char>(target); });
}
[Fact]
public void CastingTests()
{
JsonValue target = new JsonPrimitive(AnyInstance.AnyInt);
Assert.Equal(AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture), (string)target);
Assert.Equal(Convert.ToDouble(AnyInstance.AnyInt, CultureInfo.InvariantCulture), (double)target);
Assert.Equal(AnyInstance.AnyString, (string)(JsonValue)AnyInstance.AnyString);
Assert.Equal(AnyInstance.AnyChar, (char)(JsonValue)AnyInstance.AnyChar);
Assert.Equal(AnyInstance.AnyUri, (Uri)(JsonValue)AnyInstance.AnyUri);
Assert.Equal(AnyInstance.AnyGuid, (Guid)(JsonValue)AnyInstance.AnyGuid);
Assert.Equal(AnyInstance.AnyDateTime, (DateTime)(JsonValue)AnyInstance.AnyDateTime);
Assert.Equal(AnyInstance.AnyDateTimeOffset, (DateTimeOffset)(JsonValue)AnyInstance.AnyDateTimeOffset);
Assert.Equal(AnyInstance.AnyBool, (bool)(JsonValue)AnyInstance.AnyBool);
Assert.Equal(AnyInstance.AnyByte, (byte)(JsonValue)AnyInstance.AnyByte);
Assert.Equal(AnyInstance.AnyShort, (short)(JsonValue)AnyInstance.AnyShort);
Assert.Equal(AnyInstance.AnyInt, (int)(JsonValue)AnyInstance.AnyInt);
Assert.Equal(AnyInstance.AnyLong, (long)(JsonValue)AnyInstance.AnyLong);
Assert.Equal(AnyInstance.AnySByte, (sbyte)(JsonValue)AnyInstance.AnySByte);
Assert.Equal(AnyInstance.AnyUShort, (ushort)(JsonValue)AnyInstance.AnyUShort);
Assert.Equal(AnyInstance.AnyUInt, (uint)(JsonValue)AnyInstance.AnyUInt);
Assert.Equal(AnyInstance.AnyULong, (ulong)(JsonValue)AnyInstance.AnyULong);
Assert.Equal(AnyInstance.AnyDecimal, (decimal)(JsonValue)AnyInstance.AnyDecimal);
Assert.Equal(AnyInstance.AnyFloat, (float)(JsonValue)AnyInstance.AnyFloat);
Assert.Equal(AnyInstance.AnyDouble, (double)(JsonValue)AnyInstance.AnyDouble);
Uri uri = null;
string str = null;
JsonValue jv = uri;
Assert.Null(jv);
uri = (Uri)jv;
Assert.Null(uri);
jv = str;
Assert.Null(jv);
str = (string)jv;
Assert.Null(str);
ExceptionHelper.Throws<InvalidCastException>(delegate { var s = (string)AnyInstance.AnyJsonArray; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var s = (string)AnyInstance.AnyJsonObject; });
}
[Fact]
public void InvalidCastTest()
{
JsonValue nullValue = (JsonValue)null;
JsonValue strValue = new JsonPrimitive(AnyInstance.AnyString);
JsonValue boolValue = new JsonPrimitive(AnyInstance.AnyBool);
JsonValue intValue = new JsonPrimitive(AnyInstance.AnyInt);
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (double)nullValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (double)strValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (double)boolValue; });
Assert.Equal<double>(AnyInstance.AnyInt, (double)intValue);
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (float)nullValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (float)strValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (float)boolValue; });
Assert.Equal<float>(AnyInstance.AnyInt, (float)intValue);
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (decimal)nullValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (decimal)strValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (decimal)boolValue; });
Assert.Equal<decimal>(AnyInstance.AnyInt, (decimal)intValue);
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (long)nullValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (long)strValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (long)boolValue; });
Assert.Equal<long>(AnyInstance.AnyInt, (long)intValue);
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (ulong)nullValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (ulong)strValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (ulong)boolValue; });
Assert.Equal<ulong>(AnyInstance.AnyInt, (ulong)intValue);
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (int)nullValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (int)strValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (int)boolValue; });
Assert.Equal<int>(AnyInstance.AnyInt, (int)intValue);
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (uint)nullValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (uint)strValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (uint)boolValue; });
Assert.Equal<uint>(AnyInstance.AnyInt, (uint)intValue);
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (short)nullValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (short)strValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (short)boolValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (ushort)nullValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (ushort)strValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (ushort)boolValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (sbyte)nullValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (sbyte)strValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (sbyte)boolValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (byte)nullValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (byte)strValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (byte)boolValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (Guid)nullValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (Guid)strValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (Guid)boolValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (Guid)intValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTime)nullValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTime)strValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTime)boolValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTime)intValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (char)nullValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (char)strValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (char)boolValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (char)intValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTimeOffset)nullValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTimeOffset)strValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTimeOffset)boolValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTimeOffset)intValue; });
Assert.Null((Uri)nullValue);
Assert.Equal(((Uri)strValue).ToString(), (string)strValue);
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (Uri)boolValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (Uri)intValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (bool)nullValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (bool)strValue; });
Assert.Equal(AnyInstance.AnyBool, (bool)boolValue);
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (bool)intValue; });
Assert.Equal(null, (string)nullValue);
Assert.Equal(AnyInstance.AnyString, (string)strValue);
Assert.Equal(AnyInstance.AnyBool.ToString().ToLowerInvariant(), ((string)boolValue).ToLowerInvariant());
Assert.Equal(AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture), (string)intValue);
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (int)nullValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (int)strValue; });
ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (int)boolValue; });
Assert.Equal(AnyInstance.AnyInt, (int)intValue);
}
[Fact]
public void CountTest()
{
JsonArray ja = new JsonArray(1, 2);
Assert.Equal(2, ja.Count);
JsonObject jo = new JsonObject
{
{ "key1", 123 },
{ "key2", null },
{ "key3", "hello" },
};
Assert.Equal(3, jo.Count);
}
[Fact]
public void ItemTest()
{
//// Positive tests for Item on JsonArray and JsonObject are on JsonArrayTest and JsonObjectTest, respectively.
JsonValue target;
target = AnyInstance.AnyJsonPrimitive;
ExceptionHelper.Throws<InvalidOperationException>(delegate { var c = target[1]; }, String.Format(IndexerNotSupportedOnJsonType, typeof(int), target.JsonType));
ExceptionHelper.Throws<InvalidOperationException>(delegate { target[0] = 123; }, String.Format(IndexerNotSupportedOnJsonType, typeof(int), target.JsonType));
ExceptionHelper.Throws<InvalidOperationException>(delegate { var c = target["key"]; }, String.Format(IndexerNotSupportedOnJsonType, typeof(string), target.JsonType));
ExceptionHelper.Throws<InvalidOperationException>(delegate { target["here"] = 123; }, String.Format(IndexerNotSupportedOnJsonType, typeof(string), target.JsonType));
target = AnyInstance.AnyJsonObject;
ExceptionHelper.Throws<InvalidOperationException>(delegate { var c = target[0]; }, String.Format(IndexerNotSupportedOnJsonType, typeof(int), target.JsonType));
ExceptionHelper.Throws<InvalidOperationException>(delegate { target[0] = 123; }, String.Format(IndexerNotSupportedOnJsonType, typeof(int), target.JsonType));
target = AnyInstance.AnyJsonArray;
ExceptionHelper.Throws<InvalidOperationException>(delegate { var c = target["key"]; }, String.Format(IndexerNotSupportedOnJsonType, typeof(string), target.JsonType));
ExceptionHelper.Throws<InvalidOperationException>(delegate { target["here"] = 123; }, String.Format(IndexerNotSupportedOnJsonType, typeof(string), target.JsonType));
}
[Fact(Skip = "Re-enable when DCS have been removed -- see CSDMain 234538")]
public void NonSerializableTest()
{
DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(JsonValue));
ExceptionHelper.Throws<NotSupportedException>(() => dcjs.WriteObject(Stream.Null, AnyInstance.DefaultJsonValue));
}
[Fact]
public void DefaultConcatTest()
{
JsonValue jv = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);
dynamic target = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);
Person person = AnyInstance.AnyPerson;
Assert.Equal(person.Address.City, target.Address.City.ReadAs<string>());
Assert.Equal(person.Friends[0].Age, target.Friends[0].Age.ReadAs<int>());
Assert.Equal(target.ValueOrDefault("Address").ValueOrDefault("City"), target.Address.City);
Assert.Equal(target.ValueOrDefault("Address", "City"), target.Address.City);
Assert.Equal(target.ValueOrDefault("Friends").ValueOrDefault(0).ValueOrDefault("Age"), target.Friends[0].Age);
Assert.Equal(target.ValueOrDefault("Friends", 0, "Age"), target.Friends[0].Age);
Assert.Equal(JsonType.Default, AnyInstance.AnyJsonValue1.ValueOrDefault((object[])null).JsonType);
Assert.Equal(JsonType.Default, jv.ValueOrDefault("Friends", null).JsonType);
Assert.Equal(JsonType.Default, AnyInstance.AnyJsonValue1.ValueOrDefault((string)null).JsonType);
Assert.Equal(JsonType.Default, AnyInstance.AnyJsonPrimitive.ValueOrDefault(AnyInstance.AnyString, AnyInstance.AnyShort).JsonType);
Assert.Equal(JsonType.Default, AnyInstance.AnyJsonArray.ValueOrDefault((string)null).JsonType);
Assert.Equal(JsonType.Default, AnyInstance.AnyJsonObject.ValueOrDefault(AnyInstance.AnyString, null).JsonType);
Assert.Equal(JsonType.Default, AnyInstance.AnyJsonArray.ValueOrDefault(-1).JsonType);
Assert.Same(AnyInstance.AnyJsonValue1, AnyInstance.AnyJsonValue1.ValueOrDefault());
Assert.Same(AnyInstance.AnyJsonArray.ValueOrDefault(0), AnyInstance.AnyJsonArray.ValueOrDefault((short)0));
Assert.Same(AnyInstance.AnyJsonArray.ValueOrDefault(0), AnyInstance.AnyJsonArray.ValueOrDefault((ushort)0));
Assert.Same(AnyInstance.AnyJsonArray.ValueOrDefault(0), AnyInstance.AnyJsonArray.ValueOrDefault((byte)0));
Assert.Same(AnyInstance.AnyJsonArray.ValueOrDefault(0), AnyInstance.AnyJsonArray.ValueOrDefault((sbyte)0));
Assert.Same(AnyInstance.AnyJsonArray.ValueOrDefault(0), AnyInstance.AnyJsonArray.ValueOrDefault((char)0));
jv = new JsonObject();
jv[AnyInstance.AnyString] = AnyInstance.AnyJsonArray;
Assert.Same(jv.ValueOrDefault(AnyInstance.AnyString, 0), jv.ValueOrDefault(AnyInstance.AnyString, (short)0));
Assert.Same(jv.ValueOrDefault(AnyInstance.AnyString, 0), jv.ValueOrDefault(AnyInstance.AnyString, (ushort)0));
Assert.Same(jv.ValueOrDefault(AnyInstance.AnyString, 0), jv.ValueOrDefault(AnyInstance.AnyString, (byte)0));
Assert.Same(jv.ValueOrDefault(AnyInstance.AnyString, 0), jv.ValueOrDefault(AnyInstance.AnyString, (sbyte)0));
Assert.Same(jv.ValueOrDefault(AnyInstance.AnyString, 0), jv.ValueOrDefault(AnyInstance.AnyString, (char)0));
jv = AnyInstance.AnyJsonObject;
ExceptionHelper.Throws<ArgumentException>(delegate { var c = jv.ValueOrDefault(AnyInstance.AnyString, AnyInstance.AnyLong); }, String.Format(InvalidIndexType, typeof(long)));
ExceptionHelper.Throws<ArgumentException>(delegate { var c = jv.ValueOrDefault(AnyInstance.AnyString, AnyInstance.AnyUInt); }, String.Format(InvalidIndexType, typeof(uint)));
ExceptionHelper.Throws<ArgumentException>(delegate { var c = jv.ValueOrDefault(AnyInstance.AnyString, AnyInstance.AnyBool); }, String.Format(InvalidIndexType, typeof(bool)));
}
[Fact]
public void DataContractSerializerTest()
{
ValidateSerialization(new JsonPrimitive(DateTime.Now));
ValidateSerialization(new JsonObject { { "a", 1 }, { "b", 2 }, { "c", 3 } });
ValidateSerialization(new JsonArray { "a", "b", "c", 1, 2, 3 });
JsonObject beforeObject = new JsonObject { { "a", 1 }, { "b", 2 }, { "c", 3 } };
JsonObject afterObject1 = (JsonObject)ValidateSerialization(beforeObject);
beforeObject.Add("d", 4);
afterObject1.Add("d", 4);
Assert.Equal(beforeObject.ToString(), afterObject1.ToString());
JsonObject afterObject2 = (JsonObject)ValidateSerialization(beforeObject);
beforeObject.Add("e", 5);
afterObject2.Add("e", 5);
Assert.Equal(beforeObject.ToString(), afterObject2.ToString());
JsonArray beforeArray = new JsonArray { "a", "b", "c" };
JsonArray afterArray1 = (JsonArray)ValidateSerialization(beforeArray);
beforeArray.Add("d");
afterArray1.Add("d");
Assert.Equal(beforeArray.ToString(), afterArray1.ToString());
JsonArray afterArray2 = (JsonArray)ValidateSerialization(beforeArray);
beforeArray.Add("e");
afterArray2.Add("e");
Assert.Equal(beforeArray.ToString(), afterArray2.ToString());
}
private static JsonValue ValidateSerialization(JsonValue beforeSerialization)
{
Assert.NotNull(beforeSerialization);
NetDataContractSerializer serializer = new NetDataContractSerializer();
using (MemoryStream memStream = new MemoryStream())
{
serializer.Serialize(memStream, beforeSerialization);
memStream.Position = 0;
JsonValue afterDeserialization = (JsonValue)serializer.Deserialize(memStream);
Assert.Equal(beforeSerialization.ToString(), afterDeserialization.ToString());
return afterDeserialization;
}
}
}
}

Просмотреть файл

@ -1,39 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("System.Json.Test.Unit")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("System.Json.Test.Unit")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2c4d325c-ef22-46b8-92af-79bea6364683")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Просмотреть файл

@ -1,84 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\tools\WebStack.settings.targets" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{EB09CD33-992B-4A31-AB95-8673BA90F1CD}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>System.Json.Test</RootNamespace>
<AssemblyName>System.Json.Test</AssemblyName>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>$(WebStackRootPath)\bin\Debug\Test\</OutputPath>
<DefineConstants>TRACE;DEBUG</DefineConstants>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>$(WebStackRootPath)\bin\Release\Test\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'CodeCoverage' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>$(WebStackRootPath)\bin\CodeCoverage\Test\</OutputPath>
<DefineConstants>TRACE;DEBUG</DefineConstants>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="System" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.XML" />
<Reference Include="xunit">
<HintPath>..\..\packages\xunit.1.9.0.1566\lib\xunit.dll</HintPath>
</Reference>
<Reference Include="xunit.extensions">
<HintPath>..\..\packages\xunit.extensions.1.9.0.1566\lib\xunit.extensions.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Common\AnyInstance.cs" />
<Compile Include="Common\ExceptionTestHelper.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="JsonArrayTest.cs" />
<Compile Include="JsonDefaultTest.cs" />
<Compile Include="JsonObjectTest.cs" />
<Compile Include="JsonPrimitiveTest.cs" />
<Compile Include="JsonTypeTest.cs" />
<Compile Include="JsonValueDynamicMetaObjectTest.cs" />
<Compile Include="JsonValueDynamicTest.cs" />
<Compile Include="JsonValueLinqExtensionsTest.cs" />
<Compile Include="JsonValueTest.cs" />
<Compile Include="Extensions\JsonValueExtensionsTest.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Microsoft.TestCommon\Microsoft.TestCommon.csproj">
<Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>
<Name>Microsoft.TestCommon</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\System.Json\System.Json.csproj">
<Project>{F0441BE9-BDC0-4629-BE5A-8765FFAA2481}</Project>
<Name>System.Json</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>

Просмотреть файл

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="xunit" version="1.9.0.1566" />
<package id="xunit.extensions" version="1.9.0.1566" />
</packages>

Просмотреть файл

@ -1,7 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Json;
using System.Net.Http.Formatting.Parsers;
using System.Text;
using System.Web.Http;
@ -72,8 +71,6 @@ namespace System.Net.Http.Formatting
}
}
#region Tests
[Theory,
InlineData("abc", "{\"abc\":\"\"}"),
InlineData("%2eabc%2e", "{\".abc.\":\"\"}"),
@ -390,10 +387,6 @@ namespace System.Net.Http.Formatting
}
}
#endregion
#region Helpers
private static string FormUrlEncoding(JToken jsonValue)
{
List<string> results = new List<string>();
@ -510,7 +503,5 @@ namespace System.Net.Http.Formatting
Assert.Equal(expectedResult, result.ToString(Newtonsoft.Json.Formatting.None));
}
}
#endregion
}
}

Просмотреть файл

@ -1,7 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Json;
using System.Text;
using System.Web.Http;
using Microsoft.TestCommon;
@ -13,8 +12,6 @@ namespace System.Net.Http.Formatting
{
public class FormUrlEncodedJsonFromUriQueryTests
{
#region Tests
[Theory,
InlineData("abc", "{\"abc\":\"\"}"),
InlineData("%2eabc%2e", "{\".abc.\":\"\"}"),
@ -315,9 +312,6 @@ namespace System.Net.Http.Formatting
}
}
#endregion
#region Helpers
private static string FormUrlEncoding(JToken jsonValue)
{
List<string> results = new List<string>();
@ -428,7 +422,5 @@ namespace System.Net.Http.Formatting
Assert.NotNull(result);
Assert.Equal(expectedResult, result.ToString(Newtonsoft.Json.Formatting.None));
}
#endregion
}
}

Просмотреть файл

@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Json;
using Microsoft.TestCommon;
using Newtonsoft.Json.Linq;
namespace System.Net.Http.Formatting

Просмотреть файл

@ -84,10 +84,6 @@
<Project>{7AF77741-9158-4D5F-8782-8F21FADF025F}</Project>
<Name>System.Net.Http.Formatting.Test.Unit</Name>
</ProjectReference>
<ProjectReference Include="..\System.Json.Test.Integration\System.Json.Test.Integration.csproj">
<Project>{A7B1264E-BCE5-42A8-8B5E-001A5360B128}</Project>
<Name>System.Json.Test.Integration</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />

Просмотреть файл

@ -277,10 +277,6 @@
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\System.Json\System.Json.csproj">
<Project>{F0441BE9-BDC0-4629-BE5A-8765FFAA2481}</Project>
<Name>System.Json</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\System.Net.Http.Formatting\System.Net.Http.Formatting.csproj">
<Project>{668E9021-CE84-49D9-98FB-DF125A9FCDB0}</Project>
<Name>System.Net.Http.Formatting</Name>