private ResponseMessage ExecuteMethodErrorHandler(HttpContext context, RpcRequestMessage requestMessage, Exception exp, bool runFilters, List <ICallFilter> filters, CallExecutionContext callExecutionContext) { if (runFilters) { foreach (var callFilter in filters) { ICallExceptionFilter exceptionFilter = callFilter as ICallExceptionFilter; try { exceptionFilter?.HandleException(callExecutionContext, exp); } catch (Exception e) { _logger?.LogError(EventIdCode.ExecutionFilterException, e, "Exception thrown while invoking ICallExceptionFilter"); } } } _logger?.LogError(EventIdCode.ExecutionException, exp, $"Exception thrown while processing {context.Request.Path} {requestMessage.Method} - " + exp.Message); return(ReturnInternalServerError(requestMessage.Version, requestMessage.Id, $"Executing {context.Request.Path} {requestMessage.Method} {exp.Message}")); }
protected virtual Task <T> SendInnerRequestAsync <T>(string method, string route = null, params object[] paramList) { var request = new RpcRequestMessage(Guid.NewGuid().ToString(), method, paramList); return(SendInnerRequestAsync <T>(request, route)); }
protected override Task <RpcResponseMessage> SendAsync(RpcRequestMessage request, string route = null) { var logger = new RpcLogger(_log); try { lock (_lockingObject) { var rpcRequestJson = JsonConvert.SerializeObject(request, JsonSerializerSettings); var requestBytes = Encoding.UTF8.GetBytes(rpcRequestJson); logger.LogRequest(rpcRequestJson); GetPipeClient().Write(requestBytes, 0, requestBytes.Length); using (var memoryData = ReceiveFullResponse(GetPipeClient())) { memoryData.Position = 0; using (StreamReader streamReader = new StreamReader(memoryData)) using (JsonTextReader reader = new JsonTextReader(streamReader)) { var serializer = JsonSerializer.Create(JsonSerializerSettings); var message = serializer.Deserialize <RpcResponseMessage>(reader); logger.LogResponse(message); return(Task.FromResult(message)); } } } } catch (Exception ex) { var exception = new RpcClientUnknownException("Error occurred when trying to send ipc requests(s)", ex); logger.LogException(exception); throw exception; } }
/// <summary> /// rpc 其他接口查询 /// </summary> /// <param name="apiName">api请求接口名</param> /// <param name="paramsValue">对应的请求参数</param> /// <returns>返回值,根据文档中对应api 返回object </returns> public TResult SendQuery <TResult>(string apiName, params object[] paramsValue) where TResult : class, new() { var request = new RpcRequestMessage(this._rpcId, apiName, paramsValue); var result = HttpUtils.RpcPost <TResult>(this._url, request); return(result); }
/// <summary> /// 同步 获取交易回执 /// </summary> /// <param name="tanscationHash">交易Hash</param> /// <returns></returns> public ReceiptResultDto GetTranscationReceipt(string tanscationHash) { var rpcRequest = new RpcRequestMessage(this._requestId, JsonRPCAPIConfig.GetTransactionReceipt, new object[] { this._requestObjectId, tanscationHash }); var result = HttpUtils.RpcPost <ReceiptResultDto>(this._url, rpcRequest); return(result); }
/// <summary> /// 同步 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="url"></param> /// <param name="rpcRequestMessage"></param> /// <returns></returns> public static T RpcPost <T>(string url, RpcRequestMessage rpcRequestMessage = null) where T : class, new() { T t = new T(); HttpWebRequest request; RpcResponseMessage rpcResponseMessage; StreamWriter requestStream = null; HttpWebResponse response = null; request = BuildRequest(url, rpcRequestMessage); try { response = request.GetResponse() as HttpWebResponse;//异步 rpcResponseMessage = BuildResponse(response); t = AnalysisResponse <T>(rpcResponseMessage); } catch (Exception ex) { throw ex; } finally { request = null; requestStream = null; rpcResponseMessage = null; } return(t); }
/// <summary> /// 同步 获取交易回执 /// </summary> /// <param name="tanscationHash">交易Hash</param> /// <returns></returns> public ReceiptResultDto GetTranscationReceipt(string transcationHash) { var rpcRequest = new RpcRequestMessage(this._requestId, JsonRPCAPIConfig.GetTransactionReceipt, new object[] { this._requestObjectId, transcationHash }); ReceiptResultDto receiptResultDto = new ReceiptResultDto(); Stopwatch sw = new Stopwatch(); sw.Start(); long times = 0; while (true) { receiptResultDto = HttpUtils.RpcPost <ReceiptResultDto>(this._url, rpcRequest); times += sw.ElapsedMilliseconds; if (times > BaseConfig.DefaultExpirationTime) { sw.Stop(); throw new Exception("获取交易回执超时!"); } if (receiptResultDto != null) { break; } } return(receiptResultDto); }
protected override async Task<RpcResponseMessage> SendAsync(RpcRequestMessage request, string route = null) { try { var httpClient = GetOrCreateHttpClient(); var rpcRequestJson = JsonConvert.SerializeObject(request, _jsonSerializerSettings); var httpContent = new StringContent(rpcRequestJson, Encoding.UTF8, "application/json"); var cancellationTokenSource = new CancellationTokenSource(); cancellationTokenSource.CancelAfter(ConnectionTimeout); var httpResponseMessage = await httpClient.PostAsync(route, httpContent, cancellationTokenSource.Token).ConfigureAwait(false); httpResponseMessage.EnsureSuccessStatusCode(); var stream = await httpResponseMessage.Content.ReadAsStreamAsync(); using (var streamReader = new StreamReader(stream)) using (var reader = new JsonTextReader(streamReader)) { var serializer = JsonSerializer.Create(_jsonSerializerSettings); var message = serializer.Deserialize<RpcResponseMessage>(reader); return message; } } catch (TaskCanceledException ex) { throw new RpcClientTimeoutException($"Rpc timeout after {ConnectionTimeout.TotalMilliseconds} milliseconds", ex); } catch (Exception ex) { throw new RpcClientUnknownException("Error occurred when trying to send rpc requests(s)", ex); } }
public virtual async Task SendRequestAsync(string method, string route = null, params object[] paramList) { var request = new RpcRequestMessage(Guid.NewGuid().ToString(), method, paramList); var response = await SendAsync(request, route).ConfigureAwait(false); HandleRpcError(response); }
private async Task <RpcResponseMessage> SendAsync(RpcRequestMessage request, string route = null) { try { var httpClient = GetOrCreateHttpClient(); var rpcRequestJson = JsonConvert.SerializeObject(request, _jsonSerializerSettings); var httpContent = new StringContent(rpcRequestJson, Encoding.UTF8, "application/json"); var httpResponseMessage = await httpClient.PostAsync(route, httpContent).ConfigureAwait(false); httpResponseMessage.EnsureSuccessStatusCode(); var stream = await httpResponseMessage.Content.ReadAsStreamAsync(); using (var streamReader = new StreamReader(stream)) using (var reader = new JsonTextReader(streamReader)) { var serializer = JsonSerializer.Create(_jsonSerializerSettings); return(serializer.Deserialize <RpcResponseMessage>(reader)); } } catch (Exception ex) { throw new RpcClientUnknownException("Error occurred when trying to send rpc requests(s)", ex); } }
/// <summary> /// 异步 获取交易回执 /// </summary> /// <param name="tanscationHash">交易Hash</param> /// <returns></returns> public async Task <ReceiptResultDto> GetTranscationReceiptAsync(string transcationHash) { var request = new RpcRequest(this._requestId, JsonRPCAPIConfig.GetTransactionReceipt, new object[] { this._requestObjectId, transcationHash }); var getRequest = new RpcRequestMessage(this._requestId, JsonRPCAPIConfig.GetTransactionReceipt, new object[] { this._requestObjectId, transcationHash }); ReceiptResultDto receiptResultDto = new ReceiptResultDto(); Stopwatch sw = new Stopwatch(); sw.Start(); long times = 0; while (true) { receiptResultDto = await this._rpcClient.SendRequestAsync <ReceiptResultDto>(request); times += sw.ElapsedMilliseconds; if (times > BaseConfig.DefaultExpirationTime) { sw.Stop(); throw new Exception("获取交易回执超时!"); } if (receiptResultDto != null) { break; } } return(receiptResultDto); }
protected async override Task <RpcResponseMessage> SendAsync(RpcRequestMessage request, string route = null) { return(await SafeCall(async() => { return await base.SendAsync(request, route).ConfigureAwait(false); })); }
protected virtual async Task SendInnerRequestAsync(string method, string route = null, params object[] paramList) { var request = new RpcRequestMessage(Guid.NewGuid().ToString(), method, paramList); await SendInnerRequestAsync(request, route); }
protected override async Task <RpcResponseMessage> SendAsync(RpcRequestMessage request, string route = null, CancellationToken cancellationToken = default(CancellationToken)) { var logger = new RpcLogger(_log); try { lock (_lockingObject) { var rpcRequestJson = JsonConvert.SerializeObject(request, JsonSerializerSettings); var requestBytes = Encoding.UTF8.GetBytes(rpcRequestJson); logger.LogRequest(rpcRequestJson); var client = GetSocket(); client.SendBufferSize = requestBytes.Length; var val = client.SendAsync(new ArraySegment <byte>(requestBytes, 0, requestBytes.Length), SocketFlags.None).Result; using (var memoryStream = ReceiveFullResponse(client)) { memoryStream.Position = 0; using (var streamReader = new StreamReader(memoryStream)) using (var reader = new JsonTextReader(streamReader)) { var serializer = JsonSerializer.Create(JsonSerializerSettings); var message = serializer.Deserialize <RpcResponseMessage>(reader); logger.LogResponse(message); return(message); } } } } catch (Exception ex) { logger.LogException(ex); throw new RpcClientUnknownException("Error occurred when trying to send ipc requests(s)", ex); } }
protected override async Task <RpcResponseMessage> SendAsync(RpcRequestMessage message, string route = null) { _id += 1; var mapParameters = message.RawParameters as Dictionary <string, object>; var arrayParameters = message.RawParameters as object[]; var rawParameters = message.RawParameters; RpcRequestMessage rpcRequestMessage; if (mapParameters != null) { rpcRequestMessage = new RpcRequestMessage(_id, message.Method, mapParameters); } else if (arrayParameters != null) { rpcRequestMessage = new RpcRequestMessage(_id, message.Method, arrayParameters); } else { rpcRequestMessage = new RpcRequestMessage(_id, message.Method, rawParameters); } TaskCompletionSource <RpcResponseMessage> eventCompleted = new TaskCompletionSource <RpcResponseMessage>(TaskCreationOptions.None); Provider.Events.ListenForResponse <RpcResponseMessage>(rpcRequestMessage.Id, (sender, args) => { eventCompleted.SetResult(args.Response); }); await Provider.SendRequest(rpcRequestMessage); return(await eventCompleted.Task); }
public async Task SendRequestAsync(RpcRequestMessage request, IRpcStreamingResponseHandler requestResponseHandler, string route = null) { var logger = new RpcLogger(_log); try { await _semaphoreSlim.WaitAsync().ConfigureAwait(false); var rpcRequestJson = JsonConvert.SerializeObject(request, JsonSerializerSettings); var requestBytes = new ArraySegment <byte>(Encoding.UTF8.GetBytes(rpcRequestJson)); logger.LogRequest(rpcRequestJson); var timeoutCancellationTokenSource = new CancellationTokenSource(); timeoutCancellationTokenSource.CancelAfter(ConnectionTimeout); var webSocket = _clientWebSocket; await webSocket.SendAsync(requestBytes, WebSocketMessageType.Text, true, timeoutCancellationTokenSource.Token) .ConfigureAwait(false); HandleRequest(request, requestResponseHandler); } catch (Exception ex) { logger.LogException(ex); throw new RpcClientUnknownException("Error occurred trying to send web socket requests(s)", ex); } finally { _semaphoreSlim.Release(); } }
private void ProcessParams(JsonReader reader, RpcRequestMessage rpcMessage, ref object parameters, JsonSerializer serializer, string path) { if (string.IsNullOrEmpty(rpcMessage.Method)) { reader.Read(); if (reader.TokenType == JsonToken.StartObject) { parameters = serializer.Deserialize <IDictionary <string, object> >(reader); } else { parameters = serializer.Deserialize <JArray>(reader); } } else { var converter = GetConverter(path, rpcMessage.Method); if (converter != null) { rpcMessage.MethodInformation = converter.ExposedMethod; rpcMessage.Parameters = GetParametersUsingCompiledDelgates((RpcJsonReader)reader, converter, serializer); } else { rpcMessage.ErrorMessage = $"Could not find method {path} {rpcMessage.Method}"; } } }
/// <summary> /// 同步 Call 调用 适用于链上调用但不需要共识(通常用constant,view等修饰的合约方法) /// </summary> /// <param name="contractAddress">合约地址</param> /// <param name="abi">合约abi</param> /// <param name="callFunctionName">调用方法名称</param> /// <returns>返回交易回执</returns> public ReceiptResultDto CallRequest(string contractAddress, string abi, string callFunctionName, Parameter[] inputsParameters = null, params object[] value) { CallInput callDto = new CallInput(); callDto.From = new Account(this._privateKey).Address.ToLower();//address ; callDto.To = contractAddress; var contractAbi = new ABIDeserialiser().DeserialiseContract(abi); callDto.Value = new HexBigInteger(0); var function = contractAbi.Functions.FirstOrDefault(x => x.Name == callFunctionName); var sha3Signature = function.Sha3Signature;// "0x53ba0944"; if (inputsParameters == null) { callDto.Data = "0x" + sha3Signature; } else { var functionCallEncoder = new FunctionCallEncoder(); var funcData = functionCallEncoder.EncodeRequest(sha3Signature, inputsParameters, value); callDto.Data = funcData; } var request = new RpcRequestMessage(this._requestId, JsonRPCAPIConfig.Call, new object[] { this._requestObjectId, callDto }); var result = HttpUtils.RpcPost <ReceiptResultDto>(this._url, request);; return(result); }
protected virtual Task <T> SendInnerRequestAsync <T>(RpcRequest request, string route = null) { var reqMsg = new RpcRequestMessage(request.Id, request.Method, request.RawParameters); return(SendInnerRequestAsync <T>(reqMsg, route)); }
protected override async Task<T> SendInnerRequestAync<T>(string method, string route = null, params object[] paramList) { var request = new RpcRequestMessage(Guid.NewGuid().ToString(), method, paramList); var response = await SendAsync(request, route).ConfigureAwait(false); HandleRpcError(response); return response.GetResult<T>(); }
protected virtual async Task SendInnerRequestAsync(RpcRequest request, string route = null) { var reqMsg = new RpcRequestMessage(request.Id, request.Method, request.RawParameters); await SendInnerRequestAsync(reqMsg, route).ConfigureAwait(false); }
/// <summary> /// 请求发送RPC交易 /// </summary> /// <typeparam name="TResult">返回结果</typeparam> /// <param name="txData">交易数据(rlp)</param> /// <param name="txSignature">交易签名</param> /// <returns>返回交易结果</returns> protected TResult SendRequest <TResult>(byte[][] txData, EthECDSASignature txSignature) where TResult : class, new() { var rlpSignedEncoded = RLPEncoder.EncodeSigned(new SignedData(txData, txSignature), 10).ToHex(); var request = new RpcRequestMessage(this._requestId, JsonRPCAPIConfig.SendRawTransaction, new object[] { this._requestObjectId, rlpSignedEncoded }); var result = HttpUtils.RpcPost <TResult>(this._url, request); return(result); }
public CallExecutionContext(HttpContext context, Type executingClass, MethodInfo method, RpcRequestMessage requestMessage) { ContinueCall = true; HttpContext = context; ExecutingClass = executingClass; ExecutingMethod = method; RequestMessage = requestMessage; }
/// <summary> ///同步 获取当前区块高度 /// </summary> /// <param name="rpcId">rpcId</param> /// <param name="groupId">群组Id</param> /// <returns>当前区块高度</returns> public long GetBlockNumber() { var request = new RpcRequestMessage(this._rpcId, JsonRPCAPIConfig.GetBlockNumber, new object[] { this._groupId }); var responseResult = HttpUtils.RpcPost <object>(this._url, request); long blockNumber = Convert.ToInt64(responseResult.ToString(), 16); return(blockNumber); }
public async Task SendRequestAsync(RpcRequest request, IRpcStreamingResponseHandler requestResponseHandler, string route = null) { var reqMsg = new RpcRequestMessage(request.Id, request.Method, request.RawParameters); await SendRequestAsync(reqMsg, requestResponseHandler, route).ConfigureAwait(false); }
protected virtual async Task <T> SendInnerRequestAsync <T>(string method, string route = null, CancellationToken cancellationToken = default(CancellationToken), params object[] paramList) { var request = new RpcRequestMessage(Guid.NewGuid().ToString(), method, paramList); return(await SendInnerRequestAsync <T>(request, route, cancellationToken)); }
private void ProcessMethod(JsonReader reader, RpcRequestMessage rpcMessage, object parameters, JsonSerializer serializer, string path) { rpcMessage.Method = reader.ReadAsString(); if (parameters != null) { ProcessOutOfOrderParameters(rpcMessage, parameters, path); } }
protected virtual async Task <T> SendInnerRequestAsync <T>(RpcRequest request, string route = null, CancellationToken cancellationToken = default(CancellationToken)) { var reqMsg = new RpcRequestMessage(request.Id, request.Method, request.RawParameters); return(await SendInnerRequestAsync <T>(reqMsg, route, cancellationToken).ConfigureAwait(false)); }
public async Task WhenWebSocketIsNull_SendAsync_ThrowsExpectedException() { var client = new StreamingWebSocketClient(""); var rpcRequestMessage = new RpcRequestMessage("", ""); var mockResponseHandler = new Mock <IRpcStreamingResponseHandler>(); var exception = await Assert.ThrowsAsync <InvalidOperationException>(() => client.SendRequestAsync(rpcRequestMessage, mockResponseHandler.Object)); Assert.Equal("Websocket is null. Ensure that StartAsync has been called to create the websocket.", exception.Message); }
/// <summary> /// 异步 获取交易回执 /// </summary> /// <param name="tanscationHash">交易Hash</param> /// <returns></returns> public async Task <ReceiptResultDto> GetTranscationReceiptAsync(string tanscationHash) { var request = new RpcRequest(this._requestId, JsonRPCAPIConfig.GetTransactionReceipt, new object[] { this._requestObjectId, tanscationHash }); var getRequest = new RpcRequestMessage(this._requestId, JsonRPCAPIConfig.GetTransactionReceipt, new object[] { this._requestObjectId, tanscationHash }); //var result = await HttpUtils.RpcPost<ReceiptResultDto>(BaseConfig.DefaultUrl, getRequest); var result = await this._rpcClient.SendRequestAsync <ReceiptResultDto>(request); if (result == null) { throw new Exception(" 获取交易回执方法报空:" + result.ToJson()); } return(result); }