Пример #1
0
        public void CreateFromDynamicWithJsonValueChildrenTest()
        {
            JsonValue target;
            string    level3   = "{\"Name\":\"Level3\",\"Null\":null}";
            string    level2   = "{\"Name\":\"Level2\",\"JsonObject\":" + AnyInstance.AnyJsonObject + ",\"JsonArray\":" + AnyInstance.AnyJsonArray + ",\"Level3\":" + level3 + "}";
            string    level1   = "{\"Name\":\"Level1\",\"JsonPrimitive\":" + AnyInstance.AnyJsonPrimitive + ",\"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.AreEqual <string>(expected, target.ToString());
        }
Пример #2
0
        public void CreateFromDynamicComplextTest()
        {
            JsonValue target;
            Person    person = AnyInstance.AnyPerson;
            dynamic   dyn    = TestDynamicObject.CreatePersonAsDynamic(person);

            dyn.TestProperty = AnyInstance.AnyString;

            target = JsonValueExtensions.CreateFrom(dyn);
            Assert.IsNotNull(target);
            Assert.AreEqual <string>(AnyInstance.AnyString, dyn.TestProperty);
            Person jvPerson = target.ReadAsType <Person>();

            Assert.AreEqual(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.AreEqual <int>(friends.Length, personArr.Length);
            Assert.AreEqual <string>(friends[0].ToString(), personArr[0].ToString());
            Assert.AreEqual <string>(friends[1].ToString(), personArr[1].ToString());
        }
Пример #3
0
        public void CreateFromComplexTypeTest()
        {
            Assert.IsNull(JsonValueExtensions.CreateFrom(null));

            Person anyObject = AnyInstance.AnyPerson;

            JsonObject jv = JsonValueExtensions.CreateFrom(anyObject) as JsonObject;

            Assert.IsNotNull(jv);
            Assert.AreEqual(4, jv.Count);
            foreach (string key in "Name Age Address".Split())
            {
                Assert.IsTrue(jv.ContainsKey(key));
            }

            Assert.AreEqual(AnyInstance.AnyString, (string)jv["Name"]);
            Assert.AreEqual(AnyInstance.AnyInt, (int)jv["Age"]);

            JsonObject nestedObject = jv["Address"] as JsonObject;

            Assert.IsNotNull(nestedObject);
            Assert.AreEqual(3, nestedObject.Count);
            foreach (string key in "Street City State".Split())
            {
                Assert.IsTrue(nestedObject.ContainsKey(key));
            }

            Assert.AreEqual(Address.AnyStreet, (string)nestedObject["Street"]);
            Assert.AreEqual(Address.AnyCity, (string)nestedObject["City"]);
            Assert.AreEqual(Address.AnyState, (string)nestedObject["State"]);
        }
Пример #4
0
        public void GetValueOrDefaultTest()
        {
            bool      boolValue;
            JsonValue target;
            JsonValue jsonValue;

            Person     person = AnyInstance.AnyPerson;
            JsonObject jo     = JsonValueExtensions.CreateFrom(person) as JsonObject;

            Assert.AreEqual <int>(person.Age, jo.ValueOrDefault("Age").ReadAs <int>());                                          // JsonPrimitive
            Assert.AreEqual <string>(person.Address.ToString(), jo.ValueOrDefault("Address").ReadAsType <Address>().ToString()); // JsonObject
            Assert.AreEqual <int>(person.Friends.Count, jo.ValueOrDefault("Friends").Count);                                     // JsonArray

            target = jo.ValueOrDefault("Address").ValueOrDefault("City");                                                        // JsonPrimitive
            Assert.IsNotNull(target);
            Assert.AreEqual <string>(person.Address.City, target.ReadAs <string>());

            target = jo.ValueOrDefault("Address", "City"); // JsonPrimitive
            Assert.IsNotNull(target);
            Assert.AreEqual <string>(person.Address.City, target.ReadAs <string>());

            target = jo.ValueOrDefault("Address").ValueOrDefault("NonExistentProp").ValueOrDefault("NonExistentProp2"); // JsonObject
            Assert.AreEqual(JsonType.Default, target.JsonType);
            Assert.IsNotNull(target);
            Assert.IsFalse(target.TryReadAs <bool>(out boolValue));
            Assert.IsTrue(target.TryReadAs <JsonValue>(out jsonValue));

            target = jo.ValueOrDefault("Address", "NonExistentProp", "NonExistentProp2"); // JsonObject
            Assert.AreEqual(JsonType.Default, target.JsonType);
            Assert.IsNotNull(target);
            Assert.IsFalse(target.TryReadAs <bool>(out boolValue));
            Assert.IsTrue(target.TryReadAs <JsonValue>(out jsonValue));
            Assert.AreSame(target, jsonValue);
        }
Пример #5
0
        public void CreateFromPrimitiveTest()
        {
            object[] values =
            {
                AnyInstance.AnyBool,
                AnyInstance.AnyByte,
                AnyInstance.AnyChar,
                AnyInstance.AnyDateTime,
                AnyInstance.AnyDateTimeOffset,
                AnyInstance.AnyDecimal,
                AnyInstance.AnyDouble,
                AnyInstance.AnyFloat,
                AnyInstance.AnyGuid,
                AnyInstance.AnyLong,
                AnyInstance.AnySByte,
                AnyInstance.AnyShort,
                AnyInstance.AnyUInt,
                AnyInstance.AnyULong,
                AnyInstance.AnyUri,
                AnyInstance.AnyUShort,
                AnyInstance.AnyInt,
                AnyInstance.AnyString,
            };

            foreach (object value in values)
            {
                Type valueType = value.GetType();
                Console.WriteLine("Value: {0}, Type: {1}", value, valueType);
                Assert.AreEqual(value, JsonValueExtensions.CreateFrom(value).ReadAs(valueType), "Test failed on value of type: " + valueType);
            }
        }
Пример #6
0
        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.AreEqual(jo.Count, jod.Count);
            Assert.AreEqual(jo.JsonType, jod.JsonType);
            Assert.AreEqual(jo.Keys.Count, jod.Keys.Count);
            Assert.AreEqual(jo.Values.Count, jod.Values.Count);
            Assert.AreEqual(p.Age, (int)jod.Age);
            Assert.AreEqual(p.Age, (int)jod["Age"]);
            Assert.AreEqual(p.Age, (int)jo["Age"]);
            Assert.AreEqual(p.Address.City, (string)jo["Address"]["City"]);
            Assert.AreEqual(p.Address.City, (string)jod["Address"]["City"]);
            Assert.AreEqual(p.Address.City, (string)jod.Address.City);

            Assert.AreEqual(p.Friends.Count, ja.Count);
            Assert.AreEqual(ja.Count, jad.Count);
            Assert.AreEqual(ja.IsReadOnly, jad.IsReadOnly);
            Assert.AreEqual(ja.JsonType, jad.JsonType);
            Assert.AreEqual(p.Friends[0].Age, (int)ja[0]["Age"]);
            Assert.AreEqual(p.Friends[0].Age, (int)jad[0].Age);

            Assert.AreEqual(jp.JsonType, jpd.JsonType);
        }
Пример #7
0
        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.AreEqual(dt, (DateTime)jvDt1);
            Assert.AreEqual(dt, (DateTime)jvDt2);

            Assert.AreEqual(dto, (DateTimeOffset)jvDto1);
            Assert.AreEqual(dto, (DateTimeOffset)jvDto2);

            Assert.AreEqual(dt, jvDt1.ReadAs <DateTime>());
            Assert.AreEqual(dt, jvDt2.ReadAs <DateTime>());

            Assert.AreEqual(dto, jvDto1.ReadAs <DateTimeOffset>());
            Assert.AreEqual(dto, jvDto2.ReadAs <DateTimeOffset>());

            Assert.AreEqual(jvDt1.ToString(), jvDt2.ToString());
            Assert.AreEqual(jvDto1.ToString(), jvDto2.ToString());
        }
Пример #8
0
        public void CreateFromComplexTest()
        {
            JsonValue target = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);

            Assert.AreEqual(AnyInstance.AnyPerson.Name, (string)target["Name"]);
            Assert.AreEqual(AnyInstance.AnyPerson.Age, (int)target["Age"]);
            Assert.AreEqual(AnyInstance.AnyPerson.Address.City, (string)target.ValueOrDefault("Address", "City"));
        }
Пример #9
0
        public JsonValue Get(string id)
        {
            JsonObject result = JsonValueExtensions.CreateFrom(GetType(id)) as JsonObject;

            result["Self"] = "contacts/" + result["ContactID"];
            result.Remove("ContactID"); // Don't need to return this to the user
            return(result);
        }
Пример #10
0
        public void CastTests()
        {
            dynamic dyn  = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson) as JsonObject;
            string  city = dyn.Address.City;

            Assert.AreEqual <string>(AnyInstance.AnyPerson.Address.City, dyn.Address.City.ReadAs <string>());
            Assert.AreEqual <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);
        }
Пример #11
0
        public JsonValue Delete(string id)
        {
            Contact deleted = GetType(id);

            using (var context = new ContactsDataContext(connectionString))
            {
                context.Contacts.Attach(deleted);
                context.Contacts.DeleteOnSubmit(deleted);
                context.SubmitChanges();
            }

            return(JsonValueExtensions.CreateFrom(deleted));
        }
Пример #12
0
        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.IsNull(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.IsNull(jv);
                        }
                        else
                        {
                            string fromJsonValue = jv.ToString();
                            Assert.AreEqual(fromDCJS, fromJsonValue);
                        }
                    }
                }
            }
            finally
            {
                CreatorSettings.CreatorSurrogate = oldSurrogate;
            }
        }
Пример #13
0
        // 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
        //[TestMethod] 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.IsNotNull(person);
            Assert.AreEqual <string>(AnyInstance.AnyPerson.ToString(), person.ToString());

            success = jv.TryReadAsType <Person>(out person);
            Assert.IsTrue(success);
            Assert.IsNotNull(person);
            Assert.AreEqual <string>(AnyInstance.AnyPerson.ToString(), person.ToString());
        }
Пример #14
0
        public void ReadAsExtensionsOnDynamicTest()
        {
            dynamic jv = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);
            bool    success;
            object  obj;

            success = jv.TryReadAsType(typeof(Person), out obj);
            Assert.IsTrue(success);
            Assert.IsNotNull(obj);
            Assert.AreEqual <string>(AnyInstance.AnyPerson.ToString(), obj.ToString());

            obj = jv.ReadAsType(typeof(Person));
            Assert.IsNotNull(obj);
            Assert.AreEqual <string>(AnyInstance.AnyPerson.ToString(), obj.ToString());
        }
Пример #15
0
        public void CreateFromTypeTest()
        {
            JsonValue[] values =
            {
                AnyInstance.AnyJsonObject,
                AnyInstance.AnyJsonArray,
                AnyInstance.AnyJsonPrimitive,
                AnyInstance.DefaultJsonValue
            };

            foreach (JsonValue value in values)
            {
                Assert.AreSame(value, JsonValueExtensions.CreateFrom(value));
            }
        }
Пример #16
0
        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.IsNotNull(target);
            Assert.AreEqual <string>(expected, target.ToString());
        }
Пример #17
0
        public void DefaultConcatTest()
        {
            JsonValue jv     = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);
            dynamic   target = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);
            Person    person = AnyInstance.AnyPerson;

            Assert.AreEqual(person.Address.City, target.Address.City.ReadAs <string>());
            Assert.AreEqual(person.Friends[0].Age, target.Friends[0].Age.ReadAs <int>());

            Assert.AreEqual(target.ValueOrDefault("Address").ValueOrDefault("City"), target.Address.City);
            Assert.AreEqual(target.ValueOrDefault("Address", "City"), target.Address.City);

            Assert.AreEqual(target.ValueOrDefault("Friends").ValueOrDefault(0).ValueOrDefault("Age"), target.Friends[0].Age);
            Assert.AreEqual(target.ValueOrDefault("Friends", 0, "Age"), target.Friends[0].Age);

            Assert.AreEqual(JsonType.Default, AnyInstance.AnyJsonValue1.ValueOrDefault((object[])null).JsonType);
            Assert.AreEqual(JsonType.Default, jv.ValueOrDefault("Friends", null).JsonType);
            Assert.AreEqual(JsonType.Default, AnyInstance.AnyJsonValue1.ValueOrDefault((string)null).JsonType);
            Assert.AreEqual(JsonType.Default, AnyInstance.AnyJsonPrimitive.ValueOrDefault(AnyInstance.AnyString, AnyInstance.AnyShort).JsonType);
            Assert.AreEqual(JsonType.Default, AnyInstance.AnyJsonArray.ValueOrDefault((string)null).JsonType);
            Assert.AreEqual(JsonType.Default, AnyInstance.AnyJsonObject.ValueOrDefault(AnyInstance.AnyString, null).JsonType);
            Assert.AreEqual(JsonType.Default, AnyInstance.AnyJsonArray.ValueOrDefault(-1).JsonType);

            Assert.AreSame(AnyInstance.AnyJsonValue1, AnyInstance.AnyJsonValue1.ValueOrDefault());

            Assert.AreSame(AnyInstance.AnyJsonArray.ValueOrDefault(0), AnyInstance.AnyJsonArray.ValueOrDefault((short)0));
            Assert.AreSame(AnyInstance.AnyJsonArray.ValueOrDefault(0), AnyInstance.AnyJsonArray.ValueOrDefault((ushort)0));
            Assert.AreSame(AnyInstance.AnyJsonArray.ValueOrDefault(0), AnyInstance.AnyJsonArray.ValueOrDefault((byte)0));
            Assert.AreSame(AnyInstance.AnyJsonArray.ValueOrDefault(0), AnyInstance.AnyJsonArray.ValueOrDefault((sbyte)0));
            Assert.AreSame(AnyInstance.AnyJsonArray.ValueOrDefault(0), AnyInstance.AnyJsonArray.ValueOrDefault((char)0));

            jv = new JsonObject();
            jv[AnyInstance.AnyString] = AnyInstance.AnyJsonArray;

            Assert.AreSame(jv.ValueOrDefault(AnyInstance.AnyString, 0), jv.ValueOrDefault(AnyInstance.AnyString, (short)0));
            Assert.AreSame(jv.ValueOrDefault(AnyInstance.AnyString, 0), jv.ValueOrDefault(AnyInstance.AnyString, (ushort)0));
            Assert.AreSame(jv.ValueOrDefault(AnyInstance.AnyString, 0), jv.ValueOrDefault(AnyInstance.AnyString, (byte)0));
            Assert.AreSame(jv.ValueOrDefault(AnyInstance.AnyString, 0), jv.ValueOrDefault(AnyInstance.AnyString, (sbyte)0));
            Assert.AreSame(jv.ValueOrDefault(AnyInstance.AnyString, 0), jv.ValueOrDefault(AnyInstance.AnyString, (char)0));

            jv = AnyInstance.AnyJsonObject;

            ExceptionTestHelper.ExpectException <ArgumentException>(delegate { var c = jv.ValueOrDefault(AnyInstance.AnyString, AnyInstance.AnyLong); }, string.Format(InvalidIndexType, typeof(long)));
            ExceptionTestHelper.ExpectException <ArgumentException>(delegate { var c = jv.ValueOrDefault(AnyInstance.AnyString, AnyInstance.AnyUInt); }, string.Format(InvalidIndexType, typeof(uint)));
            ExceptionTestHelper.ExpectException <ArgumentException>(delegate { var c = jv.ValueOrDefault(AnyInstance.AnyString, AnyInstance.AnyBool); }, string.Format(InvalidIndexType, typeof(bool)));
        }
Пример #18
0
        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.AreSame(dyn, target);
            }
        }
Пример #19
0
        public void CreateFromDynamicSimpleTest()
        {
            JsonValue target;

            target = JsonValueExtensions.CreateFrom(AnyInstance.AnyDynamic);
            Assert.IsNotNull(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.AreEqual <string>(expected, target.ToString());

            target = JsonValueExtensions.CreateFrom(new TestDynamicObject());
            Assert.AreEqual <string>("{}", target.ToString());
        }
Пример #20
0
        public void DefaultConcatTest()
        {
            JsonValue jv     = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);
            dynamic   target = JsonValueExtensions.CreateFrom(AnyInstance.AnyPerson);
            Person    person = AnyInstance.AnyPerson;

            Assert.AreEqual(JsonType.Default, target.Friends[100000].Name.JsonType);
            Assert.AreEqual(JsonType.Default, target.Friends[0].Age.Minutes.JsonType);

            JsonValue jv1 = target.MissingProperty as JsonValue;

            Assert.IsNotNull(jv1);

            JsonValue jv2 = target.MissingProperty1.MissingProperty2 as JsonValue;

            Assert.IsNotNull(jv2);

            Assert.AreSame(jv1, jv2);
            Assert.AreSame(target.Person.Name.MissingProperty, AnyInstance.DefaultJsonValue);
        }
Пример #21
0
        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.AreEqual(expectedJson, jv.ToString());
        }
Пример #22
0
        /// <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");
        }
Пример #23
0
        public void DynamicNotationTest()
        {
            bool      boolValue;
            JsonValue jsonValue;

            Person  person = Person.CreateSample();
            dynamic jo     = JsonValueExtensions.CreateFrom(person);

            dynamic target = jo;

            Assert.AreEqual <int>(person.Age, target.Age.ReadAs <int>());                                                        // JsonPrimitive
            Assert.AreEqual <string>(person.Address.ToString(), ((JsonObject)target.Address).ReadAsType <Address>().ToString()); // JsonObject

            target = jo.Address.City;                                                                                            // JsonPrimitive
            Assert.IsNotNull(target);
            Assert.AreEqual <string>(target.ReadAs <string>(), person.Address.City);

            target = jo.Friends;  // JsonArray
            Assert.IsNotNull(target);
            jsonValue = target as JsonValue;
            Assert.AreEqual <int>(person.Friends.Count, jsonValue.ReadAsType <List <Person> >().Count);

            target = jo.Friends[1].Address.City;
            Assert.IsNotNull(target);
            Assert.AreEqual <string>(target.ReadAs <string>(), person.Address.City);

            target = jo.Address.NonExistentProp.NonExistentProp2; // JsonObject (default)
            Assert.IsNotNull(target);
            Assert.IsTrue(jo is JsonObject);
            Assert.IsFalse(target.TryReadAs <bool>(out boolValue));
            Assert.IsTrue(target.TryReadAs <JsonValue>(out jsonValue));
            Assert.AreSame(target, jsonValue);

            Assert.AreSame(jo.Address.NonExistent, AnyInstance.DefaultJsonValue);
            Assert.AreSame(jo.Friends[1000], AnyInstance.DefaultJsonValue);
            Assert.AreSame(jo.Age.NonExistentProp, AnyInstance.DefaultJsonValue);
            Assert.AreSame(jo.Friends.NonExistentProp, AnyInstance.DefaultJsonValue);
        }
Пример #24
0
        /// <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");
        }
Пример #25
0
        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");

            ExceptionTestHelper.ExpectException <InvalidOperationException>(() => target = JsonValueExtensions.CreateFrom(dyn), expectedMessage);

            dyn.UseErrorSuggestion = true;
            ExceptionTestHelper.ExpectException <TestDynamicObject.TestDynamicObjectException>(() => target = JsonValueExtensions.CreateFrom(dyn));
        }
Пример #26
0
 public static string Encode(object obj)
 {
     return(JsonValueExtensions.CreateFrom(obj).ToString());
 }