Пример #1
1
        public void ParseMultipartWithSuccess()
        {
            var reader = new JSonReader(true);

            var data1 = reader.Read("[1][2]");

            Assert.IsNotNull(data1);
            Assert.AreEqual(1, (long)((object[])data1)[0]);

            var data2 = reader.Read();
            Assert.IsNotNull(data2);
            Assert.AreEqual(2, (long)((object[])data2)[0]);
        }
Пример #2
0
        public void ParseISODateWithoutTimeZone()
        {
            var reader = new JSonReader("\"2012-05-17 09:58:33\"");
            var item = reader.ReadAsJSonObject();
            var date = item.DateTimeValue;

            Assert.AreEqual(new DateTime(2012, 05, 17, 09, 58, 33, DateTimeKind.Local), date);
        }
Пример #3
0
        public void ParseDateWithoutTimeAsUnspecified()
        {
            var reader = new JSonReader("\"1999-01-07\"");
            var item = reader.ReadAsJSonObject();
            var date = item.DateTimeValue;

            Assert.AreEqual(new DateTime(1999, 01, 07, 0, 0, 0, DateTimeKind.Unspecified), date);
        }
Пример #4
0
        public void ParseISODateWithTimeZone()
        {
            var reader = new JSonReader("\"2012-06-16T21:09:45+00:00\"");
            var item = reader.ReadAsJSonObject();
            var date = item.DateTimeValue;

            Assert.AreEqual(new DateTime(2012, 06, 16, 21, 9, 45, DateTimeKind.Utc).ToLocalTime(), date);
        }
        public void ReadMutableJSonAndUpdateIt()
        {
            const string jsonText = "[{\"minimumVersion\":\"1.0\",\"type\": null,\"channel\":\"\\/meta\\/handshake\",\"supportedConnectionTypes\":[\"request-response\"],\"successful\":true}]";

            var reader = new JSonReader(jsonText);
            var result = reader.ReadAsJSonMutableObject();

            Assert.IsNotNull(result, "Invalid data read!");
            Assert.AreEqual("1.0", result[0]["minimumVersion"].StringValue, "Expected other value for minimumVersion!");

            result[0].AsMutable.SetValue("minimumVersion", "2.0");
            Assert.AreEqual("2.0", result[0]["minimumVersion"].StringValue, "Expected updated value of minimumVersion!");

            result[0].AsMutable.Remove("minimumVersion");
            Assert.IsFalse(result[0].Contains("minimumVersion"), "Shoudn't contain the minimumVersion field!");
        }
Пример #6
0
    IEnumerator StartSyncServerTime()
    {
        WWW www = new WWW(AssetBundleManager.server_url + "currentTime.txt");//new WWW("http://203.195.200.120/hulu/currentTime");

        yield return(www);

        if (string.IsNullOrEmpty(www.error))
        {
            string timestr = www.text;
            CodeTitans.JSon.IJSonObject timeData = new CodeTitans.JSon.JSonReader().ReadAsJSonObject(timestr);
            int timestamp = timeData["time"].Int32Value;
            SetGameTime(timestamp);
        }

        www.Dispose();
        www = null;
    }
Пример #7
0
        public void ParseSerializedCurrentDateAsISO()
        {
            var writer = new JSonWriter();
            var now = DateTime.Now;

            // remove miliseconds:
            now = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, 0, now.Kind);

            using(writer.WriteObject())
                writer.WriteMember("date", now);
            
            var reader = new JSonReader(writer.ToString());
            var item = reader.ReadAsJSonObject();
            var date = item["date"].DateTimeValue;

            Assert.AreEqual(now, date);
        }
Пример #8
0
 public void ParseNumberWithInt64Forced_AndFail()
 {
     try
     {
         var reader = new JSonReader("[" + ulong.MaxValue + "]");
         reader.ReadAsJSonObject(JSonReaderNumberFormat.AsInt64);
     }
     catch (JSonReaderException ex)
     {
         Assert.AreEqual(0, ex.Line);
         Assert.AreEqual(1, ex.Offset);
         throw;
     }
 }
Пример #9
0
        /// <summary>
        /// Init constructor.
        /// </summary>
        public BayeuxConnection(IHttpDataSource connection, IHttpDataSource longPollingConnection)
        {
            if (connection == null)
                throw new ArgumentNullException("connection");

            _syncObject = new object();
            _writerCache = new StringBuilder();
            _jsonWriter = new JSonWriter(_writerCache, false);
            _jsonWriter.CompactEnumerables = true;
            _jsonReader = new JSonReader();
            _state = BayeuxConnectionState.Disconnected;
            _subscribedChannels = new List<string>();
            LongPollingRetryDelay = DefaultRetryDelay;
            LongPollingConnectRetries = DefaultNumberOfConnectRetries;

            _httpConnection = connection;
            _httpConnection.DataReceived += DataSource_OnDataReceived;
            _httpConnection.DataReceiveFailed += DataSource_OnDataReceiveFailed;

            if (longPollingConnection != null)
            {
                _httpLongPollingConnection = longPollingConnection;
                _httpLongPollingConnection.DataReceived += LongPollingDataSource_OnDataReceived;
                _httpLongPollingConnection.DataReceiveFailed += LongPollingDataSource_OnDataReceiveFailed;
            }
        }
Пример #10
0
        public void ParseNumberWithDecimalForced_AndCheckItemType()
        {
            var reader = new JSonReader((ulong.MaxValue + 1d).ToString(CultureInfo.InvariantCulture));
            var result = reader.ReadAsJSonObject(JSonReaderNumberFormat.AsDecimal);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.GetType().Name.Contains("DecimalDecimal"));
        }
        private IJSonObject ConvertToJSon(string data)
        {
            if (!string.IsNullOrEmpty(data))
            {
                try
                {
                    var reader = new JSonReader(data);
                    return reader.ReadAsJSonObject();
                }
                catch (Exception ex)
                {
                    DebugLog.WriteBayeuxLine("Request is not in JSON format!");
                    DebugLog.WriteBayeuxException(ex);
                }
            }

            return null;
        }
        /// <summary>
        /// Records a response as bayeux message, while only 'data' part of the message is given.
        /// It will try to parse data and put as IJSonMutableObject, or if parsing fails, it will put it
        /// just as string value of the field.
        /// </summary>
        public RecordedDataSourceResponse RecordBayeuxData(string name, int internalStatus, string channel, string data)
        {
            if (string.IsNullOrEmpty(channel))
                throw new ArgumentNullException("channel");

            var response = new RecordedBayeuxDataSourceResponse(name);
            var bayeuxMessage = CreateEmptyBayeuxResponse(internalStatus, channel);

            if (string.IsNullOrEmpty(data))
            {
                bayeuxMessage.SetValue("data", data);
            }
            else
            {
                try
                {
                    var reader = new JSonReader(data);
                    bayeuxMessage.SetValue("data", reader.ReadAsJSonMutableObject());
                }
                catch (Exception ex)
                {
                    DebugLog.WriteBayeuxLine("Parsing of 'data' for RecordedBayeuxDataSourceResponse failed!");
                    DebugLog.WriteBayeuxException(ex);

                    bayeuxMessage.SetValue("data", data);
                }
            }

            response.AsJSon = bayeuxMessage;

            Record(response);
            return response;
        }
Пример #13
0
        public void ParseDate1970_Variant2()
        {
            var reader = new JSonReader("\"/ DATE (" + (2 * 60 * 60 * 1000) + " )/\"");
            var result = reader.ReadAsJSonObject();
            Assert.IsNotNull(result);

            var date = result.DateTimeValue.ToUniversalTime();

            Assert.AreEqual(1970, date.Year);
            Assert.AreEqual(1, date.Month);
            Assert.AreEqual(1, date.Day);
            Assert.AreEqual(2, date.Hour);
        }
        public void TryToUpdateImmutableJSonObject()
        {
            var jsonText = "{ \"a\": 1, \"b\": 2 }";

            var reader = new JSonReader(jsonText);
            var result = reader.ReadAsJSonObject();

            Assert.IsNotNull(result, "Invalid data read!");
            Assert.AreEqual(1, result["a"].Int32Value, "Unexpected value for field 'a'.");

            result.AsMutable.SetValue("a", 3);
        }
Пример #15
0
        public void ParseSerializedCurrentDateAsEpochSeconds()
        {
            var writer = new JSonWriter();
            var now = DateTime.Now;

            using (writer.WriteObject())
                writer.WriteMember("date", now, JSonWriterDateFormat.UnixEpochSeconds);

            // remove below seconds:
            now = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, 0, now.Kind);

            var reader = new JSonReader(writer.ToString());
            var item = reader.ReadAsJSonObject();
            var date = item["date"].ToDateTimeValue(JSonDateTimeKind.UnixEpochSeconds);

            Assert.AreNotEqual(0, item["date"].Int64Value);
            Assert.AreEqual(now, date);
        }
Пример #16
0
        public void ParseCurrentDate()
        {
            var reader = new JSonReader("\"/DATE()/\"");
            var result = reader.ReadAsJSonObject();
            Assert.IsNotNull(result);

            var currentDate = DateTime.Now;
            var date = result.DateTimeValue;

            Assert.AreEqual(currentDate.Year, date.Year);
            Assert.AreEqual(currentDate.Month, date.Month);
            Assert.AreEqual(currentDate.Day, date.Day);
        }
Пример #17
0
        //this returns the json object as defined for data transfer
        public IJSonObject readJson(String data)
        {
            JSonReader jr = new JSonReader();
            IJSonObject ijo = jr.ReadAsJSonObject(data);
            String jdata;
            SHA512Managed checksum = new System.Security.Cryptography.SHA512Managed();
            if (ijo[0].BooleanValue)
            {
                //using ijo[3].StringValue != null throws ArrayOutOfBounds exception
                if (ijo.Count > 3)
                {
                    jdata = DecryptIt(ijo[2].StringValue, Convert.FromBase64String(Properties.Settings.Default.cryptKey), Convert.FromBase64String(ijo[3].StringValue));
                }
                else
                {
                    jdata = DecryptIt(ijo[2].StringValue);
                }
            }
            else
            {
                jdata = Encoding.ASCII.GetString(Convert.FromBase64String(ijo[2].StringValue));
            }
            String sha512 = Convert.ToBase64String(checksum.ComputeHash(Encoding.ASCII.GetBytes(jdata)));
            String osha512 = ijo[1].StringValue;
            IJSonObject r;
            //make sure the message is identical to original
            if (osha512 == sha512)
            {
                r = jr.ReadAsJSonObject(jdata);

            }
            else
            {
                //if this comes up data doesn't match the checksum
                r = null;
            }
            return r;
        }
Пример #18
0
        public void ParseAsIEnumerable()
        {
            var jsonText = @"[{""title"":""Title1"",""children"":[{""title"":""Child1"",""children"":[{""title"":""grandchild1"",""children"":[{""title"":""Huh""}]}] }] }, {""title"": ""Title2"" }]";

            JSonReader jr = new JSonReader(jsonText);
            IJSonObject json = jr.ReadAsJSonObject();
            IEnumerable items = json.ArrayItems;

            foreach (var arrayItem in json.ArrayItems)
            {
                //Console.WriteLine(arrayItem.ToString());
                foreach (var objItem in arrayItem.ObjectItems)
                {
                    Console.WriteLine(objItem);
                }
            }
        }
Пример #19
0
        public void ParseChineseTextWithEmbeddedArray()
        {
            var jsonText = LoadTestInputFile("chinese_encoding.json");

            var reader = new JSonReader(jsonText);
            var result = reader.ReadAsJSonObject();
            Assert.IsNotNull(result);

            var internalData = reader.ReadAsJSonObject(result["DataObject"].StringValue);
            Assert.IsNotNull(internalData);
            Assert.AreEqual(2, internalData.Count);
            Assert.AreEqual("业务员", internalData[0]["EmployeeType"].StringValue);
        }
        public void ConvertImmutableJSonObjectToMutableAndUpdateIt()
        {
            var jsonText = "{ \"a\": 1, \"b\": 2, \"c\": [1,2,3,4] }";

            var reader = new JSonReader(jsonText);
            var result = reader.ReadAsJSonObject();

            Assert.IsNotNull(result, "Invalid data read!");
            Assert.AreEqual(1, result["a"].Int32Value, "Unexpected value for field 'a'.");

            var clone = result.CreateMutableClone();
            Assert.IsNotNull(clone, "Unexpected null clone!");
            Assert.AreEqual(1, clone["a"].Int32Value, "Unexpected value for clonned field 'a'.");
            Assert.IsTrue(clone["a"].IsMutable, "Value should be mutable!");

            clone["a"].AsMutable.SetValue(3);
            clone.SetValue("b", 4);
            clone["c"].AsMutable.SetValueAt(2, 55);
            Assert.AreEqual(3, clone["a"].Int32Value, "Expected value to be updated for field 'a'!");
            Assert.AreEqual(4, clone["b"].Int32Value, "Expected value to be updated for field 'b'!");
            Assert.AreEqual(55, clone["c"][2].Int32Value, "Expected array item to be updated!");

            // verify, that original object was left intact:
            Assert.AreEqual(1, result["a"].Int32Value, "Unexpected update!");
            Assert.AreEqual(2, result["b"].Int32Value, "Unexpected update!");
            Assert.AreEqual(3, result["c"][2].Int32Value, "Unexpected update!");
        }
Пример #21
0
        public void ParseDate1970_Variant4()
        {
            var reader = new JSonReader("\"@" + (11 * 60 * 60 * 1000 + 22 * 60 * 1000 + 30 * 1000) + " @\" ");
            var result = reader.ReadAsJSonObject();
            Assert.IsNotNull(result);

            var date = result.DateTimeValue.ToUniversalTime();

            Assert.AreEqual(1970, date.Year);
            Assert.AreEqual(1, date.Month);
            Assert.AreEqual(1, date.Day);
            Assert.AreEqual(11, date.Hour);
            Assert.AreEqual(22, date.Minute);
            Assert.AreEqual(30, date.Second);
        }
Пример #22
0
        public void ReadObjectWithoutSourceSetWithException()
        {
            var reader = new JSonReader();

            reader.ReadAsJSonObject();
        }
Пример #23
0
 public void ParseNumberWithInt32Forced_AndFail()
 {
     try
     {
         var reader = new JSonReader("[12.12, 13.13, 14.14]");
         reader.ReadAsJSonObject(JSonReaderNumberFormat.AsInt32);
     }
     catch (JSonReaderException ex)
     {
         Assert.AreEqual(0, ex.Line);
         Assert.AreEqual(1, ex.Offset);
         throw;
     }
 }
        /// <summary>
        /// Method called just after selection of response performed, but before taking any other action.
        /// It might be used to:
        ///  1) update the data-source based on request data
        ///  2) update the response with request specific data
        ///  3) replace the whole response object
        ///  4) send some other extra notifications, when subclassed
        /// </summary>
        protected override void InternalPreProcessResponse(RecordedDataSourceSelectorEventArgs e)
        {
            // find fields inside the request:
            string id = ReadSharedFieldsAndID(ConvertToJSon(e));

            // update token value, if allowed:
            if (!AllowUpdateTokenOnRequest)
                UpdateTokenValue();

            // update response fields, depending if it is a single or array response:
            var response = e.SelectedResponse as RecordedBayeuxDataSourceResponse;
            if (response != null)
            {
                if (response.AsJSon != null)
                {
                    UpdateSharedFields(e.RequestDataAsJSon as IJSonObject, response.AsJSon, id);
                }
                else
                {
                    IJSonObject responseJSon = null;
                    try
                    {
                        var reader = new JSonReader(response.AsString);
                        responseJSon = reader.ReadAsJSonObject();
                    }
                    catch (Exception ex)
                    {
                        DebugLog.WriteBayeuxLine("Response AsString is not in JSON format!");
                        DebugLog.WriteBayeuxException(ex);
                    }

                    UpdateSharedFields(e.RequestDataAsJSon as IJSonObject, responseJSon, id);
                }
            }
        }
Пример #25
0
        public void ParseExplicitDate_Varian2()
        {
            var reader = new JSonReader("\"\\/ DATE (1999,  1 , 1, 12, 22, 33, 500)\\/\"");
            var result = reader.ReadAsJSonObject();
            Assert.IsNotNull(result);

            var date = result.DateTimeValue.ToUniversalTime();
            Assert.AreEqual(1999, date.Year);
            Assert.AreEqual(1, date.Month);
            Assert.AreEqual(1, date.Day);
            Assert.AreEqual(12, date.Hour);
            Assert.AreEqual(22, date.Minute);
            Assert.AreEqual(33, date.Second);
            Assert.AreEqual(500, date.Millisecond);
        }
        /// <summary>
        /// Records a response as bayeux message.
        /// </summary>
        public RecordedBayeuxDataSourceResponse RecordBayeux(string name, string messageAsJSon)
        {
            var reader = new JSonReader(messageAsJSon);
            var response = new RecordedBayeuxDataSourceResponse(name);

            response.AsJSon = reader.ReadAsJSonMutableObject();

            Record(response);
            return response;
        }
Пример #27
0
 public void ParseInvalidKeywordWithinArray_AndFail()
 {
     try
     {
         var reader = new JSonReader(" [ \t abcdef ]");
         reader.ReadAsJSonObject();
     }
     catch (JSonReaderException ex)
     {
         Assert.AreEqual(0, ex.Line);
         Assert.AreEqual(5, ex.Offset);
         throw;
     }
 }
        /// <summary>
        /// Loads recorded set of bayeux messages from an input stream-reader.
        /// </summary>
        public int LoadRecording(TextReader input)
        {
            if (input == null)
                throw new ArgumentNullException("input");

            int addedResponses = 0;

            var reader = new JSonReader(input, true);

            // if not yet end-of-the-input:
            while (input.Peek() != -1)
            {
                try
                {
                    var jObject = reader.ReadAsJSonMutableObject();

                    if (jObject != null)
                    {
                        RecordBayeux("F-" + addedResponses, jObject);
                        addedResponses++;
                    }
                }
                catch (Exception ex)
                {
                    DebugLog.WriteCoreLine("Invalid format of recorded bayeux responses");
                    DebugLog.WriteBayeuxException(ex);
                    break;
                }
            }

            return addedResponses;
        }
Пример #29
0
 public void ParseInvalidToken_AndFail()
 {
     try
     {
         var reader = new JSonReader("  \t /-~~");
         reader.ReadAsJSonObject();
     }
     catch (JSonReaderException ex)
     {
         Assert.AreEqual(0, ex.Line);
         Assert.AreEqual(4, ex.Offset);
         throw;
     }
 }
Пример #30
0
        public void ParseExplicitDate_Varian1()
        {
            var reader = new JSonReader("\"\\/ DATE (1920,12,31)\\/\"");
            var result = reader.ReadAsJSonObject();
            Assert.IsNotNull(result);

            var date = result.DateTimeValue.ToUniversalTime();

            Assert.AreEqual(1920, date.Year);
            Assert.AreEqual(12, date.Month);
            Assert.AreEqual(31, date.Day);
        }
Пример #31
0
        public void ParseToJSon()
        {
            const string jsonText = "[{\"minimumVersion\":\"1.0\",\"type\": null,\"channel\":\"\\/meta\\/handshake\",\"supportedConnectionTypes\":[\"request-response\"],\"successful\":true}]";

            var reader = new JSonReader(jsonText);
            var result = reader.ReadAsJSonObject();
            Assert.AreEqual("/meta/handshake", result[0]["channel"].StringValue, "Invalid channel");
            Assert.IsTrue(result[0]["type"].IsNull, "Type should be null");
            Assert.AreEqual(1, result[0]["supportedConnectionTypes"].Count, "Supported types are an array with 1 element");
            Assert.AreEqual(1.0, result[0]["minimumVersion"].DoubleValue, "Current version is 1.0");
            Assert.IsTrue(result[0]["successful"].IsTrue, "Operation finished with success!");
        }