Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,12 @@
// 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);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,203 @@
// 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();
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,331 @@
// 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);
}
}
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,70 @@
// 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());
}
}
}

View File

@ -0,0 +1,188 @@
// 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;
}
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,382 @@
// 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();
}
}
}
}

View File

@ -0,0 +1,435 @@
// 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;
}
}
}
}

View File

@ -0,0 +1,36 @@
// 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")]

View File

@ -0,0 +1,87 @@
<?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>

View File

@ -0,0 +1,5 @@
<?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>