private JsonRpcResponse<object> CreateResponse(object result) { var jsonResponse = new JsonRpcResponse<object>(); jsonResponse.Result = result; object messageId; MessageProperties inMsgProperties = OperationContext.Current.IncomingMessageProperties; if (inMsgProperties.TryGetValue(DispatcherUtils.MessageIdKey, out messageId)) jsonResponse.Id = messageId; return jsonResponse; }
public void Get_from_db() { IDebugBridge debugBridge = Substitute.For <IDebugBridge>(); byte[] key = new byte[] { 1, 2, 3 }; byte[] value = new byte[] { 4, 5, 6 }; debugBridge.GetDbValue(Arg.Any <string>(), Arg.Any <byte[]>()).Returns(value); IConfigProvider configProvider = Substitute.For <IConfigProvider>(); IJsonRpcModelMapper modelMapper = new JsonRpcModelMapper(); DebugModule module = new DebugModule(configProvider, NullLogManager.Instance, debugBridge, modelMapper, new UnforgivingJsonSerializer()); JsonRpcResponse response = RpcTest.TestRequest <IDebugModule>(module, "debug_getFromDb", "STATE", key.ToHexString()); byte[] result = Bytes.FromHexString((string)response.Result); Assert.AreEqual(value, result); }
private void OnReceivedResponseHandler(object sender, JsonRpcResponse jsonRpcResponse) { if (jsonRpcResponse != null) { var responseId = jsonRpcResponse.Id; TaskCompletionSource<JsonRpcResponse> requestTcs; if (_pendingRequests.TryRemove(responseId, out requestTcs)) { requestTcs.SetResult(jsonRpcResponse); } else { Debug.WriteLine("Received unmatched JsonRpcResponse."); } } }
private JsonRpcResponse <object> CreateResponse(object result) { var jsonResponse = new JsonRpcResponse <object>(); jsonResponse.Result = result; object messageId; MessageProperties inMsgProperties = OperationContext.Current.IncomingMessageProperties; if (inMsgProperties.TryGetValue(DispatcherUtils.MessageIdKey, out messageId)) { jsonResponse.Id = messageId; } return(jsonResponse); }
public RawTransactionResponse Get(string txid) { if (string.IsNullOrEmpty(txid)) { return(null); } try { JsonRpcResponse <RawTransactionResponse> obj = _client.Transaction.GetRawTransactionVerbose(txid); return(obj.Result); } catch (Exception) { return(null); } }
/// <summary> /// Sends request to specified url /// </summary> /// <param name="jsonRpc">Request body</param> /// <param name="token">Throws a <see cref="T:System.OperationCanceledException" /> if this token has had cancellation requested.</param> /// <returns>JsonRpcResponse</returns> /// <exception cref="T:System.OperationCanceledException">The token has had cancellation requested.</exception> public JsonRpcResponse Execute(IJsonRpcRequest jsonRpc, CancellationToken token) { var waiter = new ManualResetEvent(false); lock (_manualResetEventDictionary) { _manualResetEventDictionary.Add(jsonRpc.Id, waiter); } if (!OpenIfClosed(token)) { return(new JsonRpcResponse(new SystemError(ErrorCodes.ConnectionTimeoutError))); } Debug.WriteLine($">>> {jsonRpc.Message}"); _webSocket.Send(jsonRpc.Message); WaitHandle.WaitAny(new[] { token.WaitHandle, waiter }, WaitResponceTimeout); lock (_manualResetEventDictionary) { if (_manualResetEventDictionary.ContainsKey(jsonRpc.Id)) { _manualResetEventDictionary.Remove(jsonRpc.Id); } waiter.Dispose(); } JsonRpcResponse response = null; lock (_responseDictionary) { if (_responseDictionary.ContainsKey(jsonRpc.Id)) { response = _responseDictionary[jsonRpc.Id]; _responseDictionary.Remove(jsonRpc.Id); } } token.ThrowIfCancellationRequested(); if (response == null) { return(new JsonRpcResponse(new SystemError(ErrorCodes.ResponseTimeoutError))); } return(response); }
private JsonRpcResponse Execute(int id, string msg, CancellationToken token) { var waiter = new ManualResetEvent(false); lock (_manualResetEventDictionary) { _manualResetEventDictionary.Add(id, waiter); } if (!OpenIfClosed(token)) { return(new JsonRpcResponse(new SystemError(ErrorCodes.ConnectionTimeoutError))); } Debug.WriteLine($">>> {msg}"); _webSocket.Send(msg); WaitHandle.WaitAny(new[] { token.WaitHandle, waiter }, Timeout); lock (_manualResetEventDictionary) { if (_manualResetEventDictionary.ContainsKey(id)) { _manualResetEventDictionary.Remove(id); } waiter.Dispose(); } JsonRpcResponse response = null; lock (_responseDictionary) { if (_responseDictionary.ContainsKey(id)) { response = _responseDictionary[id]; _responseDictionary.Remove(id); } } token.ThrowIfCancellationRequested(); if (response == null) { return(new JsonRpcResponse(new SystemError(ErrorCodes.ResponseTimeoutError))); } return(response); }
public void ExecuteParameterWithObjectParamters() { Incubator inc = new Incubator(); inc.Set(new Echo()); EchoData data = new EchoData(); data.BoolProperty = true; data.StringProperty = "dlhsddfflk"; data.IntProperty = 888; JsonRpcRequest request = JsonRpcRequest.Create <Echo>(inc, "TestObjectParameter", data, "some addditional stuff"); JsonRpcResponse response = request.Execute(); Expect.IsNotNull(response.Result); OutLine(response.Result.ToString(), ConsoleColor.Cyan); }
public static Message CreateErrorMessage <T>(MessageVersion messageVersion, JsonRpcResponse <T> response) { byte[] rawBody = SerializeBody(response, Encoding.UTF8); Message msg = CreateMessage(messageVersion, "", rawBody, Encoding.UTF8); var property = (HttpResponseMessageProperty)msg.Properties[HttpResponseMessageProperty.Name]; if (property == null) { property = new HttpResponseMessageProperty(); msg.Properties.Add(HttpResponseMessageProperty.Name, property); } SetStatusCode(response.Error.Code, property); return(msg); }
public bool AvatarImageAssetsRequest(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; m_log.DebugFormat ("Avatar Image Assets Request"); return false; } OSDMap request = (OSDMap)json["params"]; UUID avatarId = new UUID(request["avatarId"].AsString()); OSDArray data = (OSDArray) Service.AvatarImageAssetsRequest(avatarId); response.Result = data; return true; }
public static string TestSerializedRequest <T>(IReadOnlyCollection <JsonConverter> converters, T module, string method, params string[] parameters) where T : class, IModule { IJsonRpcService service = BuildRpcService(module); JsonRpcRequest request = GetJsonRequest(method, parameters); JsonRpcResponse response = service.SendRequestAsync(request).Result; var serializer = new EthereumJsonSerializer(); foreach (var converter in converters) { serializer.RegisterConverter(converter); } var serialized = serializer.Serialize(response); TestContext.Out?.WriteLine("Serialized:"); TestContext.Out?.WriteLine(serialized); return(serialized); }
public async void CoreSerializeResponsesAsyncToStream() { var jsonSample = EmbeddedResourceManager.GetString("Assets.v2_core_batch_res.json"); var jsonRpcSerializer = new JsonRpcSerializer(); var jsonRpcMessage1 = new JsonRpcResponse(0L, 0L); var jsonRpcMessage2 = new JsonRpcResponse(0L, 1L); var jsonRpcMessages = new[] { jsonRpcMessage1, jsonRpcMessage2 }; using (var jsonStream = new MemoryStream()) { await jsonRpcSerializer.SerializeResponsesAsync(jsonRpcMessages, jsonStream); var jsonResult = Encoding.UTF8.GetString(jsonStream.ToArray()); CompareJsonStrings(jsonSample, jsonResult); } }
public async Task GetVersion_ShouldReturnVersion() { var response = new JsonRpcResponse <OdooVersionInfo>(); response.Id = 1; response.Result = new OdooVersionInfo() { ServerVersion = "9.0c", ProtocolVersion = 1 }; this.JsonRpcClient.SetNextResponse(response); var version = await RpcClient.GetOdooVersion(); Assert.Equal("9.0c", version.ServerVersion); Assert.Equal(1, version.ProtocolVersion); }
private JsonRpcResponse Execute(int id, string msg) { var waiter = new ManualResetEvent(false); lock (_manualResetEventDictionary) { _manualResetEventDictionary.Add(id, waiter); } if (!OpenIfClosed()) { return(new JsonRpcResponse(new SystemError(ErrorCodes.ConnectionTimeoutError))); } Debug.WriteLine($">>> {msg}"); _webSocket.Send(msg); waiter.WaitOne(Timeout); lock (_manualResetEventDictionary) { if (_manualResetEventDictionary.ContainsKey(id)) { _manualResetEventDictionary.Remove(id); } waiter.Dispose(); } JsonRpcResponse response = null; lock (_responseDictionary) { if (_responseDictionary.ContainsKey(id)) { response = _responseDictionary[id]; _responseDictionary.Remove(id); } } if (response == null) { return(new JsonRpcResponse(new SystemError(ErrorCodes.ResponseTimeoutError))); } return(response); }
public async Task Search_WithPaginationWithOrder_ShouldCallRpcWithCorrectParameters() { var requestParameters = new OdooSearchParameters( "res.partner", new OdooDomainFilter() .Filter("is_company", "=", true) .Filter("customer", "=", true) ); var testResults = new long[] { 7L, 18L, 12L, 14L, 17L, 19L }; var response = new JsonRpcResponse <long[]>(); response.Id = 1; response.Result = testResults; await TestOdooRpcCall(new OdooRpcCallTestParameters <long[]>() { Model = "res.partner", Method = "search", Validator = (p) => { Assert.Equal(7, p.args.Length); dynamic domainArgs = p.args[5]; Assert.Equal(2, domainArgs[0].Length); Assert.Equal( new object[] { new object[] { "is_company", "=", true }, new object[] { "customer", "=", true } }, domainArgs[0] ); dynamic pagArgs = p.args[6]; Assert.Equal(0, pagArgs.offset); Assert.Equal(5, pagArgs.limit); Assert.Equal("customer ASC, id ASC, name DESC", pagArgs.order); }, ExecuteRpcCall = () => RpcClient.Search <long[]>(requestParameters, new OdooPaginationParameters(0, 5).OrderBy("customer").ThenBy("id").ThenByDescending("name")), TestResponse = response }); }
protected void OnError <T>(JsonRpcResponse response, OperationResult <T> operationResult) { if (response.IsError) { if (response.Error is SystemError systemError) { operationResult.Error = new HttpError(systemError); } else if (response.Error is ResponseError responseError) { operationResult.Error = new BlockchainError(responseError); } else { operationResult.Error = new ServerError(response.Error); } } }
/// <summary> /// Request avatar's classified ads. /// </summary> /// <returns> /// An array containing all the calassified uuid and it's name created by the creator id /// </returns> /// <param name='json'> /// Our parameters are in the OSDMap json["params"] /// </param> /// <param name='response'> /// If set to <c>true</c> response. /// </param> public bool AvatarClassifiedsRequest(OSDMap json, ref JsonRpcResponse response) { if (!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; m_log.DebugFormat("Classified Request"); return(false); } OSDMap request = (OSDMap)json["params"]; UUID creatorId = new UUID(request["creatorId"].AsString()); OSDArray data = (OSDArray)Service.AvatarClassifiedsRequest(creatorId); response.Result = data; return(true); }
public bool PicksDelete(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; m_log.DebugFormat ("Avatar Picks Delete Request"); return false; } OSDMap request = (OSDMap)json["params"]; UUID pickId = new UUID(request["pickId"].AsString()); if(Service.PicksDelete(pickId)) return true; response.Error.Code = ErrorCode.InternalError; response.Error.Message = "data error removing record"; return false; }
private void ThrowOnError <T>(JsonRpcResponse <T> response) { if (response.Error != null) { if (response.Error.Code == ClientError.HTTP_ERROR) { throw CreateFiskalyHttpError(response); } else if (response.Error.Code == ClientError.HTTP_TIMEOUT_ERROR) { throw new FiskalyHttpTimeoutError(response.Error.Message); } else { throw CreateFiskalyClientError(response); } } }
private async void ReceiveMessages() { try { while (_socket.State == WebSocketState.Open && !_cts.IsCancellationRequested) { ArraySegment <byte> buffer = new ArraySegment <byte>(new byte[1024]); await _socket.ReceiveAsync(buffer, _cts.Token); string msg = buffer.Array.GetString(); JsonRpcResponse response = ReceiveMessage(!string.IsNullOrEmpty(_password) ? msg.Decrypt(_password) : msg); Send(response.ToJson()); } } catch { } Dispose(); OnClose?.Invoke(this, new EventArgs()); }
private void InitializeContext() { byte[] payload = PayloadFactory .BuildCreateContextPayload(DateTime.Now.ToString(), ApiKey, ApiSecret, BaseUrl); string createContextResponse = Client.Invoke(payload); System.Diagnostics.Debug.WriteLine("CreateContextResponse: " + createContextResponse); InitialContextSet = true; JsonRpcResponse <CreateContextResult> response = JsonConvert .DeserializeObject <JsonRpcResponse <CreateContextResult> >(createContextResponse); ThrowOnError(response); Context = response.Result.Context; System.Diagnostics.Debug.WriteLine("Set context to: " + Context); }
private async Task SendResponse(HttpContext httpContext, JsonRpcResponse response) { var jObject = JObject.FromObject(response, _server.Serializer); // append jsonrpc constant if enabled if (_options.UseJsonRpcConstant) { jObject.AddFirst(new JProperty("jsonrpc", "2.0")); } // ensure that respose has either result or error property var errorProperty = jObject.Property("error"); if (jObject.Property("result") == null && errorProperty == null) { jObject.Add("result", null); } // remove error data if disallowed if (!_options.AllowErrorData && errorProperty?.Value is JObject errorObject) { errorObject.Property("data", StringComparison.OrdinalIgnoreCase)?.Remove(); } httpContext.Response.StatusCode = 200; httpContext.Response.ContentType = "application/json"; // todo: move to System.Text.Json await using (var tempStream = new MemoryStream()) { await using (var tempStreamWriter = new StreamWriter(tempStream, leaveOpen: true)) using (var jsonWriter = new JsonTextWriter(tempStreamWriter)) { await jObject.WriteToAsync(jsonWriter); await jsonWriter.FlushAsync(); await jsonWriter.CloseAsync(); } tempStream.Seek(0, SeekOrigin.Begin); await tempStream.CopyToAsync(httpContext.Response.Body); } }
public async Task Get_WithIds_And_WithFields_ShouldCallRpcWithCorrectParameters() { var requestParameters = new OdooGetParameters("res.partner", new long[] { 7 }); var testPartner = new TestPartner() { comment = false, country_id = new object[] { 21, "Belgium" }, id = 7, name = "Agrolait" }; var response = new JsonRpcResponse <TestPartner[]>(); response.Id = 1; response.Result = new TestPartner[] { testPartner }; await TestOdooRpcCall(new OdooRpcCallTestParameters <TestPartner[]>() { Validator = (p) => { Assert.Equal(7, p.args.Length); dynamic args = p.args[5]; Assert.Equal(1, args.Length); Assert.Equal(requestParameters.Ids, args[0]); dynamic fieldsArgs = p.args[6]; Assert.Equal(new string[] { "name", "country_id", "comment" }, fieldsArgs.fields); }, Model = requestParameters.Model, Method = "read", ExecuteRpcCall = () => { return(RpcClient.Get <TestPartner[]>( requestParameters, new OdooFieldParameters(new string[] { "name", "country_id", "comment" }) )); }, TestResponse = response }); }
public ClientConfiguration ConfigureClient(ClientConfiguration configuration) { if (!InitialContextSet) { InitializeContext(); } byte[] payload = PayloadFactory .BuildClientConfigurationPayload(DateTime.Now.ToString(), new ConfigParams { Configuration = new Configuration { ClientTimeout = configuration.ClientTimeout, SmaersTimeout = configuration.SmaersTimeout, DebugFile = configuration.DebugFile, DebugLevel = (int)configuration.DebugLevel, HttpProxy = configuration.HttpProxy }, Context = Context }); string invocationResponse = Client.Invoke(payload); System.Diagnostics.Debug.WriteLine("ConfigureClient[invocationResponse]: " + invocationResponse); JsonRpcResponse <ConfigParams> rpcResponse = JsonConvert.DeserializeObject <JsonRpcResponse <ConfigParams> >(invocationResponse); ThrowOnError(rpcResponse); Configuration config = rpcResponse.Result.Configuration; Context = rpcResponse.Result.Context; return(new ClientConfiguration { ClientTimeout = config.ClientTimeout, SmaersTimeout = config.SmaersTimeout, DebugFile = config.DebugFile, DebugLevel = (DebugLevel)config.DebugLevel, HttpProxy = config.HttpProxy }); }
/// <summary> /// Used internally to create a response package. /// </summary> /// <typeparam name="TResData"></typeparam> /// <returns>A signed and validated JsonRpc response package</returns> public JsonRpcResponse <TResData> CreateResponsePackage <TResData>(string method, string requestUuid, TResData responseData) where TResData : IResponseResultData { var rpcResponse = new JsonRpcResponse <TResData> { Result = new ResponseResult <TResData> { Method = method, UUID = requestUuid, Data = responseData }, Version = "1.1" }; this._signer.Sign(rpcResponse); this._validator.Validate(rpcResponse); return(rpcResponse); }
private string GetAddress(JsonRpcResponse <string> response) { string address1 = response.Result; response = null; Task.Run(async() => { response = await _Client.Permission.GrantAsync(new List <string>() { address1 }, BlockChainPermission.Receive | BlockChainPermission.Send); }).GetAwaiter().GetResult(); ResponseLogger <string> .Log(response); Debug.WriteLine("grant permissions to: " + address1); Assert.IsTrue(!string.IsNullOrEmpty(response.Result)); return(response.Result); }
public bool ClassifiedDelete(OSDMap json, ref JsonRpcResponse response) { if (!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; m_log.DebugFormat("Classified Delete Request"); return(false); } OSDMap request = (OSDMap)json["params"]; UUID classifiedId = new UUID(request["classifiedID"].AsString()); OSDMap res = new OSDMap(); res["result"] = OSD.FromString("success"); response.Result = res; return(true); }
/// <summary> /// Check the crypto client response is ok. /// </summary> private T CheckResponseOk <T>(HttpResponseMessage response) { try { using (var jsonStream = response.Content.ReadAsStreamAsync().Result) { using (var jsonStreamReader = new StreamReader(jsonStream)) { if (response.StatusCode != HttpStatusCode.OK) { JsonRpcResponse <T> errRet = null; string res = jsonStreamReader.ReadToEndAsync().Result; try { errRet = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(res); } catch { throw CreateException(response, 0, res); } var code = errRet != null && errRet.Error != null ? errRet.Error.Code : 0; var msg = errRet != null && errRet.Error != null ? errRet.Error.Message : "Error"; throw CreateException(response, code, msg); } var ret = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(jsonStreamReader.ReadToEndAsync().Result); return(ret.Result); } } } catch (BitcoinClientException) { throw; } catch (Exception ex) { throw new BitcoinClientException(string.Format("Failed parsing the result, StatusCode={0}, row message={1}", response.StatusCode, response.Content.ReadAsStringAsync().Result), ex); } }
public void ExecuteOrderedParamsTest() { Incubator inc = new Incubator(); inc.Set(new Echo()); string value = "hello there ".RandomLetters(8); object id = "some value"; string inputString = "{{'jsonrpc': '2.0', 'method': 'Send', 'id': '{0}', 'params': ['{1}']}}"._Format(id, value); IHttpContext context = GetPostContextWithInput(inputString); IJsonRpcRequest parsed = JsonRpcMessage.Parse(context); JsonRpcRequest request = (JsonRpcRequest)parsed; request.Incubator = inc; JsonRpcResponse response = request.Execute(); Expect.IsTrue(response.GetType().Equals(typeof(JsonRpcResponse))); Expect.AreEqual(value, response.Result); Expect.IsNull(response.Error); Expect.AreEqual(id, response.Id); }
public void PrepareLockUnspentAsync() { MultiChainTests.Mocks.Asset asset = new MultiChainTests.Mocks.Asset(); asset.Title = "Asset2"; asset.Description = "An Asset added by a unit test"; _Client.Asset.IssueAsync(TestSettings.FromAddress, new { name = asset.Title, open = true }, 10, 1, asset); Dictionary <string, int> assetQuantities = new Dictionary <string, int>(); assetQuantities.Add(asset.Title, 1); JsonRpcResponse <PrepareLockUnspentResponse> response = null; Task.Run(async() => { response = await _Client.Transaction.PrepareLockUnspent(assetQuantities, true); }).GetAwaiter().GetResult(); ResponseLogger <PrepareLockUnspentResponse> .Log(response); }
public void GetRawTransactionVerboseAsync() { JsonRpcResponse <BlockResponse> blockresponse = _Client.Block.GetBlock(58, true); if (blockresponse.Result.Tx.Count < 2) { throw new Exception("There is no transaction to test"); } string txId = blockresponse.Result.Tx[1]; JsonRpcResponse <RawTransactionResponse> rawresponse = null; Task.Run(async() => { rawresponse = await _Client.Transaction.GetRawTransactionVerboseAsync(txId); }).GetAwaiter().GetResult(); ResponseLogger <RawTransactionResponse> .Log(rawresponse); }
public void GetNewAddressAsync() { JsonRpcResponse <string> response = null; Task.Run(async() => { response = await _Client.Wallet.GetNewAddressAsync(); }).GetAwaiter().GetResult(); ResponseLogger <string> .Log(response); JsonRpcResponse <AddressResponse> addressresponse = null; Task.Run(async() => { addressresponse = await _Client.Address.ValidateAddressAsync(response.Result); }).GetAwaiter().GetResult(); ResponseLogger <AddressResponse> .Log(addressresponse); }
public void ProvideFault(Exception error, MessageVersion version, ref Message fault) { bool includeDetails = IncludeExceptionDetails(); // TODO: check error type and set appropriate error code object msgId = null; if (OperationContext.Current.IncomingMessageProperties.ContainsKey(DispatcherUtils.MessageIdKey)) msgId = OperationContext.Current.IncomingMessageProperties[DispatcherUtils.MessageIdKey]; // TODO: extract exception details from FaultException object additionalData; var faultException = error as FaultException; if (faultException != null && faultException.GetType().IsGenericType) { additionalData = faultException.GetType().GetProperty("Detail").GetValue(faultException, null); } else { additionalData = error; } var exception = new JsonRpcException(123, error.Message, additionalData); var errMessage = new JsonRpcResponse<object>() { Error = exception, Result = null, Id = msgId }; byte[] rawBody = DispatcherUtils.SerializeBody(errMessage, Encoding.UTF8); Message msg = DispatcherUtils.CreateMessage(version, "", rawBody, Encoding.UTF8); var property = (HttpResponseMessageProperty)msg.Properties[HttpResponseMessageProperty.Name]; property.StatusCode = HttpStatusCode.InternalServerError; property.StatusDescription = "Internal Server Error"; fault = msg; }
public void SendResponseToClient(JsonRpcResponse response) { AddJObjectToQueueAsync(JObject.FromObject(response)); }