/// <summary> /// Will encode the argument to a Json string using the Connection's JsonEncoder, then will send it to the server. /// </summary> /// <returns>True if the plugin was able to send out the message</returns> public bool Send(object arg) { if (arg == null) { throw new ArgumentNullException("arg"); } lock (SyncRoot) { if (this.State != ConnectionStates.Connected) { return(false); } string json = JsonEncoder.Encode(arg); if (string.IsNullOrEmpty(json)) { HTTPManager.Logger.Error("SignalR Connection", "Failed to JSon encode the given argument. Please try to use an advanced JSon encoder(check the documentation how you can do it)."); } else { Transport.Send(json); } } return(true); }
public void TestJsonEncoder_EncodeSuccess() { /* PRECONDITION */ Debug.Assert(encoder != null); Debug.Assert(fileSystem != null); Debug.Assert(config != null); Debug.Assert(container != null); Debug.Assert(input != null); container.ComposeExportedValue <IEncodableEventQueue <JsonIntermediateFormatSample> >(input); container.ComposeExportedValue(config); container.ComposeParts(encoder); /* GIVEN */ var random = new Random(); var eventList = new List <TestEvent> { new TestEvent(random.Next()), new TestEvent(random.Next()) }; var serializedEvent = JsonManualSerialization.GenerateSerializedEvents(eventList); config.RelativeFilePath = new FilePath(fileLocation, true); /* WHEN */ encoder.Encode(new DirectoryPath(recordingFolderLocation, true)); // As the input queue is correctly attached we can now queue our events. Assert.IsTrue(input.ConsumerAttachedEvent.WaitOne(maxWaitTime), "Encoder did not attach to input queue in time!"); // We enqueue now all events we want to serialize. foreach (var @event in eventList) { var sample = new JsonIntermediateFormatSample() { Data = JsonSerializer.SerializeToUtf8Bytes(@event), IssuingModule = @event.IssuingModule, Timestamp = @event.Timestamp, Type = @event.GetType() }; input.Enqueue(sample); } input.Close(); Assert.IsTrue(encoder.EncodeFinished.WaitOne(maxWaitTime), "Encoder did not finish in time!"); /* THEN */ // We get the encoded string which the encoder produced. const string path = recordingFolderLocation + fileLocation; Assert.IsTrue(fileSystem.File.Exists(path)); var encodedString = fileSystem.File.ReadAllText(recordingFolderLocation + fileLocation, Encoding.Default); var plusResolvedString = encodedString.Replace(@"\u002B", "+"); Assert.AreEqual(serializedEvent, plusResolvedString); }
public void SendCommandLog(string commandId, DateTime startTime, DateTime endTime, Dictionary <string, string> comp, bool screenshots) { var logData = new Dictionary <string, IValue>(); var encoder = new JsonEncoder(); logData["time"] = new StringValue(startTime.ToString("yyyy-M-d HH:mm:ss")); logData["name"] = new StringValue($"{commandId,-20}"); var duration = endTime.Subtract(startTime); logData["duration"] = new StringValue(duration.ToString(@"mm\:ss")); logData["result"] = new StringValue(comp["result"]); logData["arg"] = new StringValue(comp["arg"]); if (screenshots) { _screenshotReport = screenshots; } var bytes = encoder.Encode(new DictionaryValue(logData)); string result = Encoding.UTF8.GetString(bytes); string channelStr = "<color=#94D8FF>[COMMAND]</color> " + result; Debug.Log(channelStr); _logData.Add(result); }
/// <summary> /// Serialize the specified object into a json string. /// </summary> /// <param name="obj">Object to convert to a json string.</param> public static string Serialize(object obj) { string result = JsonEncoder.Encode(CurrentJsonSerializer, obj); if (!string.IsNullOrEmpty(result) && (CurrentJsonSerializer.Options & EncodeOptions.PrettyPrint) == EncodeOptions.PrettyPrint) { return(JsonFormatter.PrettyPrint(result)); } return(result); }
public void EncodeDecodeCallbacks() { TestCallbacks tc = new TestCallbacks("Black", 23); string json = JsonEncoder.Encode(tc); Assert.IsTrue(tc.PreEncodedMethodCalled); Assert.IsTrue(tc.EncodedMethodCalled); var decoded = JsonDecoder.Decode <TestCallbacks>(json); Assert.IsTrue(decoded.DecodedMethodCalled); }
/// <summary> /// Sends the upload request asynchronously. /// </summary> /// <typeparam name="TRequest">The type of the request.</typeparam> /// <typeparam name="TResponse">The type of the response.</typeparam> /// <typeparam name="TError">The type of the error.</typeparam> /// <param name="request">The request.</param> /// <param name="body">The document to upload.</param> /// <param name="host">The server host to send the request to.</param> /// <param name="route">The route name.</param> /// <returns> /// An asynchronous task for the response. /// </returns> /// <exception cref="ApiException{TError}"> /// This exception is thrown when there is an error reported by the server. /// </exception> async Task <TResponse> ITransport.SendUploadRequestAsync <TRequest, TResponse, TError>( TRequest request, Stream body, string host, string route) { var serializedArg = JsonEncoder.Encode(request); var res = await this.RequestJsonStringWithRetry(host, route, RouteStyle.Upload, serializedArg, body); if (res.IsError) { throw JsonDecoder.Decode <ApiException <TError> >(res.ObjectResult); } return(JsonDecoder.Decode <TResponse>(res.ObjectResult)); }
/// <summary> /// Sends the download request asynchronously. /// </summary> /// <typeparam name="TRequest">The type of the request.</typeparam> /// <typeparam name="TResponse">The type of the response.</typeparam> /// <typeparam name="TError">The type of the error.</typeparam> /// <param name="request">The request.</param> /// <param name="host">The server host to send the request to.</param> /// <param name="route">The route name.</param> /// <returns> /// An asynchronous task for the response. /// </returns> /// <exception cref="ApiException{TError}"> /// This exception is thrown when there is an error reported by the server. /// </exception> async Task <IDownloadResponse <TResponse> > ITransport.SendDownloadRequestAsync <TRequest, TResponse, TError>( TRequest request, string host, string route) { var serializedArg = JsonEncoder.Encode(request); var res = await this.RequestJsonStringWithRetry(host, route, RouteStyle.Download, serializedArg); if (res.IsError) { throw JsonDecoder.Decode <ApiException <TError> >(res.ObjectResult); } var response = JsonDecoder.Decode <TResponse>(res.ObjectResult); return(new DownloadResponse <TResponse>(response, res.HttpResponse)); }
/// <summary> /// Will encode the argument to a Json string using the Connection's JsonEncoder, then will send it to the server. /// </summary> public void Send(object arg) { if (arg == null) { throw new ArgumentNullException("arg"); } lock (SyncRoot) { if (this.State != ConnectionStates.Connected) { return; } string json = JsonEncoder.Encode(arg); Transport.Send(json); } }
public void FailScenario(string assert) { var startTime = DateTime.UtcNow; var logData = new Dictionary <string, IValue>(); logData["tag"] = new StringValue("info"); logData["depth"] = new IntValue(0); logData["time"] = new StringValue(startTime.ToString("yyyy-M-d hh:mm:ss")); var data = new Dictionary <string, IValue>(); logData["data"] = new DictionaryValue(data); data["name"] = new StringValue("Final Error"); data["traceback"] = new StringValue(assert); var encoder = new JsonEncoder(); var bytes = encoder.Encode(new DictionaryValue(logData)); string result = Encoding.UTF8.GetString(bytes); _reportData.Add(result); }
private void LogsCallback(string condition, string stacktrace, LogType type) { if (type == LogType.Exception && !stacktrace.Contains("ClearPreviewCache")) { var startTime = DateTime.UtcNow; var exception = string.Format("{0}: {1}\n{2}", type, condition, stacktrace); var logData = new Dictionary <string, IValue>(); logData["tag"] = new StringValue("info"); logData["depth"] = new IntValue(0); logData["time"] = new StringValue(startTime.ToString("yyyy-M-d hh:mm:ss")); var data = new Dictionary <string, IValue>(); logData["data"] = new DictionaryValue(data); data["name"] = new StringValue("Final Error"); data["traceback"] = new StringValue(exception); var encoder = new JsonEncoder(); var bytes = encoder.Encode(new DictionaryValue(logData)); string result = Encoding.UTF8.GetString(bytes); _reportData.Add(result); OnErrorDetect?.Invoke(); } }
public void ShouldParseScriptFile(string file, string version, bool compareTrees) { const string prefix = "Escape.Tests.Scripts."; var assembly = Assembly.GetExecutingAssembly(); var scriptPath = prefix + file; var sw = new Stopwatch(); var tempFilePath = NodePath != null ? Path.GetTempFileName() : null; try { using (var stream = assembly.GetManifestResourceStream(scriptPath)) { Assert.True(stream != null, string.Format("Script resource '{0}' not found", scriptPath)); using (var sr = new StreamReader(stream)) { var source = sr.ReadToEnd(); sw.Reset(); sw.Start(); var parser = new JavaScriptParser(); var program = parser.Parse(source); var bsfp = new ByteSizeFormatProvider(); Console.WriteLine("Parsed {0} {1} ({3}) in {2} ms", file, version, sw.ElapsedMilliseconds, bsfp.Format("SZ1", source.Length, null)); Assert.NotNull(program); if (!compareTrees) { Console.WriteLine("WARNING! AST compairson skipped for {0} {1}.", file, version); return; } if (tempFilePath == null) { Console.WriteLine( "If Node.js is installed in the system path " + "then a more comprehensive test can be carried " + "out comparing Esprima's and Escape's AST."); return; } File.WriteAllText(tempFilePath, source); sw.Restart(); var esparseOutput = Esparse(tempFilePath); Console.WriteLine( "Esparse.js for {0} {1} took {2} ms, producing {3} of pretty-printed AST JSON", file, version, sw.ElapsedMilliseconds, bsfp.Format("SZ1", esparseOutput.Length, null)); var sb = new StringBuilder(esparseOutput.Length * 110 / 100); var esw = new StringWriter(sb); JsonEncoder.Encode(program, false, esw); esw.WriteLine(); Assert.Equal(esparseOutput.Length, sb.Length); Assert.True(esparseOutput == sb.ToString(), "AST JSON mismatch"); } } } finally { if (tempFilePath != null) { File.Delete(tempFilePath); } } }
public static string Encode <T>(T value) { return(JsonEncoder.Encode(value)); }
public static void Encode(TextWriter writer, object value, Type type) { JsonEncoder.Encode(writer, value, type); }
public static void Encode <T>(TextWriter writer, T value) { JsonEncoder.Encode(writer, value); }
public static string Encode(object value, Type type) { return(JsonEncoder.Encode(value, type)); }
public void SendCommandReport(string id, DateTime startTime, DateTime endTime, string state) { var logData = new Dictionary <string, IValue>(); var encoder = new JsonEncoder(); logData["tag"] = new StringValue("function"); logData["depth"] = new IntValue(1); logData["time"] = new StringValue(startTime.ToString("yyyy-M-d HH:mm:ss")); logData["data"] = new DictionaryValue(_reportDict); var callArgs = new Dictionary <string, IValue>(); IValue value = new DictionaryValue(callArgs); if (!_reportDict.TryGetValue("call_args", out value)) { _reportDict["call_args"] = new DictionaryValue(callArgs); } _reportDict["end_time"] = new DoubleValue(UnixTime(endTime)); _reportDict["start_time"] = new DoubleValue(UnixTime(startTime)); if (_screenshotReport) { var screenLogData = new Dictionary <string, IValue>(); screenLogData["tag"] = new StringValue("function"); screenLogData["depth"] = new IntValue(1); screenLogData["time"] = new StringValue(startTime.ToString("yyyy-M-d HH:mm:ss")); var dataScreen = new Dictionary <string, IValue>(); screenLogData["data"] = new DictionaryValue(dataScreen); var callArgsScreen = new Dictionary <string, IValue>(); dataScreen["call_args"] = new DictionaryValue(callArgsScreen); dataScreen["ret"] = new StringValue(CaptureScreenshot(id, endTime)); dataScreen["start_time"] = new DoubleValue(UnixTime(startTime)); dataScreen["end_time"] = new DoubleValue(UnixTime(endTime)); dataScreen["name"] = new StringValue("try_log_screen"); var screenBytes = encoder.Encode(new DictionaryValue(screenLogData)); string screenResult = Encoding.UTF8.GetString(screenBytes); _reportData.Add(screenResult); _screenshotReport = false; } else { _reportDict["ret"] = new NullValue(); } _reportDict["name"] = new StringValue(id); var bytes = encoder.Encode(new DictionaryValue(logData)); string result = Encoding.UTF8.GetString(bytes); _reportData.Add(result); var reportData = new Dictionary <string, IValue>(); reportData["time"] = new StringValue(startTime.ToString("yyyy-M-d HH:mm:ss")); reportData["name"] = new StringValue($"step_{id,-20}"); var duration = endTime.Subtract(startTime); reportData["duration"] = new StringValue(duration.ToString(@"mm\:ss")); var list = new List <IValue>(); foreach (var arg in _reportArgs) { list.Add(new StringValue(arg.Value)); } reportData["arg"] = new ListValue(list); bytes = encoder.Encode(new DictionaryValue(reportData)); result = Encoding.UTF8.GetString(bytes); string channelStr = "<color=#4EB32D>[STEPS]</color> " + result; Debug.Log(channelStr); _logData.Add(result); }