/// <summary>${iServer2_SetLayerStatusResult_method_FromJson_D}</summary> /// <returns>${iServer2_SetLayerStatusResult_method_FromJson_return}</returns> /// <param name="jsonPrimitive">${iServer2_SetLayerStatusResult_method_FromJson_param_jsonObject}</param> public static SetLayerStatusResult FromJson(JsonPrimitive jsonPrimitive) { if (jsonPrimitive == null) { return null; } return new SetLayerStatusResult { LayersKey = jsonPrimitive }; }
/// <summary>${iServer2_RemoveThemesResult_method_FromJson_D}</summary> /// <returns>${iServer2_RemoveThemesResult_method_FromJson_return}</returns> /// <param name="jsonPrimitive">${iServer2_RemoveThemesResult_method_FromJson_param_jsonObject}</param> public static RemoveThemesResult FromJson(JsonPrimitive jsonPrimitive) { if (jsonPrimitive == null) { return null; } return new RemoveThemesResult { LayerKey = jsonPrimitive }; }
/// <summary>${IS6_SetLayerStatusResult_method_FromJson_D}</summary> /// <returns>${IS6_SetLayerStatusResult_method_FromJson_return}</returns> /// <param name="jsonObject">${IS6_SetLayerStatusResult_method_FromJson_param_jsonObject}</param> public static SetLayerStatusResult FromJson(JsonPrimitive jsonObject) { if (jsonObject == null) { return null; } SetLayerStatusResult result = new SetLayerStatusResult(); result.LayersKey=(string)jsonObject; return result; }
public void ValidJsonObjectDateTimeOffsetRoundTrip() { int seed = 1; Log.Info("Seed: {0}", seed); Random rndGen = new Random(seed); JsonPrimitive sourceJson = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfDateTimeOffset(rndGen)); JsonPrimitive newJson = (JsonPrimitive)JsonValue.Parse(sourceJson.ToString()); Assert.True(JsonValueVerifier.Compare(sourceJson, newJson)); }
public void CastTests() { int value = 10; JsonValue target = new JsonPrimitive(value); int v1 = JsonValue.CastValue<int>(target); Assert.AreEqual<int>(value, v1); v1 = (int)target; Assert.AreEqual<int>(value, v1); long v2 = JsonValue.CastValue<long>(target); Assert.AreEqual<long>(value, v2); v2 = (long)target; Assert.AreEqual<long>(value, v2); string s = JsonValue.CastValue<string>(target); Assert.AreEqual<string>(value.ToString(), s); s = (string)target; Assert.AreEqual<string>(value.ToString(), s); object obj = JsonValue.CastValue<object>(target); Assert.AreEqual(target, obj); obj = (object)target; Assert.AreEqual(target, obj); object nill = JsonValue.CastValue<object>(null); Assert.IsNull(nill); dynamic dyn = target; JsonValue defaultJv = dyn.IamDefault; nill = JsonValue.CastValue<string>(defaultJv); Assert.IsNull(nill); nill = (string)defaultJv; Assert.IsNull(nill); obj = JsonValue.CastValue<object>(defaultJv); Assert.AreSame(defaultJv, obj); obj = (object)defaultJv; Assert.AreSame(defaultJv, obj); JsonValue jv = JsonValue.CastValue<JsonValue>(target); Assert.AreEqual<JsonValue>(target, jv); jv = JsonValue.CastValue<JsonValue>(defaultJv); Assert.AreEqual<JsonValue>(defaultJv, jv); jv = JsonValue.CastValue<JsonPrimitive>(target); Assert.AreEqual<JsonValue>(target, jv); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { int i = JsonValue.CastValue<int>(null); }); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { int i = JsonValue.CastValue<int>(defaultJv); }); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { int i = JsonValue.CastValue<char>(target); }); }
private void CheckValues(object[] values, JsonType expectedType) { JsonPrimitive target; bool success; foreach (object value in values) { success = JsonPrimitive.TryCreate(value, out target); Assert.True(success); Assert.NotNull(target); Assert.Equal(expectedType, target.JsonType); } }
/// <summary>${iServer2_ThemeResult_method_FromJson_D}</summary> /// <returns>${iServer2_ThemeResult_method_FromJson_return}</returns> /// <param name="jsonPrimitive">${iServer2_ThemeResult_method_FromJson_param_jsonObject}</param> public static ThemeResult FromJson(JsonPrimitive jsonPrimitive) { if (jsonPrimitive == null) { return null; } string str = jsonPrimitive; ThemeResult result = new ThemeResult(); result.Name = str.Substring(0, str.IndexOf(",")); result.Key = str.Substring(str.IndexOf(",") + 1, str.Length - str.IndexOf(",") - 1); return result; }
/// <summary>${IS6_ThemeResult_method_FromJson_D}</summary> /// <returns>${IS6_ThemeResult_method_FromJson_return}</returns> /// <param name="jsonPrimitive">${IS6_ThemeResult_method_FromJson_param_jsonObject}</param> public static ThemeResult FromJson(JsonPrimitive jsonPrimitive) { if (jsonPrimitive == null) { return null; } ThemeResult result = new ThemeResult(); result.LayerKey = jsonPrimitive; return result; }
public void ValueTest() { object[] values = { AnyInstance.AnyInt, AnyInstance.AnyString, AnyInstance.AnyGuid, AnyInstance.AnyDecimal, AnyInstance.AnyBool, AnyInstance.AnyDateTime }; foreach (object value in values) { JsonPrimitive jp; bool success = JsonPrimitive.TryCreate(value, out jp); Assert.True(success); Assert.Equal(value, jp.Value); } }
public void ReadAsTest() { JsonValue target = new JsonPrimitive(AnyInstance.AnyInt); Assert.Equal(AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture), target.ReadAs(typeof(string))); Assert.Equal(AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture), target.ReadAs <string>()); object value; double dblValue; Assert.True(target.TryReadAs(typeof(double), out value)); Assert.True(target.TryReadAs <double>(out dblValue)); Assert.Equal(Convert.ToDouble(AnyInstance.AnyInt, CultureInfo.InvariantCulture), (double)value); Assert.Equal(Convert.ToDouble(AnyInstance.AnyInt, CultureInfo.InvariantCulture), dblValue); Assert.False(target.TryReadAs(typeof(Guid), out value), "TryReadAs should have failed to read a double as a Guid"); Assert.Null(value); }
public void NonNumberToNumberConversionTest() { Assert.Equal(1, new JsonPrimitive('1').ReadAs <int>()); Assert.Equal <byte>(AnyInstance.AnyByte, new JsonPrimitive(AnyInstance.AnyByte.ToString(CultureInfo.InvariantCulture)).ReadAs <byte>()); Assert.Equal <sbyte>(AnyInstance.AnySByte, (sbyte)(new JsonPrimitive(AnyInstance.AnySByte.ToString(CultureInfo.InvariantCulture)))); Assert.Equal <short>(AnyInstance.AnyShort, (short)(new JsonPrimitive(AnyInstance.AnyShort.ToString(CultureInfo.InvariantCulture)))); Assert.Equal <ushort>(AnyInstance.AnyUShort, new JsonPrimitive(AnyInstance.AnyUShort.ToString(CultureInfo.InvariantCulture)).ReadAs <ushort>()); Assert.Equal <int>(AnyInstance.AnyInt, new JsonPrimitive(AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture)).ReadAs <int>()); Assert.Equal <uint>(AnyInstance.AnyUInt, (uint)(new JsonPrimitive(AnyInstance.AnyUInt.ToString(CultureInfo.InvariantCulture)))); Assert.Equal <long>(AnyInstance.AnyLong, (long)(new JsonPrimitive(AnyInstance.AnyLong.ToString(CultureInfo.InvariantCulture)))); Assert.Equal <ulong>(AnyInstance.AnyULong, new JsonPrimitive(AnyInstance.AnyULong.ToString(CultureInfo.InvariantCulture)).ReadAs <ulong>()); Assert.Equal <decimal>(AnyInstance.AnyDecimal, (decimal)(new JsonPrimitive(AnyInstance.AnyDecimal.ToString(CultureInfo.InvariantCulture)))); Assert.Equal <float>(AnyInstance.AnyFloat, new JsonPrimitive(AnyInstance.AnyFloat.ToString(CultureInfo.InvariantCulture)).ReadAs <float>()); Assert.Equal <double>(AnyInstance.AnyDouble, (double)(new JsonPrimitive(AnyInstance.AnyDouble.ToString(CultureInfo.InvariantCulture)))); Assert.Equal <byte>(Convert.ToByte(1.23, CultureInfo.InvariantCulture), new JsonPrimitive("1.23").ReadAs <byte>()); Assert.Equal <int>(Convert.ToInt32(12345.6789, CultureInfo.InvariantCulture), new JsonPrimitive("12345.6789").ReadAs <int>()); Assert.Equal <short>(Convert.ToInt16(1.23e2), (short)new JsonPrimitive("1.23e2")); Assert.Equal <float>(Convert.ToSingle(1.23e40), (float)new JsonPrimitive("1.23e40")); Assert.Equal <float>(Convert.ToSingle(1.23e-38), (float)new JsonPrimitive("1.23e-38")); ExceptionHelper.Throws <InvalidCastException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyBool).ReadAs <sbyte>(); }); ExceptionHelper.Throws <InvalidCastException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyBool).ReadAs <short>(); }); ExceptionHelper.Throws <InvalidCastException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyBool).ReadAs <uint>(); }); ExceptionHelper.Throws <InvalidCastException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyBool).ReadAs <long>(); }); ExceptionHelper.Throws <InvalidCastException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyBool).ReadAs <double>(); }); ExceptionHelper.Throws <FormatException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyUri).ReadAs <int>(); }); ExceptionHelper.Throws <FormatException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyDateTime).ReadAs <float>(); }); ExceptionHelper.Throws <InvalidCastException>(delegate { var n = (decimal)(new JsonPrimitive('c')); }); ExceptionHelper.Throws <InvalidCastException>(delegate { var n = (byte)(new JsonPrimitive("0xFF")); }); ExceptionHelper.Throws <InvalidCastException>(delegate { var n = (sbyte)(new JsonPrimitive(AnyInstance.AnyDateTimeOffset)); }); ExceptionHelper.Throws <FormatException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyUri).ReadAs <uint>(); }); ExceptionHelper.Throws <FormatException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyDateTime).ReadAs <double>(); }); ExceptionHelper.Throws <InvalidCastException>(delegate { var n = (long)(new JsonPrimitive('c')); }); ExceptionHelper.Throws <InvalidCastException>(delegate { var n = (ulong)(new JsonPrimitive("0xFF")); }); ExceptionHelper.Throws <InvalidCastException>(delegate { var n = (short)(new JsonPrimitive(AnyInstance.AnyDateTimeOffset)); }); ExceptionHelper.Throws <InvalidCastException>(delegate { var n = (ushort)(new JsonPrimitive('c')); }); ExceptionHelper.Throws <OverflowException>(delegate { int i = (int)new JsonPrimitive((1L << 32).ToString(CultureInfo.InvariantCulture)); }); ExceptionHelper.Throws <OverflowException>(delegate { byte b = (byte)new JsonPrimitive("-1"); }); }
public void TryCreateInvalidTest() { bool success; JsonPrimitive target; object[] values = { AnyInstance.AnyJsonArray, AnyInstance.AnyJsonObject, AnyInstance.AnyJsonPrimitive, null, AnyInstance.DefaultJsonValue, AnyInstance.AnyDynamic, AnyInstance.AnyAddress, AnyInstance.AnyPerson }; foreach (object value in values) { success = JsonPrimitive.TryCreate(value, out target); Assert.False(success); Assert.Null(target); } }
public void CastingTests() { JsonValue target = new JsonPrimitive(AnyInstance.AnyInt); Assert.Equal(AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture), (string)target); Assert.Equal(Convert.ToDouble(AnyInstance.AnyInt, CultureInfo.InvariantCulture), (double)target); Assert.Equal(AnyInstance.AnyString, (string)(JsonValue)AnyInstance.AnyString); Assert.Equal(AnyInstance.AnyChar, (char)(JsonValue)AnyInstance.AnyChar); Assert.Equal(AnyInstance.AnyUri, (Uri)(JsonValue)AnyInstance.AnyUri); Assert.Equal(AnyInstance.AnyGuid, (Guid)(JsonValue)AnyInstance.AnyGuid); Assert.Equal(AnyInstance.AnyDateTime, (DateTime)(JsonValue)AnyInstance.AnyDateTime); Assert.Equal(AnyInstance.AnyDateTimeOffset, (DateTimeOffset)(JsonValue)AnyInstance.AnyDateTimeOffset); Assert.Equal(AnyInstance.AnyBool, (bool)(JsonValue)AnyInstance.AnyBool); Assert.Equal(AnyInstance.AnyByte, (byte)(JsonValue)AnyInstance.AnyByte); Assert.Equal(AnyInstance.AnyShort, (short)(JsonValue)AnyInstance.AnyShort); Assert.Equal(AnyInstance.AnyInt, (int)(JsonValue)AnyInstance.AnyInt); Assert.Equal(AnyInstance.AnyLong, (long)(JsonValue)AnyInstance.AnyLong); Assert.Equal(AnyInstance.AnySByte, (sbyte)(JsonValue)AnyInstance.AnySByte); Assert.Equal(AnyInstance.AnyUShort, (ushort)(JsonValue)AnyInstance.AnyUShort); Assert.Equal(AnyInstance.AnyUInt, (uint)(JsonValue)AnyInstance.AnyUInt); Assert.Equal(AnyInstance.AnyULong, (ulong)(JsonValue)AnyInstance.AnyULong); Assert.Equal(AnyInstance.AnyDecimal, (decimal)(JsonValue)AnyInstance.AnyDecimal); Assert.Equal(AnyInstance.AnyFloat, (float)(JsonValue)AnyInstance.AnyFloat); Assert.Equal(AnyInstance.AnyDouble, (double)(JsonValue)AnyInstance.AnyDouble); Uri uri = null; string str = null; JsonValue jv = uri; Assert.Null(jv); uri = (Uri)jv; Assert.Null(uri); jv = str; Assert.Null(jv); str = (string)jv; Assert.Null(str); ExceptionHelper.Throws <InvalidCastException>(delegate { var s = (string)AnyInstance.AnyJsonArray; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var s = (string)AnyInstance.AnyJsonObject; }); }
public void CastingTests() { JsonValue target = new JsonPrimitive(AnyInstance.AnyInt); Assert.AreEqual(AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture), (string)target); Assert.AreEqual(Convert.ToDouble(AnyInstance.AnyInt, CultureInfo.InvariantCulture), (double)target); Assert.AreEqual(AnyInstance.AnyString, (string)(JsonValue)AnyInstance.AnyString); Assert.AreEqual(AnyInstance.AnyChar, (char)(JsonValue)AnyInstance.AnyChar); Assert.AreEqual(AnyInstance.AnyUri, (Uri)(JsonValue)AnyInstance.AnyUri); Assert.AreEqual(AnyInstance.AnyGuid, (Guid)(JsonValue)AnyInstance.AnyGuid); Assert.AreEqual(AnyInstance.AnyDateTime, (DateTime)(JsonValue)AnyInstance.AnyDateTime); Assert.AreEqual(AnyInstance.AnyDateTimeOffset, (DateTimeOffset)(JsonValue)AnyInstance.AnyDateTimeOffset); Assert.AreEqual(AnyInstance.AnyBool, (bool)(JsonValue)AnyInstance.AnyBool); Assert.AreEqual(AnyInstance.AnyByte, (byte)(JsonValue)AnyInstance.AnyByte); Assert.AreEqual(AnyInstance.AnyShort, (short)(JsonValue)AnyInstance.AnyShort); Assert.AreEqual(AnyInstance.AnyInt, (int)(JsonValue)AnyInstance.AnyInt); Assert.AreEqual(AnyInstance.AnyLong, (long)(JsonValue)AnyInstance.AnyLong); Assert.AreEqual(AnyInstance.AnySByte, (sbyte)(JsonValue)AnyInstance.AnySByte); Assert.AreEqual(AnyInstance.AnyUShort, (ushort)(JsonValue)AnyInstance.AnyUShort); Assert.AreEqual(AnyInstance.AnyUInt, (uint)(JsonValue)AnyInstance.AnyUInt); Assert.AreEqual(AnyInstance.AnyULong, (ulong)(JsonValue)AnyInstance.AnyULong); Assert.AreEqual(AnyInstance.AnyDecimal, (decimal)(JsonValue)AnyInstance.AnyDecimal); Assert.AreEqual(AnyInstance.AnyFloat, (float)(JsonValue)AnyInstance.AnyFloat); Assert.AreEqual(AnyInstance.AnyDouble, (double)(JsonValue)AnyInstance.AnyDouble); Uri uri = null; string str = null; JsonValue jv = uri; Assert.IsNull(jv); uri = (Uri)jv; Assert.IsNull(uri); jv = str; Assert.IsNull(jv); str = (string)jv; Assert.IsNull(str); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { var s = (string)AnyInstance.AnyJsonArray; }); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { var s = (string)AnyInstance.AnyJsonObject; }); }
// the input JsonPrimitive DateTime format is "\/Date(24735422733034-0700)\/" or "\/Date(24735422733034)\/" // the only thing useful for us is the UTC ticks "24735422733034" // everything after - if present - is just an optional offset between the local time and UTC private static string GetUTCTicks(JsonPrimitive jprim) { string retValue = String.Empty; string origStr = jprim.ToString(); int startIndex = origStr.IndexOf("Date(") + 5; int endIndex = origStr.IndexOf('-', startIndex + 1); // the UTC ticks can start with a '-' sign (dates prior to 1970/01/01) // if the optional offset is present in the data format, we want to take only the UTC ticks if (startIndex < endIndex) { retValue = origStr.Substring(startIndex, endIndex - startIndex); } else { // otherwise we assume the time format is without the oiptional offset, or unexpected, and use the whole string for comparison. retValue = origStr; } return(retValue); }
public void TestInvalidOperations() { JsonArray ja = new JsonArray { 1, null, "hello" }; JsonObject jo = new JsonObject { { "first", 1 }, { "second", null }, { "third", "hello" }, }; JsonPrimitive jp = new JsonPrimitive("hello"); Assert.Throws <InvalidOperationException>(() => "jp[\"hello\"] should fail: " + jp["hello"].ToString()); Assert.Throws <InvalidOperationException>(() => "ja[\"hello\"] should fail: " + ja["hello"].ToString()); Assert.Throws <InvalidOperationException>(() => jp["hello"] = "This shouldn't happen"); Assert.Throws <InvalidOperationException>(() => ja["hello"] = "This shouldn't happen"); Assert.Throws <InvalidOperationException>(() => ("jp[1] should fail: " + jp[1].ToString())); Assert.Throws <InvalidOperationException>(() => "jo[0] should fail: " + jo[1].ToString()); Assert.Throws <InvalidOperationException>(() => jp[0] = "This shouldn't happen"); Assert.Throws <InvalidOperationException>(() => jo[0] = "This shouldn't happen"); Assert.Throws <InvalidCastException>(() => "(DateTimeOffset)jp[\"hello\"] should fail: " + (DateTimeOffset)jp); Assert.Throws <InvalidCastException>(() => ("(Char)jp[\"hello\"] should fail: " + (char)jp)); Assert.Throws <InvalidCastException>(() => { short jprim = (short)new JsonPrimitive(false); }); }
public void NonNumberToStringConversionTest() { Dictionary <string, JsonPrimitive> allValues = new Dictionary <string, JsonPrimitive> { { new string(AnyInstance.AnyChar, 1), new JsonPrimitive(AnyInstance.AnyChar) }, { AnyInstance.AnyBool.ToString(CultureInfo.InvariantCulture).ToLowerInvariant(), new JsonPrimitive(AnyInstance.AnyBool) }, { AnyInstance.AnyGuid.ToString("D", CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyGuid) }, { AnyInstance.AnyDateTime.ToString(DateTimeFormat, CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyDateTime) }, { AnyInstance.AnyDateTimeOffset.ToString(DateTimeFormat, CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyDateTimeOffset) }, }; foreach (char escapedChar in "\r\n\t\u0000\uffff\u001f\\\"") { allValues.Add(new string(escapedChar, 1), new JsonPrimitive(escapedChar)); } foreach (string stringRepresentation in allValues.Keys) { JsonPrimitive jp = allValues[stringRepresentation]; Assert.Equal(stringRepresentation, (string)jp); Assert.Equal(stringRepresentation, jp.ReadAs <string>()); } }
public void NumberToStringConverstionTest() { Dictionary <string, JsonPrimitive> allNumbers = new Dictionary <string, JsonPrimitive> { { AnyInstance.AnyByte.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyByte) }, { AnyInstance.AnySByte.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnySByte) }, { AnyInstance.AnyShort.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyShort) }, { AnyInstance.AnyUShort.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyUShort) }, { AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyInt) }, { AnyInstance.AnyUInt.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyUInt) }, { AnyInstance.AnyLong.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyLong) }, { AnyInstance.AnyULong.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyULong) }, { AnyInstance.AnyDecimal.ToString(CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyDecimal) }, { AnyInstance.AnyDouble.ToString("R", CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyDouble) }, { AnyInstance.AnyFloat.ToString("R", CultureInfo.InvariantCulture), new JsonPrimitive(AnyInstance.AnyFloat) }, }; foreach (string stringRepresentation in allNumbers.Keys) { JsonPrimitive jp = allNumbers[stringRepresentation]; Assert.Equal(stringRepresentation, (string)jp); Assert.Equal(stringRepresentation, jp.ReadAs <string>()); } }
private void DoRoundTripCasting(JsonValue jo, Type type) { bool result = false; // Casting if (jo.JsonType == JsonType.String) { JsonValue jstr = (string)jo; if (type == typeof(DateTime)) { Log.Info("{0} Value:{1}", type.Name, ((DateTime)jstr).ToString(DateTimeFormatInfo.InvariantInfo)); } else if (type == typeof(DateTimeOffset)) { Log.Info("{0} Value:{1}", type.Name, ((DateTimeOffset)jstr).ToString(DateTimeFormatInfo.InvariantInfo)); } else if (type == typeof(Guid)) { Log.Info("{0} Value:{1}", type.Name, (Guid)jstr); } else if (type == typeof(char)) { Log.Info("{0} Value:{1}", type.Name, (char)jstr); } else if (type == typeof(Uri)) { Log.Info("{0} Value:{1}", type.Name, ((Uri)jstr).AbsoluteUri); } else { Log.Info("{0} Value:{1}", type.Name, (string)jstr); } if (jo.ToString() == jstr.ToString()) { result = true; } } else if (jo.JsonType == JsonType.Object) { JsonObject jobj = new JsonObject((JsonObject)jo); if (jo.ToString() == jobj.ToString()) { result = true; } } else if (jo.JsonType == JsonType.Number) { JsonPrimitive jprim = (JsonPrimitive)jo; Log.Info("{0} Value:{1}", type.Name, jprim); if (jo.ToString() == jprim.ToString()) { result = true; } } else if (jo.JsonType == JsonType.Boolean) { JsonPrimitive jprim = (JsonPrimitive)jo; Log.Info("{0} Value:{1}", type.Name, (bool)jprim); if (jo.ToString() == jprim.ToString()) { result = true; } } Assert.True(result); }
private bool TestPrimitiveType(string typeName) { bool retValue = true; bool specialCase = false; int seed = 1; Log.Info("Seed: {0}", seed); Random rndGen = new Random(seed); JsonPrimitive sourceJson = null; JsonPrimitive sourceJson2; object tempValue = null; switch (typeName.ToLower()) { case "boolean": tempValue = PrimitiveCreator.CreateInstanceOfBoolean(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString().ToLower()); sourceJson2 = new JsonPrimitive((bool)tempValue); break; case "byte": tempValue = PrimitiveCreator.CreateInstanceOfByte(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((byte)tempValue); break; case "char": sourceJson2 = new JsonPrimitive((char)PrimitiveCreator.CreateInstanceOfChar(rndGen)); specialCase = true; break; case "datetime": tempValue = PrimitiveCreator.CreateInstanceOfDateTime(rndGen); sourceJson2 = new JsonPrimitive((DateTime)tempValue); sourceJson = (JsonPrimitive)JsonValue.Parse(sourceJson2.ToString()); break; case "decimal": tempValue = PrimitiveCreator.CreateInstanceOfDecimal(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(((decimal)tempValue).ToString(NumberFormatInfo.InvariantInfo)); sourceJson2 = new JsonPrimitive((decimal)tempValue); break; case "double": double tempDouble = PrimitiveCreator.CreateInstanceOfDouble(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempDouble.ToString("R", NumberFormatInfo.InvariantInfo)); sourceJson2 = new JsonPrimitive(tempDouble); break; case "guid": sourceJson2 = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfGuid(rndGen)); specialCase = true; break; case "int16": tempValue = PrimitiveCreator.CreateInstanceOfInt16(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((short)tempValue); break; case "int32": tempValue = PrimitiveCreator.CreateInstanceOfInt32(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((int)tempValue); break; case "int64": tempValue = PrimitiveCreator.CreateInstanceOfInt64(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((long)tempValue); break; case "sbyte": tempValue = PrimitiveCreator.CreateInstanceOfSByte(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((sbyte)tempValue); break; case "single": float fltValue = PrimitiveCreator.CreateInstanceOfSingle(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(fltValue.ToString("R", NumberFormatInfo.InvariantInfo)); sourceJson2 = new JsonPrimitive(fltValue); break; case "string": do { tempValue = PrimitiveCreator.CreateInstanceOfString(rndGen); } while (tempValue == null); sourceJson2 = new JsonPrimitive((string)tempValue); sourceJson = (JsonPrimitive)JsonValue.Parse(sourceJson2.ToString()); break; case "uint16": tempValue = PrimitiveCreator.CreateInstanceOfUInt16(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((ushort)tempValue); break; case "uint32": tempValue = PrimitiveCreator.CreateInstanceOfUInt32(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((uint)tempValue); break; case "uint64": tempValue = PrimitiveCreator.CreateInstanceOfUInt64(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((ulong)tempValue); break; case "uri": Uri uri = null; do { try { uri = PrimitiveCreator.CreateInstanceOfUri(rndGen); } catch (UriFormatException) { } } while (uri == null); sourceJson2 = new JsonPrimitive(uri); specialCase = true; break; case "null": sourceJson = (JsonPrimitive)JsonValue.Parse("null"); sourceJson2 = null; break; default: sourceJson = null; sourceJson2 = null; break; } if (!specialCase) { // comparison between two constructors if (!JsonValueVerifier.Compare(sourceJson, sourceJson2)) { Log.Info("(JsonPrimitive)JsonValue.Parse(string) failed to match the results from default JsonPrimitive(obj)constructor for type {0}", typeName); retValue = false; } if (sourceJson != null) { // test JsonValue.Load(TextReader) JsonPrimitive newJson = null; using (StringReader sr = new StringReader(sourceJson.ToString())) { newJson = (JsonPrimitive)JsonValue.Load(sr); } if (!JsonValueVerifier.Compare(sourceJson, newJson)) { Log.Info("JsonValue.Load(TextReader) failed to function properly for type {0}", typeName); retValue = false; } // test JsonValue.Load(Stream) is located in the JObjectFromGenoTypeLib test case // test JsonValue.Parse(string) newJson = null; newJson = (JsonPrimitive)JsonValue.Parse(sourceJson.ToString()); if (!JsonValueVerifier.Compare(sourceJson, newJson)) { Log.Info("JsonValue.Parse(string) failed to function properly for type {0}", typeName); retValue = false; } } } else { // test JsonValue.Load(TextReader) JsonPrimitive newJson2 = null; using (StringReader sr = new StringReader(sourceJson2.ToString())) { newJson2 = (JsonPrimitive)JsonValue.Load(sr); } if (!JsonValueVerifier.Compare(sourceJson2, newJson2)) { Log.Info("JsonValue.Load(TextReader) failed to function properly for type {0}", typeName); retValue = false; } // test JsonValue.Load(Stream) is located in the JObjectFromGenoTypeLib test case // test JsonValue.Parse(string) newJson2 = null; newJson2 = (JsonPrimitive)JsonValue.Parse(sourceJson2.ToString()); if (!JsonValueVerifier.Compare(sourceJson2, newJson2)) { Log.Info("JsonValue.Parse(string) failed to function properly for type {0}", typeName); retValue = false; } } return(retValue); }
private static bool CompareJsonPrimitiveTypes(JsonPrimitive objA, JsonPrimitive objB) { try { if (objA.ToString() != objB.ToString()) { // Special case due to daylight saving hours change: every March on the morning of the third Sunday, we adjust the time // from 2am to 3am straight, so for that one hour 2:13am = 3:15am. We must result to the UTC ticks to verify the actual // time is always the same, regardless of the loc/glob setup on the machine if (objA.ToString().StartsWith("\"\\/Date(") && objA.ToString().EndsWith(")\\/\"")) { return GetUTCTicks(objA) == GetUTCTicks(objB); } else { Log.Info("JsonValueVerifier (JsonPrimitiveTypes) Error: objA = " + objA.ToString()); Log.Info("JsonValueVerifier (JsonPrimitiveTypes) Error: objB = " + objB.ToString()); return false; } } else { return true; } } catch (Exception e) { Log.Info("JsonValueVerifier (JsonPrimitiveTypes) Error: An Exception was thrown: " + e); return false; } }
public static JsonValue JXMLToJsonValue(XmlDictionaryReader jsonReader) { if (jsonReader == null) { throw new ArgumentNullException("jsonReader"); } const string RootObjectName = "RootObject"; Stack <JsonValue> jsonStack = new Stack <JsonValue>(); string nodeType = null; bool isEmptyElement = false; JsonValue parent = new JsonObject(); jsonStack.Push(parent); string currentName = RootObjectName; try { MoveToRootNode(jsonReader); while (jsonStack.Count > 0 && jsonReader.NodeType != XmlNodeType.None) { if (parent is JsonObject && currentName == null) { currentName = GetMemberName(jsonReader); } nodeType = jsonReader.GetAttribute(TypeAttributeName) ?? StringAttributeValue; if (parent is JsonArray) { // For arrays, the element name has to be "item" if (jsonReader.Name != ItemElementName) { throw new FormatException(Properties.Resources.IncorrectJsonFormat); } } switch (nodeType) { case NullAttributeValue: case BooleanAttributeValue: case StringAttributeValue: case NumberAttributeValue: JsonPrimitive jsonPrimitive = ReadPrimitive(nodeType, jsonReader); InsertJsonValue(jsonStack, ref parent, ref currentName, jsonPrimitive, true); break; case ArrayAttributeValue: JsonArray jsonArray = CreateJsonArray(jsonReader, ref isEmptyElement); InsertJsonValue(jsonStack, ref parent, ref currentName, jsonArray, isEmptyElement); break; case ObjectAttributeValue: JsonObject jsonObject = CreateObjectWithTypeHint(jsonReader, ref isEmptyElement); InsertJsonValue(jsonStack, ref parent, ref currentName, jsonObject, isEmptyElement); break; default: throw new FormatException(Properties.Resources.IncorrectJsonFormat); } while (jsonReader.NodeType == XmlNodeType.EndElement && jsonStack.Count > 0) { jsonReader.Read(); SkipWhitespace(jsonReader); jsonStack.Pop(); if (jsonStack.Count > 0) { parent = jsonStack.Peek(); } } } } catch (XmlException xmlException) { throw new FormatException(Properties.Resources.IncorrectJsonFormat, xmlException); } if (jsonStack.Count != 1) { throw new FormatException(Properties.Resources.IncorrectJsonFormat); } return(parent[RootObjectName]); }
private bool TestPrimitiveType(string typeName) { bool retValue = true; bool specialCase = false; int seed = 1; Log.Info("Seed: {0}", seed); Random rndGen = new Random(seed); JsonPrimitive sourceJson = null; JsonPrimitive sourceJson2; object tempValue = null; switch (typeName.ToLower()) { case "boolean": tempValue = PrimitiveCreator.CreateInstanceOfBoolean(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString().ToLower()); sourceJson2 = new JsonPrimitive((bool)tempValue); break; case "byte": tempValue = PrimitiveCreator.CreateInstanceOfByte(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((byte)tempValue); break; case "char": sourceJson2 = new JsonPrimitive((char)PrimitiveCreator.CreateInstanceOfChar(rndGen)); specialCase = true; break; case "datetime": tempValue = PrimitiveCreator.CreateInstanceOfDateTime(rndGen); sourceJson2 = new JsonPrimitive((DateTime)tempValue); sourceJson = (JsonPrimitive)JsonValue.Parse(sourceJson2.ToString()); break; case "decimal": tempValue = PrimitiveCreator.CreateInstanceOfDecimal(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(((decimal)tempValue).ToString(NumberFormatInfo.InvariantInfo)); sourceJson2 = new JsonPrimitive((decimal)tempValue); break; case "double": double tempDouble = PrimitiveCreator.CreateInstanceOfDouble(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempDouble.ToString("R", NumberFormatInfo.InvariantInfo)); sourceJson2 = new JsonPrimitive(tempDouble); break; case "guid": sourceJson2 = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfGuid(rndGen)); specialCase = true; break; case "int16": tempValue = PrimitiveCreator.CreateInstanceOfInt16(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((short)tempValue); break; case "int32": tempValue = PrimitiveCreator.CreateInstanceOfInt32(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((int)tempValue); break; case "int64": tempValue = PrimitiveCreator.CreateInstanceOfInt64(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((long)tempValue); break; case "sbyte": tempValue = PrimitiveCreator.CreateInstanceOfSByte(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((sbyte)tempValue); break; case "single": float fltValue = PrimitiveCreator.CreateInstanceOfSingle(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(fltValue.ToString("R", NumberFormatInfo.InvariantInfo)); sourceJson2 = new JsonPrimitive(fltValue); break; case "string": do { tempValue = PrimitiveCreator.CreateInstanceOfString(rndGen); } while (tempValue == null); sourceJson2 = new JsonPrimitive((string)tempValue); sourceJson = (JsonPrimitive)JsonValue.Parse(sourceJson2.ToString()); break; case "uint16": tempValue = PrimitiveCreator.CreateInstanceOfUInt16(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((ushort)tempValue); break; case "uint32": tempValue = PrimitiveCreator.CreateInstanceOfUInt32(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((uint)tempValue); break; case "uint64": tempValue = PrimitiveCreator.CreateInstanceOfUInt64(rndGen); sourceJson = (JsonPrimitive)JsonValue.Parse(tempValue.ToString()); sourceJson2 = new JsonPrimitive((ulong)tempValue); break; case "uri": Uri uri = null; do { try { uri = PrimitiveCreator.CreateInstanceOfUri(rndGen); } catch (UriFormatException) { } } while (uri == null); sourceJson2 = new JsonPrimitive(uri); specialCase = true; break; case "null": sourceJson = (JsonPrimitive)JsonValue.Parse("null"); sourceJson2 = null; break; default: sourceJson = null; sourceJson2 = null; break; } if (!specialCase) { // comparison between two constructors if (!JsonValueVerifier.Compare(sourceJson, sourceJson2)) { Log.Info("(JsonPrimitive)JsonValue.Parse(string) failed to match the results from default JsonPrimitive(obj)constructor for type {0}", typeName); retValue = false; } if (sourceJson != null) { // test JsonValue.Load(TextReader) JsonPrimitive newJson = null; using (StringReader sr = new StringReader(sourceJson.ToString())) { newJson = (JsonPrimitive)JsonValue.Load(sr); } if (!JsonValueVerifier.Compare(sourceJson, newJson)) { Log.Info("JsonValue.Load(TextReader) failed to function properly for type {0}", typeName); retValue = false; } // test JsonValue.Load(Stream) is located in the JObjectFromGenoTypeLib test case // test JsonValue.Parse(string) newJson = null; newJson = (JsonPrimitive)JsonValue.Parse(sourceJson.ToString()); if (!JsonValueVerifier.Compare(sourceJson, newJson)) { Log.Info("JsonValue.Parse(string) failed to function properly for type {0}", typeName); retValue = false; } } } else { // test JsonValue.Load(TextReader) JsonPrimitive newJson2 = null; using (StringReader sr = new StringReader(sourceJson2.ToString())) { newJson2 = (JsonPrimitive)JsonValue.Load(sr); } if (!JsonValueVerifier.Compare(sourceJson2, newJson2)) { Log.Info("JsonValue.Load(TextReader) failed to function properly for type {0}", typeName); retValue = false; } // test JsonValue.Load(Stream) is located in the JObjectFromGenoTypeLib test case // test JsonValue.Parse(string) newJson2 = null; newJson2 = (JsonPrimitive)JsonValue.Parse(sourceJson2.ToString()); if (!JsonValueVerifier.Compare(sourceJson2, newJson2)) { Log.Info("JsonValue.Parse(string) failed to function properly for type {0}", typeName); retValue = false; } } return retValue; }
/// <summary> /// Gets the operation support value for the specified operation and operands. /// </summary> /// <param name="operation">The operation type.</param> /// <param name="thisValue">The JsonValue instance to check operation for.</param> /// <param name="operand">The second operand instance.</param> /// <returns>An <see cref="OperationSupport"/> value.</returns> private static OperationSupport GetBinaryOperationSupport(ExpressionType operation, JsonValue thisValue, object operand) { //// Supported binary operators: +, -, *, /, %, &, |, ^, <<, >>, ==, !=, >, <, >=, <= bool isCompareOperation = false; JsonValue otherValue = operand as JsonValue; switch (operation) { //// supported binary operations case ExpressionType.Add: case ExpressionType.Subtract: case ExpressionType.Multiply: case ExpressionType.Divide: case ExpressionType.Modulo: case ExpressionType.And: case ExpressionType.Or: case ExpressionType.ExclusiveOr: case ExpressionType.LeftShift: case ExpressionType.RightShift: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: break; //// compare operations: case ExpressionType.Equal: case ExpressionType.NotEqual: isCompareOperation = true; break; default: return(OperationSupport.NotSupported); } if (operand != null) { bool thisIsPrimitive = thisValue is JsonPrimitive; if (otherValue != null) { if (!(otherValue is JsonPrimitive) || !thisIsPrimitive) { //// When either value is non-primitive it must be a compare operation. if (!isCompareOperation) { return(OperationSupport.NotSupportedOnJsonType); } } } else { //// if operand is not a JsonValue it must be a primitive CLR type and first operand must be a JsonPrimitive. if (!thisIsPrimitive) { return(OperationSupport.NotSupportedOnJsonType); } JsonPrimitive primitiveValue = null; if (!JsonPrimitive.TryCreate(operand, out primitiveValue)) { return(OperationSupport.NotSupportedOnValueType); } } } else { //// when operand is null only compare operations are valid. if (!isCompareOperation) { return(OperationSupport.NotSupportedOnOperand); } } return(OperationSupport.Supported); }
void AddPrimitive(JsonPrimitive jsonPrimitive) { if (stack.Count == 0) root = jsonPrimitive; else { var parentContainer = stack.Peek(); parentContainer.AddChild(jsonPrimitive); } }
// Convert a string to json and parse the string, then compare the result to the original value void CheckString (string str) { var json = new JsonPrimitive (str).ToString (); // Check whether the string is valid Unicode (will throw for broken surrogate pairs) new UTF8Encoding (false, true).GetBytes (json); string jvalue = (string) JsonValue.Parse (json); Assert.AreEqual (str, jvalue); }
public static JsonPrimitive GetRandomJsonPrimitives(int seed) { JsonPrimitive myObject; Random rndGen = new Random(seed); int mod = seed % 13; switch (mod) { case 1: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfBoolean(rndGen)); break; case 2: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfByte(rndGen)); break; case 3: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfDateTime(rndGen)); break; case 4: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfDecimal(rndGen)); break; case 5: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfInt16(rndGen)); break; case 6: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfInt32(rndGen)); break; case 7: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfInt64(rndGen)); break; case 8: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfSByte(rndGen)); break; case 9: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfSingle(rndGen)); break; case 10: string temp; do { temp = PrimitiveCreator.CreateInstanceOfString(rndGen); } while (temp == null); myObject = new JsonPrimitive(temp); break; case 11: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfUInt16(rndGen)); break; case 12: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfUInt32(rndGen)); break; default: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfUInt64(rndGen)); break; } return myObject; }
static IEnumerable<EmitValue> EnumeratePrimitiveIfNotNull(JsonPrimitive primitiveValue) { if (primitiveValue == null) yield break; switch (primitiveValue.JsonType) { case JsonType.String: yield return new EmitValue(JsonToken.String, primitiveValue.Value); yield break; case JsonType.Number: yield return new EmitValue( primitiveValue.Value is int? JsonToken.Integer: JsonToken.Float, primitiveValue.Value); yield break; case JsonType.Boolean: yield return new EmitValue(JsonToken.Boolean, primitiveValue.Value); yield break; default: throw new ArgumentOutOfRangeException(); } }
public void InvalidCastTest() { JsonValue nullValue = (JsonValue)null; JsonValue strValue = new JsonPrimitive(AnyInstance.AnyString); JsonValue boolValue = new JsonPrimitive(AnyInstance.AnyBool); JsonValue intValue = new JsonPrimitive(AnyInstance.AnyInt); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (double)nullValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (double)strValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (double)boolValue; }); Assert.Equal<double>(AnyInstance.AnyInt, (double)intValue); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (float)nullValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (float)strValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (float)boolValue; }); Assert.Equal<float>(AnyInstance.AnyInt, (float)intValue); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (decimal)nullValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (decimal)strValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (decimal)boolValue; }); Assert.Equal<decimal>(AnyInstance.AnyInt, (decimal)intValue); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (long)nullValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (long)strValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (long)boolValue; }); Assert.Equal<long>(AnyInstance.AnyInt, (long)intValue); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (ulong)nullValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (ulong)strValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (ulong)boolValue; }); Assert.Equal<ulong>(AnyInstance.AnyInt, (ulong)intValue); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (int)nullValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (int)strValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (int)boolValue; }); Assert.Equal<int>(AnyInstance.AnyInt, (int)intValue); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (uint)nullValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (uint)strValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (uint)boolValue; }); Assert.Equal<uint>(AnyInstance.AnyInt, (uint)intValue); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (short)nullValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (short)strValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (short)boolValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (ushort)nullValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (ushort)strValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (ushort)boolValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (sbyte)nullValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (sbyte)strValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (sbyte)boolValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (byte)nullValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (byte)strValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (byte)boolValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (Guid)nullValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (Guid)strValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (Guid)boolValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (Guid)intValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTime)nullValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTime)strValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTime)boolValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTime)intValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (char)nullValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (char)strValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (char)boolValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (char)intValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTimeOffset)nullValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTimeOffset)strValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTimeOffset)boolValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (DateTimeOffset)intValue; }); Assert.Null((Uri)nullValue); Assert.Equal(((Uri)strValue).ToString(), (string)strValue); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (Uri)boolValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (Uri)intValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (bool)nullValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (bool)strValue; }); Assert.Equal(AnyInstance.AnyBool, (bool)boolValue); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (bool)intValue; }); Assert.Equal(null, (string)nullValue); Assert.Equal(AnyInstance.AnyString, (string)strValue); Assert.Equal(AnyInstance.AnyBool.ToString().ToLowerInvariant(), ((string)boolValue).ToLowerInvariant()); Assert.Equal(AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture), (string)intValue); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (int)nullValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (int)strValue; }); ExceptionHelper.Throws<InvalidCastException>(delegate { var v = (int)boolValue; }); Assert.Equal(AnyInstance.AnyInt, (int)intValue); }
public JsonValue containsKey(JsonValue value, string key, int type) { JsonPrimitive nullValue = new JsonPrimitive(""); switch(type) { case JSON_TYPE_INT: nullValue = new JsonPrimitive(0); break; case 1: nullValue = new JsonPrimitive(""); break; case 2: nullValue = new JsonPrimitive(new DateTime()); break; } if(value == null) return nullValue; return (value.ContainsKey(key)) ? value[key] : nullValue; }
public void ValidJsonObjectDateTimeOffsetRoundTrip() { int seed = 1; Log.Info("Seed: {0}", seed); Random rndGen = new Random(seed); JsonPrimitive sourceJson = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfDateTimeOffset(rndGen)); JsonPrimitive newJson = (JsonPrimitive)JsonValue.Parse(sourceJson.ToString()); if (!JsonValueVerifier.Compare(sourceJson, newJson)) { Assert.Fail("Test failed! The new JsonObject DateTimeOffset value does not equal to the original one."); } }
public void InvalidCastTest() { JsonValue nullValue = (JsonValue)null; JsonValue strValue = new JsonPrimitive(AnyInstance.AnyString); JsonValue boolValue = new JsonPrimitive(AnyInstance.AnyBool); JsonValue intValue = new JsonPrimitive(AnyInstance.AnyInt); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (double)nullValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (double)strValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (double)boolValue; }); Assert.Equal <double>(AnyInstance.AnyInt, (double)intValue); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (float)nullValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (float)strValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (float)boolValue; }); Assert.Equal <float>(AnyInstance.AnyInt, (float)intValue); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (decimal)nullValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (decimal)strValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (decimal)boolValue; }); Assert.Equal <decimal>(AnyInstance.AnyInt, (decimal)intValue); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (long)nullValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (long)strValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (long)boolValue; }); Assert.Equal <long>(AnyInstance.AnyInt, (long)intValue); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (ulong)nullValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (ulong)strValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (ulong)boolValue; }); Assert.Equal <ulong>(AnyInstance.AnyInt, (ulong)intValue); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (int)nullValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (int)strValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (int)boolValue; }); Assert.Equal <int>(AnyInstance.AnyInt, (int)intValue); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (uint)nullValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (uint)strValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (uint)boolValue; }); Assert.Equal <uint>(AnyInstance.AnyInt, (uint)intValue); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (short)nullValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (short)strValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (short)boolValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (ushort)nullValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (ushort)strValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (ushort)boolValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (sbyte)nullValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (sbyte)strValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (sbyte)boolValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (byte)nullValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (byte)strValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (byte)boolValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (Guid)nullValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (Guid)strValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (Guid)boolValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (Guid)intValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (DateTime)nullValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (DateTime)strValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (DateTime)boolValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (DateTime)intValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (char)nullValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (char)strValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (char)boolValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (char)intValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (DateTimeOffset)nullValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (DateTimeOffset)strValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (DateTimeOffset)boolValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (DateTimeOffset)intValue; }); Assert.Null((Uri)nullValue); Assert.Equal(((Uri)strValue).ToString(), (string)strValue); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (Uri)boolValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (Uri)intValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (bool)nullValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (bool)strValue; }); Assert.Equal(AnyInstance.AnyBool, (bool)boolValue); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (bool)intValue; }); Assert.Equal(null, (string)nullValue); Assert.Equal(AnyInstance.AnyString, (string)strValue); Assert.Equal(AnyInstance.AnyBool.ToString().ToLowerInvariant(), ((string)boolValue).ToLowerInvariant()); Assert.Equal(AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture), (string)intValue); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (int)nullValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (int)strValue; }); ExceptionHelper.Throws <InvalidCastException>(delegate { var v = (int)boolValue; }); Assert.Equal(AnyInstance.AnyInt, (int)intValue); }
public void JsonObjectItemsFunctionalTest() { int seed = 1; for (int i = 0; i < iterationCount / 10; i++) { seed++; Log.Info("Seed: {0}", seed); Random rndGen = new Random(seed); bool retValue = true; JsonObject sourceJson = SpecialJsonValueHelper.CreateIndexPopulatedJsonObject(seed, arrayLength); // JsonObject[key].set_Item sourceJson["1"] = new JsonPrimitive(true); if (sourceJson["1"].ToString() != "true") { Log.Info("[JsonObjectItemsFunctionalTest] JsonObject[key].set_Item failed to function properly."); retValue = false; } else { Log.Info("[JsonObjectItemsFunctionalTest] JsonObject[key].set_Item passed test."); } // ICollection<KeyValuePair<string, JsonValue>>.Contains(KeyValuePair<string, JsonValue> item) KeyValuePair <string, System.Json.JsonValue> kp = new KeyValuePair <string, JsonValue>("5", sourceJson["5"]); if (!((ICollection <KeyValuePair <string, JsonValue> >)sourceJson).Contains(kp)) { Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.Contains(KeyValuePair<string, JsonValue> item) failed to function properly."); retValue = false; } else { Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.Contains(KeyValuePair<string, JsonValue> item) passed test."); } // ICollection<KeyValuePair<string, JsonValue>>.IsReadOnly if (((ICollection <KeyValuePair <string, JsonValue> >)sourceJson).IsReadOnly) { Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.IsReadOnly failed to function properly."); retValue = false; } else { Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.IsReadOnly passed test."); } // ICollection<KeyValuePair<string, JsonValue>>.Add(KeyValuePair<string, JsonValue> item) kp = new KeyValuePair <string, JsonValue>("100", new JsonPrimitive(100)); ((ICollection <KeyValuePair <string, JsonValue> >)sourceJson).Add(kp); if (sourceJson.Count != arrayLength + 1) { Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.Add(KeyValuePair<string, JsonValue> item) failed to function properly."); retValue = false; } else { Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.Add(KeyValuePair<string, JsonValue> item) passed test."); } // ICollection<KeyValuePair<string, JsonValue>>.Remove(KeyValuePair<string, JsonValue> item) ((ICollection <KeyValuePair <string, JsonValue> >)sourceJson).Remove(kp); if (sourceJson.Count != arrayLength) { Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.Remove(KeyValuePair<string, JsonValue> item) failed to function properly."); retValue = false; } else { Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.Remove(KeyValuePair<string, JsonValue> item) passed test."); } // ICollection<KeyValuePair<string, JsonValue>>.GetEnumerator() JsonObject jo = new JsonObject { { "member 1", 123 }, { "member 2", new JsonArray { 1, 2, 3 } } }; List <string> expected = new List <string> { "member 1 - 123", "member 2 - [1,2,3]" }; expected.Sort(); IEnumerator <KeyValuePair <string, JsonValue> > ko = ((ICollection <KeyValuePair <string, JsonValue> >)jo).GetEnumerator(); List <string> actual = new List <string>(); ko.Reset(); ko.MoveNext(); do { actual.Add(String.Format("{0} - {1}", ko.Current.Key, ko.Current.Value.ToString())); Log.Info("added one item: {0}", String.Format("{0} - {1}", ko.Current.Key, ko.Current.Value)); ko.MoveNext(); }while (ko.Current.Value != null); actual.Sort(); if (!JsonValueVerifier.CompareStringLists(expected, actual)) { Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.GetEnumerator() failed to function properly."); retValue = false; } else { Log.Info("[JsonObjectItemsFunctionalTest] ICollection<KeyValuePair<string, JsonValue>>.GetEnumerator() passed test."); } // JsonObject.Values sourceJson = SpecialJsonValueHelper.CreateIndexPopulatedJsonObject(seed, arrayLength); JsonValue[] manyValues = SpecialJsonValueHelper.CreatePrePopulatedJsonValueArray(seed, arrayLength); JsonObject jov = new JsonObject(); for (int j = 0; j < manyValues.Length; j++) { jov.Add("member" + j, manyValues[j]); } List <string> expectedList = new List <string>(); foreach (JsonValue v in manyValues) { expectedList.Add(v.ToString()); } expectedList.Sort(); List <string> actualList = new List <string>(); foreach (JsonValue v in jov.Values) { actualList.Add(v.ToString()); } actualList.Sort(); if (!JsonValueVerifier.CompareStringLists(expectedList, actualList)) { Log.Info("[JsonObjectItemsFunctionalTest] JsonObject.Values failed to function properly."); retValue = false; } else { Log.Info("[JsonObjectItemsFunctionalTest] JsonObject.Values passed test."); } for (int j = 0; j < sourceJson.Count; j++) { // JsonObject.Contains(Key) if (!sourceJson.ContainsKey(j.ToString())) { Log.Info("[JsonObjectItemsFunctionalTest] JsonObject.Contains(Key) failed to function properly."); retValue = false; } else { Log.Info("[JsonObjectItemsFunctionalTest] JsonObject.Contains(Key) passed test."); } // JsonObject.TryGetValue(String, out JsonValue) JsonValue retJson; if (!sourceJson.TryGetValue(j.ToString(), out retJson)) { Log.Info("[JsonObjectItemsFunctionalTest] JsonObject.TryGetValue(String, out JsonValue) failed to function properly."); retValue = false; } else if (retJson != sourceJson[j.ToString()]) { // JsonObjectthis[string key] Log.Info("[JsonObjectItemsFunctionalTest] JsonObject[string key] or JsonObject.TryGetValue(String, out JsonValue) failed to function properly."); retValue = false; } else { Log.Info("[JsonObjectItemsFunctionalTest] JsonObject.TryGetValue(String, out JsonValue) & JsonObject[string key] passed test."); } } Assert.True(retValue); } }
public void ReadAsTest() { JsonValue target = new JsonPrimitive(AnyInstance.AnyInt); Assert.Equal(AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture), target.ReadAs(typeof(string))); Assert.Equal(AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture), target.ReadAs<string>()); object value; double dblValue; Assert.True(target.TryReadAs(typeof(double), out value)); Assert.True(target.TryReadAs<double>(out dblValue)); Assert.Equal(Convert.ToDouble(AnyInstance.AnyInt, CultureInfo.InvariantCulture), (double)value); Assert.Equal(Convert.ToDouble(AnyInstance.AnyInt, CultureInfo.InvariantCulture), dblValue); Assert.False(target.TryReadAs(typeof(Guid), out value), "TryReadAs should have failed to read a double as a Guid"); Assert.Null(value); }
public void BindUnaryOperationTest() { JsonValue value; DynamicMetaObject target; value = new JsonPrimitive(AnyInstance.AnyInt); target = GetJsonValueDynamicMetaObject(value); TestUnaryOperationBinder.TestBindParams(target); TestUnaryOperationBinder.TestMetaObject(target, TestUnaryOperationBinder.NumberOperations); value = new JsonPrimitive(AnyInstance.AnyBool); target = GetJsonValueDynamicMetaObject(value); TestUnaryOperationBinder.TestMetaObject(target, TestUnaryOperationBinder.BooleanOperations); }
public void StringToNonNumberConversionTest() { const string DateTimeWithOffsetFormat = "yyyy-MM-ddTHH:mm:sszzz"; const string DateTimeWithOffsetFormat2 = "yyy-MM-ddTHH:mm:ss.fffK"; const string DateTimeWithoutOffsetWithoutTimeFormat = "yyy-MM-dd"; const string DateTimeWithoutOffsetFormat = "yyy-MM-ddTHH:mm:ss"; const string DateTimeWithoutOffsetFormat2 = "yyy-MM-ddTHH:mm:ss.fff"; const string TimeWithoutOffsetFormat = "HH:mm:ss"; const string TimeWithoutOffsetFormat2 = "HH:mm"; Assert.AreEqual(false, new JsonPrimitive("false").ReadAs<bool>()); Assert.AreEqual(false, (bool)(new JsonPrimitive("False"))); Assert.AreEqual(true, (bool)(new JsonPrimitive("true"))); Assert.AreEqual(true, new JsonPrimitive("True").ReadAs<bool>()); Assert.AreEqual<Uri>(AnyInstance.AnyUri, new JsonPrimitive(AnyInstance.AnyUri.ToString()).ReadAs<Uri>()); Assert.AreEqual<char>(AnyInstance.AnyChar, (char)(new JsonPrimitive(new string(AnyInstance.AnyChar, 1)))); Assert.AreEqual<Guid>(AnyInstance.AnyGuid, (Guid)(new JsonPrimitive(AnyInstance.AnyGuid.ToString("D", CultureInfo.InvariantCulture)))); DateTime anyLocalDateTime = AnyInstance.AnyDateTime.ToLocalTime(); DateTime anyUtcDateTime = AnyInstance.AnyDateTime.ToUniversalTime(); Assert.AreEqual<DateTime>(anyUtcDateTime, (DateTime)(new JsonPrimitive(anyUtcDateTime.ToString(DateTimeFormat, CultureInfo.InvariantCulture)))); Assert.AreEqual<DateTime>(anyLocalDateTime, new JsonPrimitive(anyLocalDateTime.ToString(DateTimeWithOffsetFormat2, CultureInfo.InvariantCulture)).ReadAs<DateTime>()); Assert.AreEqual<DateTime>(anyUtcDateTime, new JsonPrimitive(anyUtcDateTime.ToString(DateTimeWithOffsetFormat2, CultureInfo.InvariantCulture)).ReadAs<DateTime>()); Assert.AreEqual<DateTime>(anyLocalDateTime.Date, (DateTime)(new JsonPrimitive(anyLocalDateTime.ToString(DateTimeWithoutOffsetWithoutTimeFormat, CultureInfo.InvariantCulture)))); Assert.AreEqual<DateTime>(anyLocalDateTime, new JsonPrimitive(anyLocalDateTime.ToString(DateTimeWithoutOffsetFormat, CultureInfo.InvariantCulture)).ReadAs<DateTime>()); Assert.AreEqual<DateTime>(anyLocalDateTime, new JsonPrimitive(anyLocalDateTime.ToString(DateTimeWithoutOffsetFormat2, CultureInfo.InvariantCulture)).ReadAs<DateTime>()); DateTime dt = new JsonPrimitive(anyLocalDateTime.ToString(TimeWithoutOffsetFormat, CultureInfo.InvariantCulture)).ReadAs<DateTime>(); Assert.AreEqual(anyLocalDateTime.Hour, dt.Hour); Assert.AreEqual(anyLocalDateTime.Minute, dt.Minute); Assert.AreEqual(anyLocalDateTime.Second, dt.Second); dt = new JsonPrimitive(anyLocalDateTime.ToString(TimeWithoutOffsetFormat2, CultureInfo.InvariantCulture)).ReadAs<DateTime>(); Assert.AreEqual(anyLocalDateTime.Hour, dt.Hour); Assert.AreEqual(anyLocalDateTime.Minute, dt.Minute); Assert.AreEqual(0, dt.Second); Assert.AreEqual<DateTimeOffset>(AnyInstance.AnyDateTimeOffset, new JsonPrimitive(AnyInstance.AnyDateTimeOffset.ToString(DateTimeFormat, CultureInfo.InvariantCulture)).ReadAs<DateTimeOffset>()); Assert.AreEqual<DateTimeOffset>(AnyInstance.AnyDateTimeOffset, new JsonPrimitive(AnyInstance.AnyDateTimeOffset.ToString(DateTimeWithOffsetFormat, CultureInfo.InvariantCulture)).ReadAs<DateTimeOffset>()); Assert.AreEqual<DateTimeOffset>(AnyInstance.AnyDateTimeOffset, new JsonPrimitive(AnyInstance.AnyDateTimeOffset.ToString(DateTimeWithOffsetFormat2, CultureInfo.InvariantCulture)).ReadAs<DateTimeOffset>()); Assert.AreEqual<DateTimeOffset>(AnyInstance.AnyDateTimeOffset.ToLocalTime(), (DateTimeOffset)(new JsonPrimitive(AnyInstance.AnyDateTimeOffset.ToLocalTime().ToString(DateTimeWithoutOffsetFormat, CultureInfo.InvariantCulture)))); Assert.AreEqual<DateTimeOffset>(AnyInstance.AnyDateTimeOffset.ToLocalTime(), (DateTimeOffset)(new JsonPrimitive(AnyInstance.AnyDateTimeOffset.ToLocalTime().ToString(DateTimeWithoutOffsetFormat2, CultureInfo.InvariantCulture)))); DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(DateTime)); MemoryStream ms = new MemoryStream(); dcjs.WriteObject(ms, AnyInstance.AnyDateTime); string dcjsSerializedDateTime = Encoding.UTF8.GetString(ms.ToArray()); Assert.AreEqual(AnyInstance.AnyDateTime, JsonValue.Parse(dcjsSerializedDateTime).ReadAs<DateTime>()); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { var b = (bool)(new JsonPrimitive("notBool")); }); ExceptionTestHelper.ExpectException<UriFormatException>(delegate { var u = new JsonPrimitive("not an uri - " + new string('r', 100000)).ReadAs<Uri>(); }); ExceptionTestHelper.ExpectException<FormatException>(delegate { var date = new JsonPrimitive("not a date time").ReadAs<DateTime>(); }); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { var dto = (DateTimeOffset)(new JsonPrimitive("not a date time offset")); }); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { var c = (char)new JsonPrimitive(""); }); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { var c = (char)new JsonPrimitive("cc"); }); ExceptionTestHelper.ExpectException<FormatException>(delegate { var g = new JsonPrimitive("not a guid").ReadAs<Guid>(); }); }
public void DynamicBooleanOperators() { JsonValue jv; dynamic dyn; foreach (bool value in new bool[] { true, false }) { jv = value; dyn = jv; Log.Info("IsTrue, {0}", jv); if (dyn) { Assert.True(value, "Boolean evaluation should not enter 'if' clause."); } else { Assert.False(value, "Boolean evaluation should not enter 'else' clause."); } } foreach (string value in new string[] { "true", "false", "True", "False" }) { bool isTrueValue = value.Equals("true", StringComparison.InvariantCultureIgnoreCase); jv = new JsonPrimitive(value); dyn = jv; Log.Info("IsTrue, {0}", jv); if (dyn) { Assert.True(isTrueValue, "Boolean evaluation should not enter 'if' clause."); } else { Assert.False(isTrueValue, "Boolean evaluation should not enter 'else' clause."); } } foreach (bool first in new bool[] { false, true }) { dynamic dyn1 = new JsonPrimitive(first); Log.Info("Negation, {0}", first); Assert.Equal(!first, !dyn1); foreach (bool second in new bool[] { false, true }) { dynamic dyn2 = new JsonPrimitive(second); Log.Info("Boolean AND, {0} && {1}", first, second); Assert.Equal(first && second, (bool)(dyn1 && dyn2)); Log.Info("Boolean OR, {0} && {1}", first, second); Assert.Equal(first || second, (bool)(dyn1 || dyn2)); } } Log.Info("Invalid boolean operator usage"); dynamic boolDyn = new JsonPrimitive(true); dynamic intDyn = new JsonPrimitive(1); dynamic strDyn = new JsonPrimitive("hello"); JsonValueTests.ExpectException <InvalidOperationException>(() => { Log.Info("{0}", !intDyn); }); JsonValueTests.ExpectException <InvalidOperationException>(() => { Log.Info("{0}", !strDyn); }); JsonValueTests.ExpectException <InvalidCastException>(() => { Log.Info("{0}", intDyn && intDyn); }); JsonValueTests.ExpectException <InvalidCastException>(() => { Log.Info("{0}", intDyn || true); }); JsonValueTests.ExpectException <InvalidOperationException>(() => { Log.Info("{0}", boolDyn && 1); }); JsonValueTests.ExpectException <InvalidOperationException>(() => { Log.Info("{0}", boolDyn && intDyn); }); JsonValueTests.ExpectException <InvalidOperationException>(() => { Log.Info("{0}", boolDyn && "hello"); }); JsonValueTests.ExpectException <InvalidOperationException>(() => { Log.Info("{0}", boolDyn && strDyn); }); JsonValueTests.ExpectException <FormatException>(() => { Log.Info("{0}", strDyn && boolDyn); }); JsonValueTests.ExpectException <FormatException>(() => { Log.Info("{0}", strDyn || true); }); JsonValueTests.ExpectException <InvalidOperationException>(() => { Log.Info("{0}", !intDyn.NotHere); }); JsonValueTests.ExpectException <InvalidOperationException>(() => { Log.Info("{0}", !intDyn.NotHere && true); }); JsonValueTests.ExpectException <InvalidOperationException>(() => { Log.Info("{0}", !intDyn.NotHere || false); }); }
public void NonNumberToNumberConversionTest() { Assert.AreEqual(1, new JsonPrimitive('1').ReadAs<int>()); Assert.AreEqual<byte>(AnyInstance.AnyByte, new JsonPrimitive(AnyInstance.AnyByte.ToString(CultureInfo.InvariantCulture)).ReadAs<byte>()); Assert.AreEqual<sbyte>(AnyInstance.AnySByte, (sbyte)(new JsonPrimitive(AnyInstance.AnySByte.ToString(CultureInfo.InvariantCulture)))); Assert.AreEqual<short>(AnyInstance.AnyShort, (short)(new JsonPrimitive(AnyInstance.AnyShort.ToString(CultureInfo.InvariantCulture)))); Assert.AreEqual<ushort>(AnyInstance.AnyUShort, new JsonPrimitive(AnyInstance.AnyUShort.ToString(CultureInfo.InvariantCulture)).ReadAs<ushort>()); Assert.AreEqual<int>(AnyInstance.AnyInt, new JsonPrimitive(AnyInstance.AnyInt.ToString(CultureInfo.InvariantCulture)).ReadAs<int>()); Assert.AreEqual<uint>(AnyInstance.AnyUInt, (uint)(new JsonPrimitive(AnyInstance.AnyUInt.ToString(CultureInfo.InvariantCulture)))); Assert.AreEqual<long>(AnyInstance.AnyLong, (long)(new JsonPrimitive(AnyInstance.AnyLong.ToString(CultureInfo.InvariantCulture)))); Assert.AreEqual<ulong>(AnyInstance.AnyULong, new JsonPrimitive(AnyInstance.AnyULong.ToString(CultureInfo.InvariantCulture)).ReadAs<ulong>()); Assert.AreEqual<decimal>(AnyInstance.AnyDecimal, (decimal)(new JsonPrimitive(AnyInstance.AnyDecimal.ToString(CultureInfo.InvariantCulture)))); Assert.AreEqual<float>(AnyInstance.AnyFloat, new JsonPrimitive(AnyInstance.AnyFloat.ToString(CultureInfo.InvariantCulture)).ReadAs<float>()); Assert.AreEqual<double>(AnyInstance.AnyDouble, (double)(new JsonPrimitive(AnyInstance.AnyDouble.ToString(CultureInfo.InvariantCulture)))); Assert.AreEqual<byte>(Convert.ToByte(1.23, CultureInfo.InvariantCulture), new JsonPrimitive("1.23").ReadAs<byte>()); Assert.AreEqual<int>(Convert.ToInt32(12345.6789, CultureInfo.InvariantCulture), new JsonPrimitive("12345.6789").ReadAs<int>()); Assert.AreEqual<short>(Convert.ToInt16(1.23e2), (short)new JsonPrimitive("1.23e2")); Assert.AreEqual<float>(Convert.ToSingle(1.23e40), (float)new JsonPrimitive("1.23e40")); Assert.AreEqual<float>(Convert.ToSingle(1.23e-38), (float)new JsonPrimitive("1.23e-38")); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyBool).ReadAs<sbyte>(); }); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyBool).ReadAs<short>(); }); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyBool).ReadAs<uint>(); }); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyBool).ReadAs<long>(); }); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyBool).ReadAs<double>(); }); ExceptionTestHelper.ExpectException<FormatException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyUri).ReadAs<int>(); }); ExceptionTestHelper.ExpectException<FormatException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyDateTime).ReadAs<float>(); }); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { var n = (decimal)(new JsonPrimitive('c')); }); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { var n = (byte)(new JsonPrimitive("0xFF")); }); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { var n = (sbyte)(new JsonPrimitive(AnyInstance.AnyDateTimeOffset)); }); ExceptionTestHelper.ExpectException<FormatException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyUri).ReadAs<uint>(); }); ExceptionTestHelper.ExpectException<FormatException>(delegate { var n = new JsonPrimitive(AnyInstance.AnyDateTime).ReadAs<double>(); }); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { var n = (long)(new JsonPrimitive('c')); }); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { var n = (ulong)(new JsonPrimitive("0xFF")); }); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { var n = (short)(new JsonPrimitive(AnyInstance.AnyDateTimeOffset)); }); ExceptionTestHelper.ExpectException<InvalidCastException>(delegate { var n = (ushort)(new JsonPrimitive('c')); }); ExceptionTestHelper.ExpectException<OverflowException>(delegate { int i = (int)new JsonPrimitive((1L << 32).ToString(CultureInfo.InvariantCulture)); }); ExceptionTestHelper.ExpectException<OverflowException>(delegate { byte b = (byte)new JsonPrimitive("-1"); }); }
// the input JsonPrimitive DateTime format is "\/Date(24735422733034-0700)\/" or "\/Date(24735422733034)\/" // the only thing useful for us is the UTC ticks "24735422733034" // everything after - if present - is just an optional offset between the local time and UTC private static string GetUTCTicks(JsonPrimitive jprim) { string retValue = string.Empty; string origStr = jprim.ToString(); int startIndex = origStr.IndexOf("Date(") + 5; int endIndex = origStr.IndexOf('-', startIndex + 1); // the UTC ticks can start with a '-' sign (dates prior to 1970/01/01) // if the optional offset is present in the data format, we want to take only the UTC ticks if (startIndex < endIndex) { retValue = origStr.Substring(startIndex, endIndex - startIndex); } else { // otherwise we assume the time format is without the oiptional offset, or unexpected, and use the whole string for comparison. retValue = origStr; } return retValue; }
public void StringToNonNumberConversionTest() { const string DateTimeWithOffsetFormat = "yyyy-MM-ddTHH:mm:sszzz"; const string DateTimeWithOffsetFormat2 = "yyy-MM-ddTHH:mm:ss.fffK"; const string DateTimeWithoutOffsetWithoutTimeFormat = "yyy-MM-dd"; const string DateTimeWithoutOffsetFormat = "yyy-MM-ddTHH:mm:ss"; const string DateTimeWithoutOffsetFormat2 = "yyy-MM-ddTHH:mm:ss.fff"; const string TimeWithoutOffsetFormat = "HH:mm:ss"; const string TimeWithoutOffsetFormat2 = "HH:mm"; Assert.Equal(false, new JsonPrimitive("false").ReadAs <bool>()); Assert.Equal(false, (bool)(new JsonPrimitive("False"))); Assert.Equal(true, (bool)(new JsonPrimitive("true"))); Assert.Equal(true, new JsonPrimitive("True").ReadAs <bool>()); Assert.Equal <Uri>(AnyInstance.AnyUri, new JsonPrimitive(AnyInstance.AnyUri.ToString()).ReadAs <Uri>()); Assert.Equal <char>(AnyInstance.AnyChar, (char)(new JsonPrimitive(new string(AnyInstance.AnyChar, 1)))); Assert.Equal <Guid>(AnyInstance.AnyGuid, (Guid)(new JsonPrimitive(AnyInstance.AnyGuid.ToString("D", CultureInfo.InvariantCulture)))); DateTime anyLocalDateTime = AnyInstance.AnyDateTime.ToLocalTime(); DateTime anyUtcDateTime = AnyInstance.AnyDateTime.ToUniversalTime(); Assert.Equal <DateTime>(anyUtcDateTime, (DateTime)(new JsonPrimitive(anyUtcDateTime.ToString(DateTimeFormat, CultureInfo.InvariantCulture)))); Assert.Equal <DateTime>(anyLocalDateTime, new JsonPrimitive(anyLocalDateTime.ToString(DateTimeWithOffsetFormat2, CultureInfo.InvariantCulture)).ReadAs <DateTime>()); Assert.Equal <DateTime>(anyUtcDateTime, new JsonPrimitive(anyUtcDateTime.ToString(DateTimeWithOffsetFormat2, CultureInfo.InvariantCulture)).ReadAs <DateTime>()); Assert.Equal <DateTime>(anyLocalDateTime.Date, (DateTime)(new JsonPrimitive(anyLocalDateTime.ToString(DateTimeWithoutOffsetWithoutTimeFormat, CultureInfo.InvariantCulture)))); Assert.Equal <DateTime>(anyLocalDateTime, new JsonPrimitive(anyLocalDateTime.ToString(DateTimeWithoutOffsetFormat, CultureInfo.InvariantCulture)).ReadAs <DateTime>()); Assert.Equal <DateTime>(anyLocalDateTime, new JsonPrimitive(anyLocalDateTime.ToString(DateTimeWithoutOffsetFormat2, CultureInfo.InvariantCulture)).ReadAs <DateTime>()); DateTime dt = new JsonPrimitive(anyLocalDateTime.ToString(TimeWithoutOffsetFormat, CultureInfo.InvariantCulture)).ReadAs <DateTime>(); Assert.Equal(anyLocalDateTime.Hour, dt.Hour); Assert.Equal(anyLocalDateTime.Minute, dt.Minute); Assert.Equal(anyLocalDateTime.Second, dt.Second); dt = new JsonPrimitive(anyLocalDateTime.ToString(TimeWithoutOffsetFormat2, CultureInfo.InvariantCulture)).ReadAs <DateTime>(); Assert.Equal(anyLocalDateTime.Hour, dt.Hour); Assert.Equal(anyLocalDateTime.Minute, dt.Minute); Assert.Equal(0, dt.Second); Assert.Equal <DateTimeOffset>(AnyInstance.AnyDateTimeOffset, new JsonPrimitive(AnyInstance.AnyDateTimeOffset.ToString(DateTimeFormat, CultureInfo.InvariantCulture)).ReadAs <DateTimeOffset>()); Assert.Equal <DateTimeOffset>(AnyInstance.AnyDateTimeOffset, new JsonPrimitive(AnyInstance.AnyDateTimeOffset.ToString(DateTimeWithOffsetFormat, CultureInfo.InvariantCulture)).ReadAs <DateTimeOffset>()); Assert.Equal <DateTimeOffset>(AnyInstance.AnyDateTimeOffset, new JsonPrimitive(AnyInstance.AnyDateTimeOffset.ToString(DateTimeWithOffsetFormat2, CultureInfo.InvariantCulture)).ReadAs <DateTimeOffset>()); Assert.Equal <DateTimeOffset>(AnyInstance.AnyDateTimeOffset.ToLocalTime(), (DateTimeOffset)(new JsonPrimitive(AnyInstance.AnyDateTimeOffset.ToLocalTime().ToString(DateTimeWithoutOffsetFormat, CultureInfo.InvariantCulture)))); Assert.Equal <DateTimeOffset>(AnyInstance.AnyDateTimeOffset.ToLocalTime(), (DateTimeOffset)(new JsonPrimitive(AnyInstance.AnyDateTimeOffset.ToLocalTime().ToString(DateTimeWithoutOffsetFormat2, CultureInfo.InvariantCulture)))); DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(DateTime)); MemoryStream ms = new MemoryStream(); dcjs.WriteObject(ms, AnyInstance.AnyDateTime); string dcjsSerializedDateTime = Encoding.UTF8.GetString(ms.ToArray()); Assert.Equal(AnyInstance.AnyDateTime, JsonValue.Parse(dcjsSerializedDateTime).ReadAs <DateTime>()); ExceptionHelper.Throws <InvalidCastException>(delegate { var b = (bool)(new JsonPrimitive("notBool")); }); ExceptionHelper.Throws <UriFormatException>(delegate { var u = new JsonPrimitive("not an uri - " + new string('r', 100000)).ReadAs <Uri>(); }); ExceptionHelper.Throws <FormatException>(delegate { var date = new JsonPrimitive("not a date time").ReadAs <DateTime>(); }); ExceptionHelper.Throws <InvalidCastException>(delegate { var dto = (DateTimeOffset)(new JsonPrimitive("not a date time offset")); }); ExceptionHelper.Throws <InvalidCastException>(delegate { var c = (char)new JsonPrimitive(""); }); ExceptionHelper.Throws <InvalidCastException>(delegate { var c = (char)new JsonPrimitive("cc"); }); ExceptionHelper.Throws <FormatException>(delegate { var g = new JsonPrimitive("not a guid").ReadAs <Guid>(); }); }
public object FromPrimitive(JsonPrimitive value) { return this.m_from(value); }
public static JsonPrimitive GetRandomJsonPrimitives(int seed) { JsonPrimitive myObject; Random rndGen = new Random(seed); int mod = seed % 13; switch (mod) { case 1: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfBoolean(rndGen)); break; case 2: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfByte(rndGen)); break; case 3: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfDateTime(rndGen)); break; case 4: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfDecimal(rndGen)); break; case 5: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfInt16(rndGen)); break; case 6: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfInt32(rndGen)); break; case 7: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfInt64(rndGen)); break; case 8: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfSByte(rndGen)); break; case 9: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfSingle(rndGen)); break; case 10: string temp; do { temp = PrimitiveCreator.CreateInstanceOfString(rndGen); }while (temp == null); myObject = new JsonPrimitive(temp); break; case 11: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfUInt16(rndGen)); break; case 12: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfUInt32(rndGen)); break; default: myObject = new JsonPrimitive(PrimitiveCreator.CreateInstanceOfUInt64(rndGen)); break; } return(myObject); }