public void SetValueWithInvalidIndex()
 {
     AssertException.Throws<ArgumentException>(() =>
     {
         JConstructor c = new JConstructor();
         c["badvalue"] = new JValue(3);
     }, @"Set JConstructor values with invalid key value: ""badvalue"". Argument position index expected.");
 }
        public void JValueDictionary()
        {
            Dictionary<JToken, int> dic = new Dictionary<JToken, int>(JToken.EqualityComparer);
            JValue v11 = new JValue(1);
            JValue v12 = new JValue(1);

            dic[v11] = 1;
            dic[v12] += 1;
            Assert.AreEqual(2, dic[v11]);
        }
    public void SetValue()
    {
      object key = 0;

      JConstructor c = new JConstructor();
      c.Name = "con";
      c.Add(null);
      c[key] = new JValue(3);

      Assert.AreEqual(3, (int)c[key]);
    }
Beispiel #4
1
    public void ChangeValue()
    {
      JValue v = new JValue(true);
      Assert.AreEqual(true, v.Value);
      Assert.AreEqual(JTokenType.Boolean, v.Type);

      v.Value = "Pie";
      Assert.AreEqual("Pie", v.Value);
      Assert.AreEqual(JTokenType.String, v.Type);

      v.Value = null;
      Assert.AreEqual(null, v.Value);
      Assert.AreEqual(JTokenType.Null, v.Type);

      v.Value = (int?)null;
      Assert.AreEqual(null, v.Value);
      Assert.AreEqual(JTokenType.Null, v.Type);

      v.Value = "Pie";
      Assert.AreEqual("Pie", v.Value);
      Assert.AreEqual(JTokenType.String, v.Type);

#if !(NETFX_CORE || PORTABLE)
      v.Value = DBNull.Value;
      Assert.AreEqual(DBNull.Value, v.Value);
      Assert.AreEqual(JTokenType.Null, v.Type);
#endif

      byte[] data = new byte[0];
      v.Value = data;

      Assert.AreEqual(data, v.Value);
      Assert.AreEqual(JTokenType.Bytes, v.Type);

      v.Value = StringComparison.OrdinalIgnoreCase;
      Assert.AreEqual(StringComparison.OrdinalIgnoreCase, v.Value);
      Assert.AreEqual(JTokenType.Integer, v.Type);

      v.Value = new Uri("http://json.codeplex.com/");
      Assert.AreEqual(new Uri("http://json.codeplex.com/"), v.Value);
      Assert.AreEqual(JTokenType.Uri, v.Type);

      v.Value = TimeSpan.FromDays(1);
      Assert.AreEqual(TimeSpan.FromDays(1), v.Value);
      Assert.AreEqual(JTokenType.TimeSpan, v.Type);

      Guid g = Guid.NewGuid();
      v.Value = g;
      Assert.AreEqual(g, v.Value);
      Assert.AreEqual(JTokenType.Guid, v.Type);
    }
        public void Example()
        {
            #region Usage
            JValue s1 = new JValue("A string");
            JValue s2 = new JValue("A string");
            JValue s3 = new JValue("A STRING");

            Console.WriteLine(JToken.DeepEquals(s1, s2));
            // true

            Console.WriteLine(JToken.DeepEquals(s2, s3));
            // false

            JObject o1 = new JObject
            {
                { "Integer", 12345 },
                { "String", "A string" },
                { "Items", new JArray(1, 2) }
            };

            JObject o2 = new JObject
            {
                { "Integer", 12345 },
                { "String", "A string" },
                { "Items", new JArray(1, 2) }
            };

            Console.WriteLine(JToken.DeepEquals(o1, o2));
            // true

            Console.WriteLine(JToken.DeepEquals(s1, o1["String"]));
            // true
            #endregion
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            Department department = (Department)value;

            JObject o = new JObject();
            o["DepartmentId"] = new JValue(department.DepartmentId.ToString());
            o["Name"] = new JValue(new string(department.Name.Reverse().ToArray()));

            o.WriteTo(writer);
        }
Beispiel #7
0
    public void Contains()
    {
      JValue v = new JValue(1);

      JArray a = new JArray {v};

      Assert.AreEqual(false, a.Contains(new JValue(2)));
      Assert.AreEqual(false, a.Contains(new JValue(1)));
      Assert.AreEqual(false, a.Contains(null));
      Assert.AreEqual(true, a.Contains(v));
    }
    public void GenericCollectionRemove()
    {
      JValue v = new JValue(1);
      JObject o = new JObject();
      o.Add("PropertyNameValue", v);
      Assert.AreEqual(1, o.Children().Count());

      Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1))));
      Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2))));
      Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))));
      Assert.AreEqual(true, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", v)));

      Assert.AreEqual(0, o.Children().Count());
    }
Beispiel #9
0
    public void Manual()
    {
      JArray array = new JArray();
      JValue text = new JValue("Manual text");
      JValue date = new JValue(new DateTime(2000, 5, 23));

      array.Add(text);
      array.Add(date);

      string json = array.ToString();
      // [
      //   "Manual text",
      //   "\/Date(958996800000+1200)\/"
      // ]
    }
Beispiel #10
0
        public void Example()
        {
            #region Usage
            JValue v1 = new JValue("1");
            int i = (int)v1;

            Console.WriteLine(i);
            // 1

            JValue v2 = new JValue(true);
            bool b = (bool)v2;

            Console.WriteLine(b);
            // true

            JValue v3 = new JValue("19.95");
            decimal d = (decimal)v3;

            Console.WriteLine(d);
            // 19.95

            JValue v4 = new JValue(new DateTime(2013, 1, 21));
            string s = (string)v4;

            Console.WriteLine(s);
            // 01/21/2013 00:00:00

            JValue v5 = new JValue("http://www.bing.com");
            Uri u = (Uri)v5;

            Console.WriteLine(u);
            // http://www.bing.com/

            JValue v6 = JValue.CreateNull();
            u = (Uri)v6;

            Console.WriteLine((u != null) ? u.ToString() : "{null}");
            // {null}

            DateTime? dt = (DateTime?)v6;

            Console.WriteLine((dt != null) ? dt.ToString() : "{null}");
            // {null}
            #endregion
        }
        public void Example()
        {
            #region Usage
            JValue s = new JValue("A string value");

            Console.WriteLine(s.Value.GetType().Name);
            // String
            Console.WriteLine(s.Value);
            // A string value

            JValue u = new JValue(new Uri("http://www.google.com/"));

            Console.WriteLine(u.Value.GetType().Name);
            // Uri
            Console.WriteLine(u.Value);
            // http://www.google.com/
            #endregion
        }
        public void Example()
        {
            #region Usage
            JValue v1 = new JValue(true);

            bool b = v1.ToObject<bool>();

            Console.WriteLine(b);
            // true

            int i = v1.ToObject<int>();

            Console.WriteLine(i);
            // 1

            string s = v1.ToObject<string>();

            Console.WriteLine(s);
            // "True"
            #endregion
        }
        public void Example()
        {
            #region Usage
            JValue v1 = new JValue(true);

            bool b = (bool)v1.ToObject(typeof(bool));

            Console.WriteLine(b);
            // true

            int i = (int)v1.ToObject(typeof(int));

            Console.WriteLine(i);
            // 1

            string s = (string)v1.ToObject(typeof(string));

            Console.WriteLine(s);
            // "True"
            #endregion
        }
        public void ToObjectWithDefaultSettings()
        {
            try
            {
                JsonConvert.DefaultSettings = () =>
                {
                    return new JsonSerializerSettings
                    {
                        Converters = { new MetroStringConverter() }
                    };
                };

                JValue v = new JValue(":::STRING:::");
                string s = v.ToObject<string>();

                Assert.Equal("string", s);
            }
            finally
            {
                JsonConvert.DefaultSettings = null;
            }
        }
    public void DictionaryItemShouldSet()
    {
      JObject o = new JObject();
      o["PropertyNameValue"] = new JValue(1);
      Assert.AreEqual(1, o.Children().Count());

      JToken t;
      Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
      Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t));

      o["PropertyNameValue"] = new JValue(2);
      Assert.AreEqual(1, o.Children().Count());

      Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
      Assert.AreEqual(true, JToken.DeepEquals(new JValue(2), t));

      o["PropertyNameValue"] = null;
      Assert.AreEqual(1, o.Children().Count());

      Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
      Assert.AreEqual(true, JToken.DeepEquals(new JValue((object)null), t));
    }
		public string ToJson()
		{
			JObject json = new JObject();

			JObject aps = new JObject();

			if (!this.Alert.IsEmpty)
			{
                if (!string.IsNullOrEmpty(this.Alert.Body)
					&& string.IsNullOrEmpty(this.Alert.LocalizedKey)
					&& string.IsNullOrEmpty(this.Alert.ActionLocalizedKey)
					&& (this.Alert.LocalizedArgs == null || this.Alert.LocalizedArgs.Count <= 0)
					&& string.IsNullOrEmpty(this.Alert.LaunchImage)
                    && !this.HideActionButton)
				{
					aps["alert"] = new JValue(this.Alert.Body);
				}
				else
				{
					JObject jsonAlert = new JObject();

					if (!string.IsNullOrEmpty(this.Alert.LocalizedKey))
						jsonAlert["loc-key"] = new JValue(this.Alert.LocalizedKey);

					if (this.Alert.LocalizedArgs != null && this.Alert.LocalizedArgs.Count > 0)
						jsonAlert["loc-args"] = new JArray(this.Alert.LocalizedArgs.ToArray());

					if (!string.IsNullOrEmpty(this.Alert.Body))
						jsonAlert["body"] = new JValue(this.Alert.Body);

					if (this.HideActionButton)
						jsonAlert["action-loc-key"] = new JValue((string)null);
					else if (!string.IsNullOrEmpty(this.Alert.ActionLocalizedKey))
						jsonAlert["action-loc-key"] = new JValue(this.Alert.ActionLocalizedKey);

                    if (!string.IsNullOrEmpty(this.Alert.LaunchImage))
                        jsonAlert["launch-image"] = new JValue(this.Alert.LaunchImage);

					aps["alert"] = jsonAlert;
				}
			}

			if (this.Badge.HasValue)
				aps["badge"] = new JValue(this.Badge.Value);

			if (!string.IsNullOrEmpty(this.Sound))
				aps["sound"] = new JValue(this.Sound);

            if (this.ContentAvailable.HasValue)
            {
                aps["content-available"] = new JValue(this.ContentAvailable.Value);
                if (string.IsNullOrEmpty(this.Sound))
                {
                    //You need to add an empty string for sound or the payload is not sent
                    aps["sound"] = new JValue("");
                }
            }

			if (!string.IsNullOrEmpty(this.Category))
			{
				// iOS8 Interactive Notifications
				aps["category"] = new JValue(this.Category);
			}

		    if (aps.Count > 0)
				json["aps"] = aps;

			foreach (string key in this.CustomItems.Keys)
			{
				if (this.CustomItems[key].Length == 1)
					json[key] = new JValue(this.CustomItems[key][0]);
				else if (this.CustomItems[key].Length > 1)
					json[key] = new JArray(this.CustomItems[key]);
			}

			string rawString = json.ToString(Newtonsoft.Json.Formatting.None, null);

			StringBuilder encodedString = new StringBuilder();
			foreach (char c in rawString)
			{
				if ((int)c < 32 || (int)c > 127)
					encodedString.Append("\\u" + String.Format("{0:x4}", Convert.ToUInt32(c)));
				else
					encodedString.Append(c);
			}
			return rawString;// encodedString.ToString();
		}
Beispiel #17
0
    public void Startz()
    {
        theName = "Alice";
        print(HomeSceneMenuControl.data.tutorialStage + "fiojewapfjewofjoewaifjoewaifjoewaifjoewaifjio");
        if (HomeSceneMenuControl.data.tutorialStage == 6)
        {
            conditionList = new List <Condition_CodeModifier>();
            conditionList.Add(new Condition_CodeModifier(101, 1001, "HPMT", "내 체력 25% 이상ㅋ", 0, 0f, 0f, 888.8f, 25f, "Condition1", "Up", -1));
        }
        if (HomeSceneMenuControl.data.tutorialStage == 15)
        {
            conditionList.Add(new Condition_CodeModifier(302, 1002, "EnemyLT", "공격 반경 안 적이 0명 이하", 0, 0f, 0f, 888.8f, 0f, "Condition6", "Down", -1));
        }
        if (HomeSceneMenuControl.data.tutorialStage > 15)
        {
            conditionList.Add(new Condition_CodeModifier(101, 1003, "HPMT", "내 체력 20% 이상", 0, 0f, 0f, 888.8f, 20f, "Condition1", "Up", -1));
            conditionList.Add(new Condition_CodeModifier(201, 1004, "DPSMT", "한번에 받는 데미지 5% 이상", 0, 0f, 0f, 888.8f, 5f, "Condition2", "Up", -1));
            conditionList.Add(new Condition_CodeModifier(403, 1005, "OAmoveForward", "타겟에게 전진 중", 0, 0f, 0f, 888.8f, 0f, "Condition1", "On", -1));
        }

        /*  conditionList.Add(new Condition_CodeModifier(101, 1001, "HPMT", "내 체력 50% 이상", 0, 0f, 0f, 888.8f, 50f, "Condition1", "Up"));
         * conditionList.Add(new Condition_CodeModifier(101, 1002, "HPMT", "내 체력 70% 이상", 0, 0f, 0f, 888.8f, 70f, "Condition1", "Up"));
         * conditionList.Add(new Condition_CodeModifier(102, 1004, "HPLT", "내 체력 70% 이하", 0, 0f, 0f, 888.8f, 70f, "Condition1", "Down"));
         * conditionList.Add(new Condition_CodeModifier(102, 1005, "HPLT", "내 체력 50% 이하", 0, 0f, 0f, 888.8f, 50f, "Condition1", "Down"));
         * conditionList.Add(new Condition_CodeModifier(201, 1006, "DPSMT", "한번에 받는 데미지 5% 이상", 0, 0f, 0f, 888.8f, 5f, "Condition2", "Up"));
         * conditionList.Add(new Condition_CodeModifier(202, 1007, "DPSLT", "한번에 받는 데미지 5% 이하", 0, 0f, 0f, 888.8f, 5f, "Condition2", "Down"));
         * conditionList.Add(new Condition_CodeModifier(203, 1008, "isStunned", "내 상태 기절", 0, 0f, 0f, 888.8f, 0f, "Condition3", "On"));
         * conditionList.Add(new Condition_CodeModifier(204, 1009, "BuffedAtk", "공격력 버프 유지 중", 0, 0f, 0f, 888.8f, 0f, "Condition5", "On"));
         * conditionList.Add(new Condition_CodeModifier(205, 1010, "DebuffedDef", "방어력 디버프 유지 중", 0, 0f, 0f, 888.8f, 0f, "Condition4", "On"));
         * conditionList.Add(new Condition_CodeModifier(206, 1011, "BuffedDef", "방어력 버프 유지 중", 0, 0f, 0f, 888.8f, 0f, "Condition4", "On"));
         * conditionList.Add(new Condition_CodeModifier(207, 1012, "DebuffedAtk", "공격력 디버프 유지 중", 0, 0f, 0f, 888.8f, 0f, "Condition5", "On"));
         * conditionList.Add(new Condition_CodeModifier(101, 1013, "HPMT", "내 체력 45% 이상", 0, 0f, 0f, 888.8f, 45f, "Condition1", "Up"));
         * conditionList.Add(new Condition_CodeModifier(102, 1014, "HPLT", "내 체력 85% 이하", 0, 0f, 0f, 888.8f, 85f, "Condition1", "Down"));
         * conditionList.Add(new Condition_CodeModifier(101, 1015, "HPMT", "내 체력 20% 이상", 0, 0f, 0f, 888.8f, 20f, "Condition1", "Up"));
         * conditionList.Add(new Condition_CodeModifier(102, 1016, "HPLT", "내 체력 60% 이하", 0, 0f, 0f, 888.8f, 60f, "Condition1", "Down"));
         * conditionList.Add(new Condition_CodeModifier(301, 1017, "EnemyMT", "공격 반경 안 적이 3명 이상", 0, 0f, 0f, 888.8f, 3f, "Condition6", "Up"));
         * conditionList.Add(new Condition_CodeModifier(302, 1018, "EnemyLT", "공격 반경 안 적이 3명 이하", 0, 0f, 0f, 888.8f, 3f, "Condition6", "Down"));
         * conditionList.Add(new Condition_CodeModifier(301, 1020, "EnemyMT", "공격 반경 안 적이 1명 이상", 0, 0f, 0f, 888.8f, 1f, "Condition6", "Up"));
         * conditionList.Add(new Condition_CodeModifier(401, 1021, "OAuseWeapon", "무기 사용 중", 0, 0f, 0f, 888.8f, 0f, "Condition1", "On"));
         * conditionList.Add(new Condition_CodeModifier(402, 1022, "OAuseHealthPotion", "체력 포션 사용 중", 0, 0f, 0f, 888.8f, 0f, "Condition1", "On"));
         * conditionList.Add(new Condition_CodeModifier(403, 1023, "OAmoveForward", "타겟에게 전진 중", 0, 0f, 0f, 888.8f, 0f, "Condition1", "On"));
         * conditionList.Add(new Condition_CodeModifier(404, 1024, "OAmoveBackward", "타겟에게서 후진 중", 0, 0f, 0f, 888.8f, 0f, "Condition1", "On"));
         * conditionList.Add(new Condition_CodeModifier(405, 1025, "OAmoveLeft", "타겟의 좌측으로 이동 중", 0, 0f, 0f, 888.8f, 0f, "Condition1", "On"));
         * conditionList.Add(new Condition_CodeModifier(406, 1026, "OAmoveRight", "타겟의 우측으로 이동 중", 0, 0f, 0f, 888.8f, 0f, "Condition1", "On"));
         * conditionList.Add(new Condition_CodeModifier(407, 1027, "OAmoveNorth", "맵의 위쪽으로 이동 중", 0, 0f, 0f, 888.8f, 0f, "Condition1", "On"));
         * conditionList.Add(new Condition_CodeModifier(408, 1028, "OAmoveSouth", "맵의 아래쪽으로 이동 중", 0, 0f, 0f, 888.8f, 0f, "Condition1", "On"));
         * conditionList.Add(new Condition_CodeModifier(409, 1029, "OAmoveWest", "맵의 왼쪽으로 이동 중", 0, 0f, 0f, 888.8f, 0f, "Condition1", "On"));
         * conditionList.Add(new Condition_CodeModifier(410, 1030, "OAmoveEast", "맵의 오른쪽으로 이동 중", 0, 0f, 0f, 888.8f, 0f, "Condition1", "On"));
         * conditionList.Add(new Condition_CodeModifier(101, 1031, "HPMT", "내 체력 10% 이상", 0, 0f, 0f, 888.8f, 10f, "Condition1", "Up"));
         * conditionList.Add(new Condition_CodeModifier(102, 1032, "HPLT", "내 체력 40% 이하", 0, 0f, 0f, 888.8f, 40f, "Condition1", "Down"));
         * conditionList.Add(new Condition_CodeModifier(102, 1034, "HPLT", "내 체력 30% 이하", 0, 0f, 0f, 888.8f, 30f, "Condition1", "Down"));
         */

        string jdata = JsonConvert.SerializeObject(conditionList);

        jdata = JValue.Parse(jdata).ToString(Formatting.Indented);
        //byte[] bytes = System.Text.Encoding.UTF8.GetBytes(jdata);
        //string format = System.Convert.ToBase64String(bytes);
        //File.WriteAllText(Application.dataPath + "/Scripts/CodeEditor/ConditionData.json",format);
        File.WriteAllText(Application.dataPath + "/Resources/CodeEditor/" + theName + "/ConditionData.json", jdata); //ID 추가해주기

        if (HomeSceneMenuControl.data.tutorialStage == 6)
        {
            actionList = new List <Action_CodeModifier>();
            actionList.Add(new Action_CodeModifier(1, "useWeapon", "무기 사용", 2, 2, 0f, 0f));
        }
        if (HomeSceneMenuControl.data.tutorialStage == 15)
        {
            actionList.Add(new Action_CodeModifier(2, "useHealthPotion", "체력 포션 사용", 3, 2, 0f, 0f));
            actionList.Add(new Action_CodeModifier(3, "moveForward", "타겟에게 전진", 1, 2, 0f, 0f));
        }

        /*   actionList.Add(new Action_CodeModifier(2, "useHealthPotion", "체력 포션 사용", 3, 2, 0f, 0f));
         * actionList.Add(new Action_CodeModifier(4, "moveBackward", "타겟에게서 후진", 1, 2, 0f, 0f));
         * actionList.Add(new Action_CodeModifier(5, "moveLeft", "타겟의 좌측으로 이동", 1, 2, 0f, 0f));
         * actionList.Add(new Action_CodeModifier(6, "moveRight", "타겟의 우측으로 이동", 1, 2, 0f, 0f));
         * actionList.Add(new Action_CodeModifier(7, "moveNorth", "맵의 위쪽으로 이동", 1, 2, 0f, 0f));
         * actionList.Add(new Action_CodeModifier(8, "moveSouth", "맵의 아래쪽으로 이동", 1, 2, 0f, 0f));
         * actionList.Add(new Action_CodeModifier(9, "moveWest", "맵의 왼쪽으로 이동", 1, 2, 0f, 0f));
         * actionList.Add(new Action_CodeModifier(10, "moveEast", "맵의 오른쪽으로 이동", 1, 2, 0f, 0f));
         */
        jdata = JsonConvert.SerializeObject(actionList);
        //bytes = System.Text.Encoding.UTF8.GetBytes(jdata);
        //format = System.Convert.ToBase64String(bytes);
        //File.WriteAllText(Application.dataPath + "/Scripts/CodeEditor/ActionData.json",format);
        File.WriteAllText(Application.dataPath + "/Resources/CodeEditor/" + theName + "/ActionData.json", jdata); //ID 추가해주기
        AssetDatabase.Refresh();
    }
        private void ValidateInteger(JsonSchemaModel schema)
        {
            if (schema == null)
            {
                return;
            }

            if (!TestType(schema, JsonSchemaType.Integer))
            {
                return;
            }

            ValidateNotDisallowed(schema);

            object value = _reader.Value;

            if (schema.Maximum != null)
            {
                if (JValue.Compare(JTokenType.Integer, value, schema.Maximum) > 0)
                {
                    RaiseError("Integer {0} exceeds maximum value of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.Maximum), schema);
                }
                if (schema.ExclusiveMaximum && JValue.Compare(JTokenType.Integer, value, schema.Maximum) == 0)
                {
                    RaiseError("Integer {0} equals maximum value of {1} and exclusive maximum is true.".FormatWith(CultureInfo.InvariantCulture, value, schema.Maximum), schema);
                }
            }

            if (schema.Minimum != null)
            {
                if (JValue.Compare(JTokenType.Integer, value, schema.Minimum) < 0)
                {
                    RaiseError("Integer {0} is less than minimum value of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.Minimum), schema);
                }
                if (schema.ExclusiveMinimum && JValue.Compare(JTokenType.Integer, value, schema.Minimum) == 0)
                {
                    RaiseError("Integer {0} equals minimum value of {1} and exclusive minimum is true.".FormatWith(CultureInfo.InvariantCulture, value, schema.Minimum), schema);
                }
            }

            if (schema.DivisibleBy != null)
            {
                bool notDivisible;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
//                if (value is BigInteger)
//                {
//                    // not that this will lose any decimal point on DivisibleBy
//                    // so manually raise an error if DivisibleBy is not an integer and value is not zero
//                    BigInteger i = (BigInteger)value;
//                    bool divisibleNonInteger = !Math.Abs(schema.DivisibleBy.Value - Math.Truncate(schema.DivisibleBy.Value)).Equals(0);
//                    if (divisibleNonInteger)
//                    {
//                        notDivisible = i != 0;
//                    }
//                    else
//                    {
//                        notDivisible = i % new BigInteger(schema.DivisibleBy.Value) != 0;
//                    }
//                }
//                else
#endif
                {
                    notDivisible = !IsZero(Convert.ToInt64(value, CultureInfo.InvariantCulture) % schema.DivisibleBy.GetValueOrDefault());
                }

                if (notDivisible)
                {
                    RaiseError("Integer {0} is not evenly divisible by {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.DivisibleBy), schema);
                }
            }
        }
Beispiel #19
0
    public void Item()
    {
      JValue v1 = new JValue(1);
      JValue v2 = new JValue(2);
      JValue v3 = new JValue(3);
      JValue v4 = new JValue(4);

      JArray j = new JArray();

      j.Add(v1);
      j.Add(v2);
      j.Add(v3);

      j[1] = v4;

      Assert.AreEqual(null, v2.Parent);
      Assert.AreEqual(-1, j.IndexOf(v2));
      Assert.AreEqual(j, v4.Parent);
      Assert.AreEqual(1, j.IndexOf(v4));
    }
Beispiel #20
0
 public void MapRowsToHits_WithNullTimespan_ReturnsHitsWithNull()
 {
     using var hitsTable = HitTypeTestTable(Type.GetType("System.TimeSpan"), DBNull.Value);
     MapHitTypeAndAssert(hitsTable, defaultQuery, JValue.CreateNull());
 }
Beispiel #21
0
 private static JToken WriteFrameworkName(NuGetFramework item)
 {
     return(item != null ? new JValue(item.ToString()) : JValue.CreateNull());
 }
Beispiel #22
0
        private static void areSame(string filename, JToken expected, JToken actual, List <string> errors)
        {
            if ((expected.Type == JTokenType.Integer && actual.Type == JTokenType.Float) ||
                (expected.Type == JTokenType.Float && actual.Type == JTokenType.Integer))
            {
                JValue leftVal  = (JValue)expected;
                JValue rightVal = (JValue)actual;

                if (leftVal.ToString() != rightVal.ToString())
                {
                    errors.Add(String.Format("Error comparing values in: {0}:{1}, {2} - {3}",
                                             filename, expected.Path, leftVal.ToString(), rightVal.ToString()));
                }
                // Assert.AreEqual(leftVal.ToString(), rightVal.ToString());
                // Bug in json.net, will sometimes convert to integer instead of float
                return;
            }

            if (expected.Type != actual.Type)
            {
                throw new AssertFailedException("Token type is not the same at " + actual.Path);
            }

            if (expected.Type == JTokenType.Array)
            {
                var la = (JArray)expected;
                var ra = (JArray)actual;

                if (la.Count != ra.Count)
                {
                    throw new AssertFailedException("Array size is not the same at " + actual.Path);
                }

                for (var i = 0; i < la.Count; i++)
                {
                    areSame(filename, la[i], ra[i], errors);
                }
            }

            else if (expected.Type == JTokenType.Object)
            {
                var lo = (JObject)expected;
                var ro = (JObject)actual;

                foreach (var lMember in lo)
                {
                    JToken rMember;

                    // Hack, some examples have empty arrays or objects, these are illegal and will result in missing members after round-tripiing
                    if (lMember.Value is JArray && ((JArray)lMember.Value).Count == 0)
                    {
                        continue;
                    }
                    if (lMember.Value is JObject && ((JObject)lMember.Value).Count == 0)
                    {
                        continue;
                    }

                    if (!ro.TryGetValue(lMember.Key, out rMember) || rMember == null)
                    {
                        throw new AssertFailedException(String.Format("Expected member '{0}' not found in actual at " + expected.Path, lMember.Key));
                    }

                    areSame(filename, lMember.Value, rMember, errors);
                }

                foreach (var rMember in ro)
                {
                    JToken lMember;

                    if (!lo.TryGetValue(rMember.Key, out lMember))
                    {
                        throw new AssertFailedException(String.Format("Actual has unexpected extra member {0} at " + actual.Path, rMember.Key));
                    }
                }
            }

            else if (expected.Type == JTokenType.String)
            {
                var lValue = expected.ToString();
                var rValue = actual.ToString();

                if (lValue.TrimStart().StartsWith("<div"))
                {
                    // Don't check the narrative, namespaces are not correctly generated in DSTU2
                    //var leftDoc = SerializationUtil.XDocumentFromXmlText(lValue);
                    //var rightDoc = SerializationUtil.XDocumentFromXmlText(rValue);

                    //XmlAssert.AreSame(filename, leftDoc, rightDoc);
                }
                else
                {
                    XmlAssert.AssertAreTheSame(expected.Path, lValue, rValue);
                }
            }

            else
            {
                if (!JToken.DeepEquals(expected, actual))
                {
                    throw new AssertFailedException(String.Format("Values not the same at " + expected.Path));
                }
            }
        }
        public override void Migrate()
        {
            var sqlDataTypes = Sql()
                               .Select <DataTypeDto>()
                               .From <DataTypeDto>()
                               .Where <DataTypeDto>(x => x.EditorAlias == Constants.PropertyEditors.Aliases.ContentPicker ||
                                                    x.EditorAlias == Constants.PropertyEditors.Aliases.MediaPicker ||
                                                    x.EditorAlias == Constants.PropertyEditors.Aliases.MultiNodeTreePicker);

            var dataTypes = Database.Fetch <DataTypeDto>(sqlDataTypes).ToList();

            foreach (var datatype in dataTypes.Where(x => !x.Configuration.IsNullOrWhiteSpace()))
            {
                switch (datatype.EditorAlias)
                {
                case Constants.PropertyEditors.Aliases.ContentPicker:
                case Constants.PropertyEditors.Aliases.MediaPicker:
                {
                    var config      = JsonConvert.DeserializeObject <JObject>(datatype.Configuration);
                    var startNodeId = config.Value <string>("startNodeId");
                    if (!startNodeId.IsNullOrWhiteSpace() && int.TryParse(startNodeId, out var intStartNode))
                    {
                        var guid = intStartNode <= 0
                                    ? null
                                    : Context.Database.ExecuteScalar <Guid?>(
                            Sql().Select <NodeDto>(x => x.UniqueId).From <NodeDto>().Where <NodeDto>(x => x.NodeId == intStartNode));
                        if (guid.HasValue)
                        {
                            var udi = new GuidUdi(datatype.EditorAlias == Constants.PropertyEditors.Aliases.MediaPicker
                                        ? Constants.UdiEntityType.Media
                                        : Constants.UdiEntityType.Document, guid.Value);
                            config["startNodeId"] = new JValue(udi.ToString());
                        }
                        else
                        {
                            config.Remove("startNodeId");
                        }

                        datatype.Configuration = JsonConvert.SerializeObject(config);
                        Database.Update(datatype);
                    }

                    break;
                }

                case Constants.PropertyEditors.Aliases.MultiNodeTreePicker:
                {
                    var config          = JsonConvert.DeserializeObject <JObject>(datatype.Configuration);
                    var startNodeConfig = config.Value <JObject>("startNode");
                    if (startNodeConfig != null)
                    {
                        var startNodeId = startNodeConfig.Value <string>("id");
                        var objectType  = startNodeConfig.Value <string>("type");
                        if (!objectType.IsNullOrWhiteSpace() &&
                            !startNodeId.IsNullOrWhiteSpace() &&
                            int.TryParse(startNodeId, out var intStartNode))
                        {
                            var guid = intStartNode <= 0
                                        ? null
                                        : Context.Database.ExecuteScalar <Guid?>(
                                Sql().Select <NodeDto>(x => x.UniqueId).From <NodeDto>().Where <NodeDto>(x => x.NodeId == intStartNode));

                            string entityType = null;
                            switch (objectType.ToLowerInvariant())
                            {
                            case "content":
                                entityType = Constants.UdiEntityType.Document;
                                break;

                            case "media":
                                entityType = Constants.UdiEntityType.Media;
                                break;

                            case "member":
                                entityType = Constants.UdiEntityType.Member;
                                break;
                            }

                            if (entityType != null && guid.HasValue)
                            {
                                var udi = new GuidUdi(entityType, guid.Value);
                                startNodeConfig["id"] = new JValue(udi.ToString());
                            }
                            else
                            {
                                startNodeConfig.Remove("id");
                            }

                            datatype.Configuration = JsonConvert.SerializeObject(config);
                            Database.Update(datatype);
                        }
                    }

                    break;
                }
                }
            }
        }
Beispiel #24
0
 public static bool Contains(JValue main, JValue sub)
 {
     return(main.Equals(sub));
 }
Beispiel #25
0
        public NativeJsonFile Do(string Base64File, Dictionary <string, object> FileData)
        {
            var          Base64EncodedBytes = System.Convert.FromBase64String(Base64File);
            MemoryStream SourceFile         = new MemoryStream(Base64EncodedBytes);
            object       Delimiter          = null;

            FileData.TryGetValue("Delimiter", out Delimiter);
            if (Delimiter == null)
            {
                throw new Exception(ServicesConstants.DelimiterMissing);
            }
            object HasTitleInDefinition = null;

            FileData.TryGetValue("HasTitle", out HasTitleInDefinition);
            bool   HasTitle          = HasTitleInDefinition != null && Convert.ToBoolean(HasTitleInDefinition.ToString());
            string JsonFileConverted = "";

            string []      Columns     = null;
            int            Step        = 0;
            List <JObject> JObjectList = new List <JObject>();

            using (StreamReader StreamReader = new StreamReader(SourceFile))
            {
                String ActualLine = "";
                while ((ActualLine = StreamReader.ReadLine()) != null)
                {
                    string[] DataInLine      = ActualLine.Split(Delimiter.ToString());
                    int      ColumnsQuantity = DataInLine.Length;
                    Step++;
                    if (Step == 1)
                    {
                        if (HasTitle)
                        {
                            Columns = DataInLine;
                        }
                        else
                        {
                            Columns = new string[ColumnsQuantity];
                            for (int i = 0; i < ColumnsQuantity; i++)
                            {
                                Columns[i] = "Column-" + i.ToString();
                            }
                        }
                    }
                    dynamic JObjectLine = new JObject();
                    if (Step > 1 || !HasTitle)
                    {
                        int i = 0;
                        foreach (string Data in DataInLine)
                        {
                            JObjectLine[Columns[i]] = new JValue(TypeFunction.GetTyped(Data));;
                            i++;
                        }
                        JObjectList.Add(JObjectLine);
                    }
                }
            }
            var            JSonFileConverted = Newtonsoft.Json.JsonConvert.SerializeObject(JObjectList);
            NativeJsonFile NativeJsonFile    = new NativeJsonFile();

            NativeJsonFile.Content = JSonFileConverted;
            NativeJsonFile.Columns = Columns;
            return(NativeJsonFile);
        }
Beispiel #26
0
        private void EscapedPathAssert(string propertyName, string expectedPath)
        {
            int v1 = int.MaxValue;
            JValue value = new JValue(v1);

            JObject o = new JObject(new JProperty(propertyName, value));

            Assert.AreEqual(expectedPath, value.Path);

            JValue selectedValue = (JValue)o.SelectToken(value.Path);

            Assert.AreEqual(value, selectedValue);
        }
    public void DoubleDeepEquals()
    {
      JArray a =
        new JArray(
          double.NaN,
          double.PositiveInfinity,
          double.NegativeInfinity
        );

      JArray a2 = (JArray)a.DeepClone();

      Assert.IsTrue(a.DeepEquals(a2));

      double d = 1 + 0.1 + 0.1 + 0.1;

      JValue v1 = new JValue(d);
      JValue v2 = new JValue(1.3);

      Assert.IsTrue(v1.DeepEquals(v2));
    }
        public void IntegerLessThanMaximumValue_BigInteger()
        {
            string schemaJson = @"{
  ""type"":""integer"",
  ""minimum"":5
}";

            JValue v = new JValue(new BigInteger(1));

            Json.Schema.ValidationEventArgs validationEventArgs = null;

            v.Validate(JsonSchema.Parse(schemaJson), (sender, args) => { validationEventArgs = args; });

            Assert.NotNull(validationEventArgs);
            Assert.Equal("Integer 1 is less than minimum value of 5.", validationEventArgs.Message);
            Assert.Equal("", validationEventArgs.Path);
        }
Beispiel #29
0
    internal void AddValue(JValue value, JsonToken token)
    {
      if (_parent != null)
      {
        _parent.Add(value);

        if (_parent.Type == JTokenType.Property)
          _parent = _parent.Parent;
      }
      else
      {
        _value = value ?? new JValue((object)null);
      }
    }
Beispiel #30
0
        public T GetData <T>(string obj)
        {
            JValue o = (JValue)obj;

            return((o).ToObject <T>());
        }
Beispiel #31
0
 public void ConvertsToString_Null()
 {
     Assert.AreEqual(string.Empty, Convert.ToString(JValue.CreateNull()));
 }
Beispiel #32
0
 public void SetData <T>(string name, T data)
 {
     this._data[name] = JValue.FromObject(data);
 }
Beispiel #33
0
    public void SetValue()
    {
      object key = 0;

      JArray a = new JArray((object) null);
      a[key] = new JValue(3);

      Assert.AreEqual(3, (int) a[key]);
    }
        private async void sendMessageToDeviceButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (checkBox1.Checked)
                {
                    if (string.IsNullOrEmpty(textBoxMessage.Text))
                    {
                        cloudToDeviceMessage = DateTime.Now.ToLocalTime().ToString();
                    }
                    else
                    {
                        if (isInJsonFormat(textBoxMessage.Text)) //any JSON format string should start with "{" || "[" and end with "}" || "]"
                        {
                            JValue date = new JValue(DateTime.Now.ToLocalTime());
                            JToken t    = JToken.Parse(textBoxMessage.Text);
                            if (t.Type.Equals(JTokenType.Object)) //JSON string is of type Object
                            {
                                JObject o = (JObject)t;
                                o.Add("timestamp", date);
                                cloudToDeviceMessage = o.ToString();
                            }
                            else if (t.Type.Equals(JTokenType.Array)) //JSON string is of type Array
                            {
                                JObject o = new JObject();
                                o.Add("message", (JArray)t);
                                o.Add("timestamp", date);
                                cloudToDeviceMessage = o.ToString();
                            }
                        }
                        else
                        {
                            cloudToDeviceMessage = DateTime.Now.ToLocalTime() + " - " + textBoxMessage.Text;
                        }
                    }
                }
                else
                {
                    isInJsonFormat(textBoxMessage.Text); //any JSON format string should start with "{" || "[" and end with "}" || "]"
                    cloudToDeviceMessage = textBoxMessage.Text;
                }

                ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(activeIoTHubConnectionString);

                var serviceMessage = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(cloudToDeviceMessage));
                serviceMessage.Ack       = DeliveryAcknowledgement.Full;
                serviceMessage.MessageId = Guid.NewGuid().ToString();

                for (var i = 0; i < messagePropertiesGrid.Rows.Count - 1; i++)
                {
                    var row = messagePropertiesGrid.Rows[i];
                    if (row.Cells[0].Value == null && row.Cells[1].Value == null)
                    {
                        continue;
                    }

                    if (row.Cells[0].Value == null || row.Cells[1].Value == null)
                    {
                        throw new InvalidOperationException("Properties have null key or value.");
                    }

                    serviceMessage.Properties.Add(row.Cells[0].Value?.ToString() ?? string.Empty, row.Cells[1].Value?.ToString() ?? string.Empty);
                }


                if (messageSysPropMessageId.Cells[1].Value != null)
                {
                    serviceMessage.MessageId = (string)messageSysPropMessageId.Cells[1].Value;
                }

                if (messageSysPropCorrelationId.Cells[1].Value != null)
                {
                    serviceMessage.CorrelationId = (string)messageSysPropCorrelationId.Cells[1].Value;
                }

                if (messageSysPropContentType.Cells[1].Value != null)
                {
                    serviceMessage.ContentType = (string)messageSysPropContentType.Cells[1].Value;
                }

                if (messageSysPropContentEncoding.Cells[1].Value != null)
                {
                    serviceMessage.ContentEncoding = (string)messageSysPropContentEncoding.Cells[1].Value;
                }

                await serviceClient.SendAsync(deviceIDsComboBoxForCloudToDeviceMessage.SelectedItem.ToString(), serviceMessage);

                messagesTextBox.Text += $"Sent to Device ID: [{deviceIDsComboBoxForCloudToDeviceMessage.SelectedItem.ToString()}], Message:\"{cloudToDeviceMessage}\", message Id: {serviceMessage.MessageId}\n";
                messagesTextBox.Focus();

                await serviceClient.CloseAsync();
            }
            catch (Exception ex)
            {
                using (new CenterDialog(this))
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Beispiel #35
0
        public int PrintCoinStatus()
        {
            FileStream fs = null;

            byte[] buffer /* = new byte[MAX_BUFFER]*/;
            int    size_write = 0;

            string str = url + coin_str;

            try
            {
                path = DateTime.Now.ToString("yyyyMMdd") + coin_str + ".txt";
                // 경로에 파일 쓰기.
                fs = new FileStream(path, FileMode.Append);

                //string Text = httpWebGET(str, str);
                string  text = fetch(str);
                JObject jobj = JObject.Parse(text);
                jobj.Add("time", DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss"));
                buffer     = Encoding.UTF8.GetBytes(jobj.ToString() + ",\r\n");
                size_write = buffer.Length;
                fs.Write(buffer, 0, size_write);
                Console.Write("[" + coin_str + "] ");
                Console.Write("closing_price = " + jobj["data"]["closing_price"]);
                Console.Write(", min_price = " + jobj["data"]["min_price"]);
                Console.WriteLine(", max_price = " + jobj["data"]["max_price"]);
                //Console.WriteLine(jobj.ToString());
                Console.WriteLine("aver_rate(" + cnt + ") : " + aver_rate);
                Console.WriteLine("cur_rate");
                list_rate.ForEach((rate) => { Console.Write(rate + " "); });
                Console.WriteLine("\n");
                //Console.WriteLine(err);
                JValue jval = jobj["data"]["closing_price"] as JValue;
                cur_closing_price = Double.Parse(jval.ToString());

                //Console.WriteLine(cash + ", " + coin_cnt * cur_closing_price + ", " + cash + coin_cnt * cur_closing_price);
                //if(jval != null && cur_closing_price > (double)17500)
                //{
                //	System.Windows.Forms.MessageBox.Show(
                //		new Form() { WindowState = FormWindowState.Maximized, TopMost = true },
                //		jval.ToString()
                //	);
                //}
                //if(jval != null && cur_closing_price < (double)1950)
                //{
                //	System.Windows.Forms.MessageBox.Show(
                //		new Form() { WindowState = FormWindowState.Maximized, TopMost = true },
                //		jval.ToString()
                //	);
                //}
                cnt_interval++;
                if (cnt_interval > interval)
                {
                    if (prev_closing_price != 0)
                    {
                        cur_rate = (cur_closing_price - prev_closing_price);
                        list_rate.Add(cur_rate);
                        if (list_rate.Count > MAX_LIST)
                        {
                            list_rate.RemoveAt(0);
                        }

                        if (cur_rate < 0)
                        {
                            cur_rate = -cur_rate;
                        }

                        aver_rate = aver_rate * cnt + cur_rate;
                        cnt++;
                        aver_rate /= cnt;

                        if (aver_rate * 5 < cur_rate)
                        {
                            System.Windows.Forms.MessageBox.Show(
                                new Form()
                            {
                                WindowState = FormWindowState.Maximized, TopMost = true
                            },
                                cur_rate + ", " + jval.ToString()
                                );
                        }
                    }

                    prev_closing_price = cur_closing_price;
                    cnt_interval       = 0;
                }
                fs.Close();
            }
            catch (Exception e)
            {
                if (fs != null)
                {
                    fs.Close();
                }
                Console.WriteLine(e.Message);
                err += "[" + DateTime.Now.ToString("yyyyMMdd") + "] : [ERROR] " + e.Message + "\n";
            }
            return(0);
        }
 /// <summary>
 /// Sets the paddings of the shadow node.
 /// </summary>
 /// <param name="index">The spacing type index.</param>
 /// <param name="padding">The padding value.</param>
 public override void SetPaddings(int index, JValue padding)
 {
     MarkUpdated();
     base.SetPaddings(index, padding);
 }
Beispiel #37
0
 public void MapRowsToHits_WithNullDateTime_ReturnsHitsWithNull()
 {
     using DataTable hitsTable = HitTypeTestTable(Type.GetType("System.DateTime"), DBNull.Value);
     MapHitTypeAndAssert(hitsTable, defaultQuery, JValue.CreateNull());
 }
Beispiel #38
0
        public void JValueEquals()
        {
            JObject o = new JObject(
                new JProperty("Null", JValue.CreateNull()),
                new JProperty("Integer", new JValue(1)),
                new JProperty("Float", new JValue(1.1d)),
                new JProperty("Decimal", new JValue(1.1m)),
                new JProperty("DateTime", new JValue(new DateTime(2000, 12, 29, 23, 51, 10, DateTimeKind.Utc))),
                new JProperty("Boolean", new JValue(true)),
                new JProperty("String", new JValue("A string lol!")),
                new JProperty("Bytes", new JValue(Encoding.UTF8.GetBytes("A string lol!"))),
                new JProperty("Uri", new Uri("http://json.codeplex.com/")),
                new JProperty("Guid", new Guid("EA27FE1D-0D80-44F2-BF34-4654156FA7AF")),
                new JProperty("TimeSpan", TimeSpan.FromDays(1))
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
                , new JProperty("BigInteger", BigInteger.Parse("1"))
#endif
                );

            dynamic d = o;

            Assert.IsTrue(d.Null == d.Null);
            Assert.IsTrue(d.Null == null);
            Assert.IsTrue(d.Null == JValue.CreateNull());
            Assert.IsFalse(d.Null == 1);

            Assert.IsTrue(d.Integer == d.Integer);
            Assert.IsTrue(d.Integer > 0);
            Assert.IsTrue(d.Integer > 0.0m);
            Assert.IsTrue(d.Integer > 0.0f);
            Assert.IsTrue(d.Integer > null);
            Assert.IsTrue(d.Integer >= null);
            Assert.IsTrue(d.Integer == 1);
            Assert.IsTrue(d.Integer == 1m);
            Assert.IsTrue(d.Integer != 1.1f);
            Assert.IsTrue(d.Integer != 1.1d);

            Assert.IsTrue(d.Decimal == d.Decimal);
            Assert.IsTrue(d.Decimal > 0);
            Assert.IsTrue(d.Decimal > 0.0m);
            Assert.IsTrue(d.Decimal > 0.0f);
            Assert.IsTrue(d.Decimal > null);
            Assert.IsTrue(d.Decimal >= null);
            Assert.IsTrue(d.Decimal == 1.1);
            Assert.IsTrue(d.Decimal == 1.1m);
            Assert.IsTrue(d.Decimal != 1.0f);
            Assert.IsTrue(d.Decimal != 1.0d);
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
            Assert.IsTrue(d.Decimal > new BigInteger(0));
#endif

            Assert.IsTrue(d.Float == d.Float);
            Assert.IsTrue(d.Float > 0);
            Assert.IsTrue(d.Float > 0.0m);
            Assert.IsTrue(d.Float > 0.0f);
            Assert.IsTrue(d.Float > null);
            Assert.IsTrue(d.Float >= null);
            Assert.IsTrue(d.Float < 2);
            Assert.IsTrue(d.Float <= 1.1);
            Assert.IsTrue(d.Float == 1.1);
            Assert.IsTrue(d.Float == 1.1m);
            Assert.IsTrue(d.Float != 1.0f);
            Assert.IsTrue(d.Float != 1.0d);
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
            Assert.IsTrue(d.Float > new BigInteger(0));
#endif

#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
            Assert.IsTrue(d.BigInteger == d.BigInteger);
            Assert.IsTrue(d.BigInteger > 0);
            Assert.IsTrue(d.BigInteger > 0.0m);
            Assert.IsTrue(d.BigInteger > 0.0f);
            Assert.IsTrue(d.BigInteger > null);
            Assert.IsTrue(d.BigInteger >= null);
            Assert.IsTrue(d.BigInteger < 2);
            Assert.IsTrue(d.BigInteger <= 1.1);
            Assert.IsTrue(d.BigInteger == 1);
            Assert.IsTrue(d.BigInteger == 1m);
            Assert.IsTrue(d.BigInteger != 1.1f);
            Assert.IsTrue(d.BigInteger != 1.1d);
#endif

            Assert.IsTrue(d.Bytes == d.Bytes);
            Assert.IsTrue(d.Bytes == Encoding.UTF8.GetBytes("A string lol!"));
            Assert.IsTrue(d.Bytes == new JValue(Encoding.UTF8.GetBytes("A string lol!")));

            Assert.IsTrue(d.Uri == d.Uri);
            Assert.IsTrue(d.Uri == new Uri("http://json.codeplex.com/"));
            Assert.IsTrue(d.Uri > new Uri("http://abc.org/"));
            Assert.IsTrue(d.Uri >= new Uri("http://abc.com/"));
            Assert.IsTrue(d.Uri > null);
            Assert.IsTrue(d.Uri >= null);

            Assert.IsTrue(d.Guid == d.Guid);
            Assert.IsTrue(d.Guid == new Guid("EA27FE1D-0D80-44F2-BF34-4654156FA7AF"));
            Assert.IsTrue(d.Guid > new Guid("AAAAAAAA-0D80-44F2-BF34-4654156FA7AF"));
            Assert.IsTrue(d.Guid >= new Guid("AAAAAAAA-0D80-44F2-BF34-4654156FA7AF"));
            Assert.IsTrue(d.Guid > null);
            Assert.IsTrue(d.Guid >= null);

            Assert.IsTrue(d.TimeSpan == d.TimeSpan);
            Assert.IsTrue(d.TimeSpan == TimeSpan.FromDays(1));
            Assert.IsTrue(d.TimeSpan > TimeSpan.FromHours(1));
            Assert.IsTrue(d.TimeSpan >= TimeSpan.FromHours(1));
            Assert.IsTrue(d.TimeSpan > null);
            Assert.IsTrue(d.TimeSpan >= null);
        }
Beispiel #39
0
        public void SetValueWithInvalidPropertyName()
        {
            JObject o = new JObject();

            o[0] = new JValue(3);
        }
Beispiel #40
0
        public void JValueAddition()
        {
            JObject o = new JObject(
                new JProperty("Null", JValue.CreateNull()),
                new JProperty("Integer", new JValue(1)),
                new JProperty("Float", new JValue(1.1d)),
                new JProperty("Decimal", new JValue(1.1m)),
                new JProperty("DateTime", new JValue(new DateTime(2000, 12, 29, 23, 51, 10, DateTimeKind.Utc))),
                new JProperty("Boolean", new JValue(true)),
                new JProperty("String", new JValue("A string lol!")),
                new JProperty("Bytes", new JValue(Encoding.UTF8.GetBytes("A string lol!"))),
                new JProperty("Uri", new Uri("http://json.codeplex.com/")),
                new JProperty("Guid", new Guid("EA27FE1D-0D80-44F2-BF34-4654156FA7AF")),
                new JProperty("TimeSpan", TimeSpan.FromDays(1))
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
                , new JProperty("BigInteger", new BigInteger(100))
#endif
                );

            dynamic d = o;
            dynamic r;

            #region Add
            r = d.String + " LAMO!";
            Assert.AreEqual("A string lol! LAMO!", (string)r);
            r += " gg";
            Assert.AreEqual("A string lol! LAMO! gg", (string)r);

            r = d.String + null;
            Assert.AreEqual("A string lol!", (string)r);
            r += null;
            Assert.AreEqual("A string lol!", (string)r);

            r = d.Integer + 1;
            Assert.AreEqual(2, (int)r);
            r += 2;
            Assert.AreEqual(4, (int)r);

            r = d.Integer + 1.1;
            Assert.AreEqual(2.1, (double)r);
            r += 2;
            Assert.AreEqual(4.1, (double)r);

            r = d.Integer + 1.1d;
            Assert.AreEqual(2.1m, (decimal)r);
            r += 2;
            Assert.AreEqual(4.1m, (decimal)r);

            r = d.Integer + null;
            Assert.AreEqual(null, r.Value);
            r += 2;
            Assert.AreEqual(null, r.Value);

            r = d.Float + 1;
            Assert.AreEqual(2.1d, (double)r);
            r += 2;
            Assert.AreEqual(4.1d, (double)r);

            r = d.Float + 1.1;
            Assert.AreEqual(2.2d, (double)r);
            r += 2;
            Assert.AreEqual(4.2d, (double)r);

            r = d.Float + 1.1d;
            Assert.AreEqual(2.2m, (decimal)r);
            r += 2;
            Assert.AreEqual(4.2m, (decimal)r);

            r = d.Float + null;
            Assert.AreEqual(null, r.Value);
            r += 2;
            Assert.AreEqual(null, r.Value);

            r = d.Decimal + 1;
            Assert.AreEqual(2.1m, (decimal)r);
            r += 2;
            Assert.AreEqual(4.1m, (decimal)r);

            r = d.Decimal + 1.1;
            Assert.AreEqual(2.2m, (decimal)r);
            r += 2;
            Assert.AreEqual(4.2m, (decimal)r);

            r = d.Decimal + 1.1d;
            Assert.AreEqual(2.2m, (decimal)r);
            r += 2;
            Assert.AreEqual(4.2m, (decimal)r);

            r = d.Decimal + null;
            Assert.AreEqual(null, r.Value);
            r += 2;
            Assert.AreEqual(null, r.Value);

#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
            r = d.BigInteger + null;
            Assert.AreEqual(null, r.Value);
            r += 2;
            Assert.AreEqual(null, r.Value);

            r = d.BigInteger + 1;
            Assert.AreEqual(101, (int)r);
            r += 2;
            Assert.AreEqual(103, (int)r);

            r = d.BigInteger + 1.1d;
            Assert.AreEqual(101m, (decimal)r);
            r += 2;
            Assert.AreEqual(103m, (decimal)r);
#endif
            #endregion

            #region Subtract
            r = d.Integer - 1;
            Assert.AreEqual(0, (int)r);
            r -= 2;
            Assert.AreEqual(-2, (int)r);

            r = d.Integer - 1.1;
            Assert.AreEqual(-0.1d, (double)r, 0.00001);
            r -= 2;
            Assert.AreEqual(-2.1d, (double)r);

            r = d.Integer - 1.1d;
            Assert.AreEqual(-0.1m, (decimal)r);
            r -= 2;
            Assert.AreEqual(-2.1m, (decimal)r);

            r = d.Integer - null;
            Assert.AreEqual(null, r.Value);
            r -= 2;
            Assert.AreEqual(null, r.Value);

            r = d.Float - 1;
            Assert.AreEqual(0.1d, (double)r, 0.00001);
            r -= 2;
            Assert.AreEqual(-1.9d, (double)r);

            r = d.Float - 1.1;
            Assert.AreEqual(0d, (double)r);
            r -= 2;
            Assert.AreEqual(-2d, (double)r);

            r = d.Float - 1.1d;
            Assert.AreEqual(0m, (decimal)r);
            r -= 2;
            Assert.AreEqual(-2m, (decimal)r);

            r = d.Float - null;
            Assert.AreEqual(null, r.Value);
            r -= 2;
            Assert.AreEqual(null, r.Value);

            r = d.Decimal - 1;
            Assert.AreEqual(0.1m, (decimal)r);
            r -= 2;
            Assert.AreEqual(-1.9m, (decimal)r);

            r = d.Decimal - 1.1;
            Assert.AreEqual(0m, (decimal)r);
            r -= 2;
            Assert.AreEqual(-2m, (decimal)r);

            r = d.Decimal - 1.1d;
            Assert.AreEqual(0m, (decimal)r);
            r -= 2;
            Assert.AreEqual(-2m, (decimal)r);

            r = d.Decimal - null;
            Assert.AreEqual(null, r.Value);
            r -= 2;
            Assert.AreEqual(null, r.Value);

#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
            r = d.BigInteger - null;
            Assert.AreEqual(null, r.Value);
            r -= 2;
            Assert.AreEqual(null, r.Value);

            r = d.BigInteger - 1.1d;
            Assert.AreEqual(99m, (decimal)r);
            r -= 2;
            Assert.AreEqual(97m, (decimal)r);
#endif
            #endregion

            #region Multiply
            r = d.Integer * 1;
            Assert.AreEqual(1, (int)r);
            r *= 2;
            Assert.AreEqual(2, (int)r);

            r = d.Integer * 1.1;
            Assert.AreEqual(1.1d, (double)r);
            r *= 2;
            Assert.AreEqual(2.2d, (double)r);

            r = d.Integer * 1.1d;
            Assert.AreEqual(1.1m, (decimal)r);
            r *= 2;
            Assert.AreEqual(2.2m, (decimal)r);

            r = d.Integer * null;
            Assert.AreEqual(null, r.Value);
            r *= 2;
            Assert.AreEqual(null, r.Value);

            r = d.Float * 1;
            Assert.AreEqual(1.1d, (double)r);
            r *= 2;
            Assert.AreEqual(2.2d, (double)r);

            r = d.Float * 1.1;
            Assert.AreEqual(1.21d, (double)r, 0.00001);
            r *= 2;
            Assert.AreEqual(2.42d, (double)r, 0.00001);

            r = d.Float * 1.1d;
            Assert.AreEqual(1.21m, (decimal)r);
            r *= 2;
            Assert.AreEqual(2.42m, (decimal)r);

            r = d.Float * null;
            Assert.AreEqual(null, r.Value);
            r *= 2;
            Assert.AreEqual(null, r.Value);

            r = d.Decimal * 1;
            Assert.AreEqual(1.1m, (decimal)r);
            r *= 2;
            Assert.AreEqual(2.2m, (decimal)r);

            r = d.Decimal * 1.1;
            Assert.AreEqual(1.21m, (decimal)r);
            r *= 2;
            Assert.AreEqual(2.42m, (decimal)r);

            r = d.Decimal * 1.1d;
            Assert.AreEqual(1.21m, (decimal)r);
            r *= 2;
            Assert.AreEqual(2.42m, (decimal)r);

            r = d.Decimal * null;
            Assert.AreEqual(null, r.Value);
            r *= 2;
            Assert.AreEqual(null, r.Value);

#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
            r = d.BigInteger * 1.1d;
            Assert.AreEqual(100m, (decimal)r);
            r *= 2;
            Assert.AreEqual(200m, (decimal)r);

            r = d.BigInteger * null;
            Assert.AreEqual(null, r.Value);
            r *= 2;
            Assert.AreEqual(null, r.Value);
#endif
            #endregion

            #region Divide
            r = d.Integer / 1;
            Assert.AreEqual(1, (int)r);
            r /= 2;
            Assert.AreEqual(0, (int)r);

            r = d.Integer / 1.1;
            Assert.AreEqual(0.9090909090909091d, (double)r);
            r /= 2;
            Assert.AreEqual(0.454545454545455d, (double)r, 0.00001);

            r = d.Integer / 1.1d;
            Assert.AreEqual(0.909090909090909m, (decimal)r);
            r /= 2;
            Assert.AreEqual(0.454545454545454m, (decimal)r);

            r = d.Integer / null;
            Assert.AreEqual(null, r.Value);
            r /= 2;
            Assert.AreEqual(null, r.Value);

            r = d.Float / 1;
            Assert.AreEqual(1.1d, (double)r);
            r /= 2;
            Assert.AreEqual(0.55d, (double)r);

            r = d.Float / 1.1;
            Assert.AreEqual(1d, (double)r, 0.00001);
            r /= 2;
            Assert.AreEqual(0.5d, (double)r, 0.00001);

            r = d.Float / 1.1d;
            Assert.AreEqual(1m, (decimal)r);
            r /= 2;
            Assert.AreEqual(0.5m, (decimal)r);

            r = d.Float / null;
            Assert.AreEqual(null, r.Value);
            r /= 2;
            Assert.AreEqual(null, r.Value);

            r = d.Decimal / 1;
            Assert.AreEqual(1.1m, (decimal)r);
            r /= 2;
            Assert.AreEqual(0.55m, (decimal)r);

            r = d.Decimal / 1.1;
            Assert.AreEqual(1m, (decimal)r);
            r /= 2;
            Assert.AreEqual(0.5m, (decimal)r);

            r = d.Decimal / 1.1d;
            Assert.AreEqual(1m, (decimal)r);
            r /= 2;
            Assert.AreEqual(0.5m, (decimal)r);

            r = d.Decimal / null;
            Assert.AreEqual(null, r.Value);
            r /= 2;
            Assert.AreEqual(null, r.Value);

#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
            r = d.BigInteger / 1.1d;
            Assert.AreEqual(100m, (decimal)r);
            r /= 2;
            Assert.AreEqual(50m, (decimal)r);

            r = d.BigInteger / null;
            Assert.AreEqual(null, r.Value);
            r /= 2;
            Assert.AreEqual(null, r.Value);
#endif
            #endregion
        }
Beispiel #41
0
        internal static EntityHistory EntityHistory(this EntityEntry entry, JsonSerializer jsonSerializer)
        {
            var entityHistory = new EntityHistory
            {
                EntityName = entry.Metadata.Relational().TableName
            };

            // Get the mapped properties for the entity type.
            // (include shadow properties, not include navigations & references)
            var properties = entry.Properties;

            var json = new JObject();

            switch (entry.State)
            {
            case EntityState.Added:
                foreach (var prop in properties)
                {
                    if (prop.Metadata.IsKey() || prop.Metadata.IsForeignKey())
                    {
                        continue;
                    }
                    json[prop.Metadata.Name] = prop.CurrentValue != null
                            ? JToken.FromObject(prop.CurrentValue, jsonSerializer)
                            : JValue.CreateNull();
                }

                entityHistory.EntityId      = entry.PrimaryKey();
                entityHistory.EntityState   = EntityState.Added;
                entityHistory.ChangeHistory = json.ToString();
                break;

            case EntityState.Modified:
                var before = new JObject();
                var after  = new JObject();

                foreach (var prop in properties)
                {
                    if (prop.IsModified)
                    {
                        before[prop.Metadata.Name] = prop.OriginalValue != null
                            ? JToken.FromObject(prop.OriginalValue, jsonSerializer)
                            : JValue.CreateNull();

                        after[prop.Metadata.Name] = prop.CurrentValue != null
                            ? JToken.FromObject(prop.CurrentValue, jsonSerializer)
                            : JValue.CreateNull();
                    }
                }

                json["before"] = before;
                json["after"]  = after;

                entityHistory.EntityId      = entry.PrimaryKey();
                entityHistory.EntityState   = EntityState.Modified;
                entityHistory.ChangeHistory = json.ToString();
                break;

            case EntityState.Deleted:
                foreach (var prop in properties)
                {
                    json[prop.Metadata.Name] = prop.OriginalValue != null
                            ? JToken.FromObject(prop.OriginalValue, jsonSerializer)
                            : JValue.CreateNull();
                }
                entityHistory.EntityId      = entry.PrimaryKey();
                entityHistory.EntityState   = EntityState.Deleted;
                entityHistory.ChangeHistory = json.ToString();
                break;

            case EntityState.Detached:
            case EntityState.Unchanged:
            default:
                throw new NotSupportedException("AutoHistory only support Deleted and Modified entity.");
            }

            return(entityHistory);
        }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        object value = new object();

        if (reader.TokenType != JsonToken.Null)
        {
            if (reader.TokenType == JsonToken.StartArray)
            {
                JToken        token     = JToken.Load(reader);
                List <object> resultado = new List <object>();
                foreach (var Value in token)
                {
                    switch (Value.Type)
                    {
                    case JTokenType.Integer:
                        value = Convert.ToInt32(Value);
                        resultado.Add(value);
                        break;

                    case JTokenType.Float:
                        value = Convert.ToDecimal(Value);
                        resultado.Add(value);
                        break;

                    case JTokenType.String:
                        value = Convert.ToString(Value);
                        resultado.Add(value);
                        break;

                    case JTokenType.Boolean:
                        value = Convert.ToBoolean(Value);
                        resultado.Add(value);
                        break;

                    case JTokenType.Null:
                        value = null;
                        resultado.Add(value);
                        break;

                    case JTokenType.Date:
                        value = Convert.ToDateTime(Value);
                        resultado.Add(value);
                        break;

                    case JTokenType.Bytes:
                        value = Convert.ToByte(Value);
                        resultado.Add(value);
                        break;

                    default:
                        Console.WriteLine("Default case");
                        Console.WriteLine(reader.TokenType.ToString());
                        break;
                    }
                }
                value = resultado.ToArray();
            }
            else
            {
                JValue jValue = new JValue(reader.Value);
                switch (reader.TokenType)
                {
                case JsonToken.Integer:
                    value = Convert.ToInt32(reader.Value);
                    break;

                case JsonToken.Float:
                    value = Convert.ToDecimal(reader.Value);
                    break;

                case JsonToken.String:
                    value = Convert.ToString(reader.Value);
                    break;

                case JsonToken.Boolean:
                    value = Convert.ToBoolean(reader.Value);
                    break;

                case JsonToken.Null:
                    value = null;
                    break;

                case JsonToken.Date:
                    value = Convert.ToDateTime(reader.Value);
                    break;

                case JsonToken.Bytes:
                    value = Convert.ToByte(reader.Value);
                    break;

                default:
                    Console.WriteLine("Default case");
                    Console.WriteLine(reader.TokenType.ToString());
                    break;
                }
            }
        }
        return(value);
    }
Beispiel #43
0
        protected Dictionary <string, DataObject> ScanFromData(Dictionary <string, DataObject> source, ConditionToken token)
        {
            Dictionary <string, DataObject> result = new Dictionary <string, DataObject>();
            Argument left  = token.Left;
            Argument right = token.Right;


            //  계산하기 편하도록 값(Value)은 오른쪽에 배치
            if (left is Value && (right is Value) == false)
            {
                ExchangeArgument(ref left, ref right);
            }


            //  양쪽 모두 값인 경우
            if (left is Value && right is Value)
            {
                int comp = left.CompareTo(right);
                if (IsTrue(comp, token.ComparisonOperator))
                {
                    return(source);
                }

                return(result);
            }


            //  key에 해당하는 ObjectId 목록을 가져온다.
            string        key          = (left as ReferenceValue).Expr;
            List <string> objectIdList = Collection.GetObjects(key).Keys.ToList();


            foreach (var objectId in objectIdList)
            {
                //  source에 포함된 Object만을 대상으로 한다.
                if (source.ContainsKey(objectId) == false)
                {
                    continue;
                }


                //  Collection Key에 해당하는 데이터 가져오기
                DataObject obj = Collection.CachedObjects.GetData(objectId);
                JValue     leftVal = null, compVal = null;


                //  값과 비교
                if (right is Value)
                {
                    leftVal = obj.GetValue(key);
                    compVal = new JValue(right.GetValue());
                }
                else if (right is ReferenceValue)
                {
                    leftVal = obj.GetValue(key);
                    compVal = obj.GetValue((right as ReferenceValue).Expr);
                }

                int comp = leftVal.CompareTo(compVal);
                if (IsTrue(comp, token.ComparisonOperator))
                {
                    result.Add(obj.ObjectId, obj);
                }
            }

            return(result);
        }
Beispiel #44
0
        public void Previous()
        {
            JValue v = new JValue(true);

            Assert.IsNull(v.Previous);
        }
Beispiel #45
0
    public void ExceptionFromOverloadWithJValue()
    {
      dynamic name = new JValue("Matthew Doig");

      IDictionary<string, string> users = new Dictionary<string, string>();

      // unfortunatly there doesn't appear to be a way around this
      ExceptionAssert.Throws<Microsoft.CSharp.RuntimeBinder.RuntimeBinderException>("The best overloaded method match for 'System.Collections.Generic.IDictionary<string,string>.Add(string, string)' has some invalid arguments",
        () =>
          {
            users.Add("name2", name);

            Assert.AreEqual(users["name2"], "Matthew Doig");
          });
    }
Beispiel #46
0
    public void Insert()
    {
      JValue v1 = new JValue(1);
      JValue v2 = new JValue(2);
      JValue v3 = new JValue(3);
      JValue v4 = new JValue(4);

      JArray j = new JArray();

      j.Add(v1);
      j.Add(v2);
      j.Add(v3);
      j.Insert(1, v4);

      Assert.AreEqual(0, j.IndexOf(v1));
      Assert.AreEqual(1, j.IndexOf(v4));
      Assert.AreEqual(2, j.IndexOf(v2));
      Assert.AreEqual(3, j.IndexOf(v3));
    }
Beispiel #47
0
        public void Root()
        {
            JValue v = new JValue(true);

            Assert.AreEqual(v, v.Root);
        }
        public void JPropertyIndexOf()
        {
            JValue v = new JValue(1);
            JProperty p1 = new JProperty("TestProperty", v);

            IList l1 = p1;
            Assert.Equal(0, l1.IndexOf(v));

            IList<JToken> l2 = p1;
            Assert.Equal(0, l2.IndexOf(v));
        }
Beispiel #49
0
        public void Next()
        {
            JValue v = new JValue(true);

            Assert.IsNull(v.Next);
        }
        private bool EqualsWithStringCoercion(JValue value, JValue queryValue)
        {
            if (value.Equals(queryValue))
            {
                return true;
            }

            if (queryValue.Type != JTokenType.String)
            {
                return false;
            }

            string queryValueString = (string)queryValue.Value;

            string currentValueString;

            // potential performance issue with converting every value to string?
            switch (value.Type)
            {
                case JTokenType.Date:
                    using (StringWriter writer = StringUtils.CreateStringWriter(64))
                    {
#if !NET20
                        if (value.Value is DateTimeOffset)
                        {
                            DateTimeUtils.WriteDateTimeOffsetString(writer, (DateTimeOffset)value.Value, DateFormatHandling.IsoDateFormat, null, CultureInfo.InvariantCulture);
                        }
                        else
#endif
                        {
                            DateTimeUtils.WriteDateTimeString(writer, (DateTime)value.Value, DateFormatHandling.IsoDateFormat, null, CultureInfo.InvariantCulture);
                        }

                        currentValueString = writer.ToString();
                    }
                    break;
                case JTokenType.Bytes:
                    currentValueString = Convert.ToBase64String((byte[])value.Value);
                    break;
                case JTokenType.Guid:
                case JTokenType.TimeSpan:
                    currentValueString = value.Value.ToString();
                    break;
                case JTokenType.Uri:
                    currentValueString = ((Uri)value.Value).OriginalString;
                    break;
                default:
                    return false;
            }

            return string.Equals(currentValueString, queryValueString, StringComparison.Ordinal);
        }
Beispiel #51
0
        public void ToStringFormat()
        {
            JValue v = new JValue(new DateTime(2013, 02, 01, 01, 02, 03, 04));

            Assert.AreEqual("2013", v.ToString("yyyy"));
        }
Beispiel #52
0
    public void InsertShouldInsertAtZeroIndex()
    {
      JValue v1 = new JValue(1);
      JValue v2 = new JValue(2);

      JArray j = new JArray();

      j.Insert(0, v1);
      Assert.AreEqual(0, j.IndexOf(v1));

      j.Insert(0, v2);
      Assert.AreEqual(1, j.IndexOf(v1));
      Assert.AreEqual(0, j.IndexOf(v2));
    }
 public static string GetValue(this JValue jobj) => (string)jobj;
Beispiel #54
0
 public void SetValueWithInvalidIndex()
 {
   ExceptionAssert.Throws<ArgumentException>(
     @"Set JArray values with invalid key value: ""badvalue"". Array position index expected.",
     () =>
     {
       JArray a = new JArray();
       a["badvalue"] = new JValue(3);
     });
 }
        public void JPropertyContains()
        {
            JValue v = new JValue(1);
            var p = new JProperty("TestProperty", v);

            Assert.Equal(true, p.Contains(v));
            Assert.Equal(false, p.Contains(new JValue(1)));
        }
Beispiel #56
0
 private static void WriteBool(JToken token, string property, bool value)
 {
     token[property] = new JValue(value);
 }
Beispiel #57
0
 private static JToken WriteString(string item)
 {
     return(item != null ? new JValue(item) : JValue.CreateNull());
 }
Beispiel #58
0
    public void AddFirstAddedTokenShouldBeFirst()
    {
      JValue v1 = new JValue(1);
      JValue v2 = new JValue(2);
      JValue v3 = new JValue(3);

      JArray j = new JArray();
      Assert.AreEqual(null, j.First);
      Assert.AreEqual(null, j.Last);

      j.AddFirst(v1);
      Assert.AreEqual(v1, j.First);
      Assert.AreEqual(v1, j.Last);

      j.AddFirst(v2);
      Assert.AreEqual(v2, j.First);
      Assert.AreEqual(v1, j.Last);

      j.AddFirst(v3);
      Assert.AreEqual(v3, j.First);
      Assert.AreEqual(v1, j.Last);
    }
        internal void AddValue(JValue value, JsonToken token)
        {
            if (_parent != null)
            {
                _parent.Add(value);

                if (_parent.Type == JTokenType.Property)
                    _parent = _parent.Parent;
            }
            else
            {
                _value = value ?? JValue.CreateNull();
            }
        }
        public void Authorize(string client_id, string client_secret, int port = 8080)
        {
            // the strava oath/authorize endpoint expects a redirect url so that after the user logs in
            // to strava in the browser and authorizes the app to access his data, it redirects the browser
            // to the redirect url. We will start an http server on the specified port in order to receive
            // that redirect. The redirect url they redirect to will include a parameter named "code" which
            // we need for the next step.

            // start the http server
            MyHttpServer httpServer = new MyHttpServer(port);
            Thread       thread     = new Thread(new ThreadStart(httpServer.listen));

            thread.IsBackground = true;
            thread.Start();

            Console.WriteLine("Launching a browser to log in to Strava and authorize StravaExporter to download your data");

            // build the initial authorization request url and launch a browser for user to
            // log in and grant us access
            string redirect_uri = string.Format("http://localhost:{0}/exchange_token", port);
            //string scope = "read,read_all,profile:read_all,profile:write,activity:read,activity:read_all,activity:write";
            string scope = "read,activity:read,activity:read_all";
            string url   = string.Format("http://www.strava.com/oauth/authorize?client_id={0}&response_type=code&redirect_uri={1}&approval_prompt=force&scope={2}",
                                         client_id, redirect_uri, scope);

            // launch the browser
            System.Diagnostics.Process.Start(url);

            // after the user completes the authorization in the browser, it will redirect to our http server.
            // wait for the http server thread to complete for a while then we'll fail;
            // need to assume failure at some point, and if the client id was bad we can't recover otherwise
            int timeoutSecs = 60;

            Console.Write("Waiting for authorization from browser. Press CTRL+C to cancel. Will time out in... ");
            int row = Console.CursorTop;
            int col = Console.CursorLeft;

            Console.Write("{0,2}", timeoutSecs);
            while (--timeoutSecs >= 0 && !thread.Join(1000))
            {
                Console.SetCursorPosition(col, row);
                Console.Write("{0,2}", timeoutSecs);
            }
            Console.WriteLine();
            Console.WriteLine();

            string accessCode = httpServer.AccessCode;

            if (accessCode == null)
            {
                throw new AuthorizationException("StravaExporter was not authorized to access Strava data");
            }

            // now we need to POST to https://www.strava.com/oauth/token with the access code
            // client_id: your application’s ID, obtained during registration
            // client_secret: your application’s secret, obtained during registration
            // code: authorization code from last step
            // grant_type: the grant type for the request. For initial authentication, must always be "authorization_code".

            // https://www.strava.com/oauth/token?client_id=12345&client_secret=xxxxx&code=&grant_type=authorization_code
            url = string.Format("https://www.strava.com/oauth/token?client_id={0}&client_secret={1}&code={2}&grant_type=authorization_code",
                                client_id, client_secret, accessCode);

            HttpClient          httpClient = new HttpClient();
            HttpResponseMessage response   = httpClient.PostAsync(url, null).GetAwaiter().GetResult();

            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                throw new AuthorizationException("Authorization failed. Please check your API keys (client id and secret)");
            }
            response.EnsureSuccessStatusCode();
            string responseBody = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();

            dynamic json          = JValue.Parse(responseBody);
            string  access_token  = json.access_token;
            string  refresh_token = json.refresh_token;

            Console.WriteLine("Access Token = {0}", access_token);
            Console.WriteLine("Refresh Token = {0}", refresh_token);

            Properties.Settings.Default.RefreshToken = refresh_token;

            Console.WriteLine();
            Console.WriteLine("Authorization succeeded");
        }