Esempio n. 1
0
 public static JsonRpcResponse CreateSuccessfulJsonRpcResponse(JsonRpcRequest request, JToken result)
 {
     return new JsonRpcResponse(request)
     {
         Result = result
     };
 }
Esempio n. 2
0
        private JsonRpcResponse OnReceivedSmall(JsonRpcRequest jsonRpcRequest)
        {
            var testModel = jsonRpcRequest.Params.ToObject<SmallObjectTestModel>();
            testModel.ServerReceivedTime = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);

            return JsonRpcResponse.Factory.CreateSuccessfulJsonRpcResponse(jsonRpcRequest, JToken.FromObject(testModel));
        }
Esempio n. 3
0
 private JsonRpcResponse ExecuteCommand(JsonRpcRequest request)
 {
     try
     {
         var json = request.@params == null ? null : [email protected]();
         var result = _processor.Process(request.method, json);
         return new JsonRpcResponse
         {
             jsonrpc = request.jsonrpc,
             result = result,
             error = null,
             id = request.id,
         };
     }
     catch (Exception ex)
     {
         return new JsonRpcResponse
         {
             jsonrpc = request.jsonrpc,
             result = null,
             error = new JsonRpcError
             {
                 code = 1,
                 message = ex.GetBaseException().Message,
                 data = ex,
             },
             id = request.id,
         };
     }
 }
Esempio n. 4
0
 private JsonRpcResponse(JsonRpcRequest request)
 {
     Debug.Assert(request.IsNotification == false, "Cannot respond to a notification.");
     JsonRpc = JsonRpcConstants.Version;
     Error = null;
     Result = null;
     Id = request.Id;
 }
Esempio n. 5
0
        protected JsonRpcResponse(JsonRpcRequest jsonRpcRequest)
        {
            if (jsonRpcRequest.IsNotification)
            {
                throw new NotSupportedException("Cannot respond to a notification.");
            }

            JsonRpc = JsonRpcConstants.Version;
            Id = jsonRpcRequest.Id;
        }
Esempio n. 6
0
        public void ToggleMute()
        {
            var request = new JsonRpcRequest()
            {
                Credentials = this.credentials,
                Id = GetRequestId(),
                Method = "XBMC.ToggleMute"
            };

            client.Execute<JToken>(request, (response, exception) => {});
        }
Esempio n. 7
0
 public static JsonRpcResponse CreateErrorJsonRpcResponse(JsonRpcRequest request, String errorMessage)
 {
     return new JsonRpcResponse(request)
     {
         Error = new JsonRpcError()
         {
             Code = 0,
             Message = errorMessage
         }
     };
 }
Esempio n. 8
0
        public void SetVolume(int volume)
        {
            var request = new JsonRpcRequest()
            {
                Credentials = this.credentials,
                Id = GetRequestId(),
                Method = "XBMC.SetVolume",
                Parameters = new JArray { volume }
            };

            client.Execute<JToken>(request, (response, exception) => {});
        }
Esempio n. 9
0
        public void Log(string message)
        {
            var request = new JsonRpcRequest
            {
                Credentials = this.credentials,
                Id = GetRequestId(),
                Method = "XBMC.Log",
                Parameters = new JArray { message  }
            };

            client.Execute<JToken>(request, (response, exception) => {});
        }
Esempio n. 10
0
        public void Log(string message, LogLevel level)
        {
            // All the log levels are lowercase characters.
            var request = new JsonRpcRequest()
            {
                Credentials = this.credentials,
                Id = GetRequestId(),
                Method = "XBMC.Log",
                Parameters = new JArray { message, level.ToString().ToLower() }
            };

            client.Execute<JToken>(request, (response, exception) => {});
        }
Esempio n. 11
0
        public async Task<JsonRpcResponse> SendRequestAsync(JsonRpcRequest jsonRpcRequest)
        {
            Debug.Assert(jsonRpcRequest != null && jsonRpcRequest.Id != null && jsonRpcRequest.Id != String.Empty);

            JTokenStreamContent streamContent = new JTokenStreamContent(JToken.FromObject(jsonRpcRequest));
            TaskCompletionSource<JsonRpcResponse> sendJsonRpcRequestTask = new TaskCompletionSource<JsonRpcResponse>(jsonRpcRequest);
            _outgoingJsonRpcRequests.Enqueue(streamContent);
            _incompleteJsonRpcRequests.AddOrUpdate(jsonRpcRequest.Id, sendJsonRpcRequestTask, (k, v) =>
            {
                Debug.Assert(false, "Should not send requests with the same id.");
                return sendJsonRpcRequestTask;
            });
            return await sendJsonRpcRequestTask.Task;
        }
        private JsonRpcRequest CreateRequest(object[] parameters)
        {
            JsonRpcRequest jsonRequest = new JsonRpcRequest();
            jsonRequest.Id = Guid.NewGuid().ToString(); // TODO: mb int?
            jsonRequest.Method = _operation.Name;
            var args = new JObject();

            int paramIndex = 0;
            foreach (var parameter in _requestMessage.Body.Parts) {
                var token = JToken.FromObject(parameters[paramIndex]);
                args.Add(new JProperty(parameter.Name, token));
                paramIndex++;
            }

            jsonRequest.Params = args;

            return jsonRequest;
        }
Esempio n. 13
0
        private void OnReceivedRequestHandler(object sender, JsonRpcRequest jsonRpcRequest)
        {
            JsonRpcResponse jsonRpcResponse;
            switch (jsonRpcRequest.Method)
            {
                case "Large":
                    jsonRpcResponse = OnReceivedLarge(jsonRpcRequest);
                    break;
                case "Small":
                    jsonRpcResponse = OnReceivedSmall(jsonRpcRequest);
                    break;
                default:
                    throw new NotSupportedException();
            }

            if (!jsonRpcRequest.IsNotification)
            {
                _jsonRpcStreamClient.SendResponseToClient(jsonRpcResponse);
            }
        }
Esempio n. 14
0
 protected JsonRpcResponse(JsonRpcRequest request, JsonRpcError error)
     : this(request)
 {
     Error = error;
 }
Esempio n. 15
0
 public void SendResponse(JsonRpcRequest request)
 {
     client.SendResponse(request, new Dictionary <string, object>());
 }
Esempio n. 16
0
 private async Task <JsonRpcResponse> ExecuteAsync(JsonRpcRequest request, string methodName,
                                                   (MethodInfo Info, bool ReadOnly) method, JsonRpcContext context)
Esempio n. 17
0
        /// <summary>
        /// Create and execute custom json-rpc method
        /// </summary>
        /// <typeparam name="T">Custom type. JsonConvert will try to convert json-response to you custom object</typeparam>
        /// <param name="api">api name</param>
        /// <param name="method">Sets json-rpc "method" field</param>
        /// <param name="token">Throws a <see cref="T:System.OperationCanceledException" /> if this token has had cancellation requested.</param>
        /// <param name="data">Sets to json-rpc params field. JsonConvert use`s for convert array of data to string.</param>
        /// <returns></returns>
        /// <exception cref="T:System.OperationCanceledException">The token has had cancellation requested.</exception>
        public Task <JsonRpcResponse <T> > CustomGetRequestAsync <T>(string api, string method, object[] data, CancellationToken token)
        {
            var jsonRpc = new JsonRpcRequest(JsonSerializerSettings, api, method, data);

            return(ConnectionManager.RepeatExecuteAsync <T>(jsonRpc, JsonSerializerSettings, token));
        }
Esempio n. 18
0
        private async ValueTask sendMessage(CancellationToken cancelToken, ClientWebSocket cws, JsonRpcRequest request)
        {
            var _json_string = JsonConvert.SerializeObject(request);

#if DEBUG
            DRLogger.SNG.WriteC(this, _json_string);
#endif

            var _message = Encoding.UTF8.GetBytes(_json_string);
            await cws.SendAsync(
                new ArraySegment <byte>(_message),
                WebSocketMessageType.Text,
                endOfMessage : true,
                cancellationToken : cancelToken
                );
        }
Esempio n. 19
0
        /// <summary>
        /// Create and execute custom json-rpc method
        /// </summary>
        /// <param name="method">Sets json-rpc "method" field</param>
        /// <param name="token">Throws a <see cref="T:System.OperationCanceledException" /> if this token has had cancellation requested.</param>
        /// <param name="data">Sets to json-rpc params field. JsonConvert use`s for convert array of data to string.</param>
        /// <returns></returns>
        /// <exception cref="T:System.OperationCanceledException">The token has had cancellation requested.</exception>
        public JsonRpcResponse CustomGetRequest(string method, CancellationToken token, params object[] data)
        {
            var jsonRpc = new JsonRpcRequest(_jsonSerializerSettings, method, data);

            return(_connectionManager.Execute(jsonRpc, token));
        }
Esempio n. 20
0
 private static JsonRpcResponse CreateErrorResponse(JsonRpcRequest request, JsonRpcError error)
 {
     return new JsonRpcResponse(request, error);
 }
Esempio n. 21
0
        public void GetVolumn(Action<int, Exception> callback)
        {
            var request = new JsonRpcRequest()
            {
                Credentials = this.credentials,
                Id = GetRequestId(),
                Method = "XBMC.GetVolume"
            };

            client.Execute<int>(request, (rpcResponse, exception) =>
                {
                    if (exception != null)
                    {
                        callback(0, exception);
                    }
                    else
                    {
                        callback(rpcResponse.Result, null);
                    }
                });

            return ;
        }
Esempio n. 22
0
        public T MakeRequest <T>(Methods method, params object[] parameters)
        {
            var jsonRpcRequest = new JsonRpcRequest(1, method.ToString(), parameters);
            var webRequest     = (HttpWebRequest)WebRequest.Create(_url);

            SetBasicAuthHeader(webRequest, _user, _pwd);
            webRequest.Credentials = new NetworkCredential(_user, _pwd);
            webRequest.ContentType = "application/json-rpc";
            webRequest.Method      = "POST";
            webRequest.Proxy       = null;
            webRequest.Timeout     = 3000;
            var byteArray = jsonRpcRequest.GetBytes();

            webRequest.ContentLength = jsonRpcRequest.GetBytes().Length;

            using (var dataStream = webRequest.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Dispose();
            }

            try
            {
                string json;

                using (var webResponse = webRequest.GetResponse())
                {
                    using (var stream = webResponse.GetResponseStream())
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            var result = reader.ReadToEnd();
                            reader.Dispose();
                            json = result;
                        }
                    }
                }

                var rpcResponse = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(json);
                return(rpcResponse.Result);
            }
            catch (WebException webException)
            {
                var webResponse = webException.Response as HttpWebResponse;

                if (webResponse != null)
                {
                    switch (webResponse.StatusCode)
                    {
                    case HttpStatusCode.InternalServerError:
                    {
                        using (var stream = webResponse.GetResponseStream())
                        {
                            if (stream == null)
                            {
                                throw new Exception("The RPC request was either not understood by the server or there was a problem executing the request", webException);
                            }

                            using (var reader = new StreamReader(stream))
                            {
                                var result = reader.ReadToEnd();
                                reader.Dispose();

                                try
                                {
                                    var jsonRpcResponseObject = JsonConvert.DeserializeObject <JsonRpcResponse <object> >(result);

                                    //var internalServerErrorException = new Exception(jsonRpcResponseObject.Error.Message, webException)
                                    //{
                                    //    RpcErrorCode = jsonRpcResponseObject.Error.Code
                                    //};

                                    //throw internalServerErrorException;
                                    throw new Exception(result, webException);
                                }
                                catch (JsonException)
                                {
                                    throw new Exception(result, webException);
                                }
                            }
                        }
                    }

                    default:
                        throw new Exception("Unhandled web exception", webException);
                    }
                }

                if (webException.Message == "The operation has timed out")
                {
                    throw new Exception(webException.Message);
                }

                throw new Exception("An unknown web exception occured while trying to read the response", webException);
            }
            catch (Exception ex)
            {
                throw new Exception($"A problem was encountered while calling MakeRpcRequest() for: {jsonRpcRequest.Method}", ex);
            }
        }
Esempio n. 23
0
        public JsonRpcResponse <T> MakeRequest <T>(string rpcMethod, object parameters, string id = "KodiJSON-RPC", int timeout = 50000)
        {
            var jsonRpcRequest = new JsonRpcRequest
            {
                Id         = id,
                Method     = rpcMethod,
                Parameters = parameters
            };

            if (Convert.ToBoolean(ConfigurationManager.AppSettings["Debug"]))
            {
                Console.WriteLine(jsonRpcRequest.ToString());
            }

            var uri = $"{_service.Host}:{_service.Port}/jsonrpc";

            var webRequest = (HttpWebRequest)WebRequest.Create(uri);

            webRequest.ContentType = "application/json-rpc";
            webRequest.KeepAlive   = false;
            webRequest.Method      = "POST";
            webRequest.Timeout     = timeout;
            webRequest.Credentials = new NetworkCredential(_service.Username, _service.Password);

            try
            {
                using (var requestStream = webRequest.GetRequestStream())
                {
                    using (var requestWriter = new StreamWriter(requestStream))
                    {
                        requestWriter.Write(jsonRpcRequest.ToString());
                    }
                }
            }
            catch (Exception e)
            {
                throw new RpcException("There was a problem sending the request to Kodi.", e);
            }

            try
            {
                string json;

                using (var webResponse = webRequest.GetResponse())
                {
                    using (var responseStream = webResponse.GetResponseStream())
                    {
                        if (responseStream == null)
                        {
                            throw new RpcException("Response stream is empty.");
                        }

                        using (var responseReader = new StreamReader(responseStream, Encoding.UTF8))
                        {
                            json = responseReader.ReadToEnd();
                        }
                    }
                }

                var rpcResponse = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(json);

                if (rpcResponse.Error == null)
                {
                    return(rpcResponse);
                }

                var internalServerErrorException = new RpcInternalServerErrorException(rpcResponse.Error)
                {
                    RpcErrorCode = rpcResponse.Error.Code
                };

                throw internalServerErrorException;
            }
            catch (WebException e)
            {
                var webResponse = e.Response as HttpWebResponse;

                if (webResponse != null)
                {
                    switch (webResponse.StatusCode)
                    {
                    case HttpStatusCode.InternalServerError:
                    {
                        using (var stream = webResponse.GetResponseStream())
                        {
                            if (stream == null)
                            {
                                throw new RpcException("The RPC request was either not understood by the server or there was a problem executing the request", e);
                            }

                            using (var reader = new StreamReader(stream))
                            {
                                var result = reader.ReadToEnd();
                                reader.Dispose();

                                try
                                {
                                    var jsonRpcResponseObject = JsonConvert.DeserializeObject <JsonRpcResponse <object> >(result);

                                    var internalServerErrorException = new RpcInternalServerErrorException(jsonRpcResponseObject.Error.Message, e)
                                    {
                                        RpcErrorCode = jsonRpcResponseObject.Error.Code
                                    };

                                    throw internalServerErrorException;
                                }
                                catch (JsonException)
                                {
                                    throw new RpcException(result, e);
                                }
                            }
                        }
                    }

                    default:
                        throw new RpcException("The RPC request was either not understood by the server or there was a problem executing the request", e);
                    }
                }

                if (e.Message == "The operation has timed out")
                {
                    throw new RpcRequestTimeoutException(e.Message);
                }

                throw new RpcException("An unknown web exception occured while trying to read the JSON response", e);
            }
            catch (JsonException e)
            {
                throw new RpcResponseDeserializationException(
                          "There was a problem deserializing the response from Kodi.", e);
            }
            catch (ProtocolViolationException e)
            {
                throw new RpcException("Unable to connect to the server.", e);
            }
            catch (Exception e)
            {
                throw new Exception($"A problem was encountered while calling MakeRpcRequest() for: {jsonRpcRequest.Method} with request object {jsonRpcRequest}:  \nException: {e.Message}"); // with parameters: {qryParams}. \nException: {e.Message}");
            }
        }
Esempio n. 24
0
        private dynamic odooServerCall <T>(string url, JsonRpcRequestParameter parameter)
        {
            var    tmpData        = new JsonRpcRequest(parameter);
            string requestContent = "";

            // this.Password = Settings.UserPassword;

            if (Device.RuntimePlatform == "Android")
            {
                requestContent = JsonConvert.SerializeObject(tmpData);
            }
            else
            {
                //Dictionary<string, dynamic> paramsDic = new Dictionary<string, dynamic>();
                //paramsDic.Add("service", parameter.Service);
                //paramsDic.Add("method", parameter.Method);
                //paramsDic.Add("args", parameter.Argument);

                //Dictionary<string, dynamic> jObj = new Dictionary<string, dynamic>();
                //jObj.Add("jsonrpc", "2.0");
                //jObj.Add("method", "call");
                //jObj.Add("params", paramsDic);

                //var formatData = JsonConvert.SerializeObject(jObj);
                //requestContent = formatData;
            }
            System.Diagnostics.Debug.WriteLine("WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW " + requestContent);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));

            request.ContentType = "application/json";
            request.Method      = "POST";
            try
            {
                App.responseState = true;
                App.NetAvailable  = true;
                IAsyncResult resultRequest = request.BeginGetRequestStream(null, null);
                Stream       streamInput   = request.EndGetRequestStream(resultRequest);
                byte[]       byteArray     = Encoding.UTF8.GetBytes(requestContent);
                streamInput.WriteAsync(byteArray, 0, byteArray.Length);
                streamInput.FlushAsync();

                // Receive data from server
                IAsyncResult    resultResponse = request.BeginGetResponse(null, null);
                HttpWebResponse response       = (HttpWebResponse)request.EndGetResponse(resultResponse);
                Stream          streamResponse = response.GetResponseStream();
                StreamReader    streamRead     = new StreamReader(streamResponse);
                var             resultData     = streamRead.ReadToEndAsync();
                var             responseData   = resultData.Result;
                streamResponse.FlushAsync();

                if (Device.RuntimePlatform == "iOS")
                {
                    string rspData = string.Join("", responseData);
                    try
                    {
                        JObject jsonObj = JObject.Parse(rspData);
                        Dictionary <string, dynamic> dictObj = jsonObj.ToObject <Dictionary <string, dynamic> >();
                        return(dictObj["result"]);
                    }
                    catch (Exception ea)
                    {
                        return(responseData);
                    }
                }
                else
                {
                    try
                    {
                        JsonRpcResponse <T> jsonRpcResponse = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(responseData);
                        if (jsonRpcResponse.Error != null)
                        {
                            return("Odoo Error");
                        }
                        else
                        {
                            return(jsonRpcResponse.Result);
                        }
                    }
                    catch (Exception ea)
                    {
                        return(responseData);
                    }
                }
            }
            catch (Exception ea)
            {
                if (ea.Message.Contains("(Network is unreachable)") || ea.Message.Contains("NameResolutionFailure"))
                {
                    App.NetAvailable = false;
                }

                else if (ea.Message.Contains("(503) Service Unavailable"))
                {
                    App.responseState = false;
                }

                System.Diagnostics.Debug.WriteLine(ea.Message);
                //  throw;
            }
            return(default(T));
        }
Esempio n. 25
0
        public void PlayEpisode(int id)
        {
            JObject args = new JObject();
            args.Add(new JProperty("episodeid", id));

            var request = new JsonRpcRequest
            {
                Credentials = this.credentials,
                Id = GetRequestId(),
                Method = "XBMC.Play",
                Parameters = args
            };

            client.Execute<JToken>(request, (response, exception) => { });
        }
Esempio n. 26
0
 protected JsonRpcResponse(JsonRpcRequest request, Object result)
     : this(request)
 {
     Result = JToken.FromObject(result);
 }
Esempio n. 27
0
 private StringContent GetPayload(JsonRpcRequest request)
 => new StringContent(new EthereumJsonSerializer().Serialize(request), Encoding.UTF8, "application/json");
Esempio n. 28
0
 public void SendResponse(JsonRpcRequest request, object response)
 {
     client.SendResponse(request, response);
 }
Esempio n. 29
0
        public void SendNotificationAsync(JsonRpcRequest jsonRpcRequest)
        {
            Debug.Assert(jsonRpcRequest != null && jsonRpcRequest.Id != null && jsonRpcRequest.Id != String.Empty);
            Debug.Assert(jsonRpcRequest.IsNotification == true);

            JTokenStreamContent streamContent = new JTokenStreamContent(JToken.FromObject(jsonRpcRequest));
            _outgoingJsonRpcRequests.Enqueue(streamContent);
        }
Esempio n. 30
0
 private static JsonRpcResponse CreateGoodResponse(JsonRpcRequest request, Object result)
 {
     return new JsonRpcResponse(request, result);
 }
Esempio n. 31
0
 public void SendRequestToClient(JsonRpcRequest request)
 {
     AddJObjectToQueueAsync(JObject.FromObject(request));
 }
        public T MakeRequest <T>(RpcMethods rpcMethod, params object[] parameters)
        {
            id++;
            var jsonRpcRequest = new JsonRpcRequest(id, rpcMethod.ToString(), parameters);
            var webRequest     = (HttpWebRequest)WebRequest.Create(_coinService.Parameters.SelectedDaemonUrl);

            byte[] byteArray;

            if (rpcMethod == RpcMethods.stop) /* Dirty workaround to properly support json notification syntax, lets merge this into library later properly*/
            {
                var jsonRpcRequestNotification = new JsonRpcRequestNotification(rpcMethod.ToString(), parameters);
                SetBasicAuthHeader(webRequest, _coinService.Parameters.RpcUsername, _coinService.Parameters.RpcPassword);
                webRequest.Credentials = new NetworkCredential(_coinService.Parameters.RpcUsername, _coinService.Parameters.RpcPassword);

                webRequest.ContentType = "application/json-rpc";
                webRequest.Method      = "POST";
                webRequest.Proxy       = null;
                webRequest.Timeout     = _coinService.Parameters.RpcRequestTimeoutInSeconds * GlobalConstants.MillisecondsInASecond;
                byteArray = jsonRpcRequestNotification.GetBytes();
                webRequest.ContentLength = jsonRpcRequestNotification.GetBytes().Length;
            }
            else if (rpcMethod == RpcMethods.waitforchange) /* Latest XAYA library addition pases waitforchange arguments as array, this also needs special handling*/
            {
                string[] aRR = new string[parameters.Length];

                for (int s = 0; s < parameters.Length; s++)
                {
                    aRR[s] = parameters[s].ToString();
                }

                var jsonRpcRequestNotification = new JsonRpcRequestArray(id, rpcMethod.ToString(), aRR);
                SetBasicAuthHeader(webRequest, _coinService.Parameters.RpcUsername, _coinService.Parameters.RpcPassword);
                webRequest.Credentials = new NetworkCredential(_coinService.Parameters.RpcUsername, _coinService.Parameters.RpcPassword);

                webRequest.ContentType = "application/json-rpc";
                webRequest.Method      = "POST";
                webRequest.Proxy       = null;
                webRequest.Timeout     = _coinService.Parameters.RpcRequestTimeoutInSeconds * GlobalConstants.MillisecondsInASecond;
                byteArray = jsonRpcRequestNotification.GetBytes();
                webRequest.ContentLength = jsonRpcRequestNotification.GetBytes().Length;
            }
            else
            {
                SetBasicAuthHeader(webRequest, _coinService.Parameters.RpcUsername, _coinService.Parameters.RpcPassword);
                webRequest.Credentials = new NetworkCredential(_coinService.Parameters.RpcUsername, _coinService.Parameters.RpcPassword);

                webRequest.ContentType = "application/json-rpc";
                webRequest.Method      = "POST";
                webRequest.Proxy       = null;
                webRequest.Timeout     = _coinService.Parameters.RpcRequestTimeoutInSeconds * GlobalConstants.MillisecondsInASecond;
                byteArray = jsonRpcRequest.GetBytes();
                webRequest.ContentLength = jsonRpcRequest.GetBytes().Length;
            }

            if (rpcMethod == RpcMethods.waitforchange) /* Dirty workaround to properly support json notification syntax, lets merge this into library later properly*/
            {
                webRequest.Timeout = int.MaxValue;
            }

            try
            {
                using (var dataStream = webRequest.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    dataStream.Dispose();
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("There was a problem sending the request to the wallet", exception);
                return(default(T));
            }

            try
            {
                string json;

                using (var webResponse = webRequest.GetResponse())
                {
                    using (var stream = webResponse.GetResponseStream())
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            var result = reader.ReadToEnd();
                            reader.Dispose();
                            json = result;
                        }
                    }
                }

                if (json != "")
                {
                    var rpcResponse = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(json);
                    return(rpcResponse.Result);
                }
                else
                {
                    return(default(T));
                }
            }
            catch (WebException webException)
            {
                #region RPC Internal Server Error (with an Error Code)

                var webResponse = webException.Response as HttpWebResponse;

                if (webResponse != null)
                {
                    switch (webResponse.StatusCode)
                    {
                    case HttpStatusCode.InternalServerError:
                    {
                        using (var stream = webResponse.GetResponseStream())
                        {
                            if (stream == null)
                            {
                                throw new RpcException("The RPC request was either not understood by the server or there was a problem executing the request", webException);
                            }

                            using (var reader = new StreamReader(stream))
                            {
                                var result = reader.ReadToEnd();
                                reader.Dispose();

                                try
                                {
                                    var jsonRpcResponseObject = JsonConvert.DeserializeObject <JsonRpcResponse <object> >(result);

                                    var internalServerErrorException = new RpcInternalServerErrorException(jsonRpcResponseObject.Error.Message, webException)
                                    {
                                        RpcErrorCode = jsonRpcResponseObject.Error.Code
                                    };

                                    throw internalServerErrorException;
                                }
                                catch (JsonException)
                                {
                                    throw new RpcException(result, webException);
                                }
                            }
                        }
                    }

                    default:
                        throw new RpcException("The RPC request was either not understood by the server or there was a problem executing the request", webException);
                    }
                }

                #endregion

                #region RPC Time-Out

                if (webException.Message == "The operation has timed out")
                {
                    throw new RpcRequestTimeoutException(webException.Message);
                }

                #endregion

                return(default(T));
            }
            catch (JsonException jsonException)
            {
                throw new RpcResponseDeserializationException("There was a problem deserializing the response from the wallet", jsonException);
            }
            catch (ProtocolViolationException protocolViolationException)
            {
                throw new RpcException("Unable to connect to the server", protocolViolationException);
            }
            catch (Exception exception)
            {
                var queryParameters = jsonRpcRequest.Parameters.Cast <string>().Aggregate(string.Empty, (current, parameter) => current + (parameter + " "));
                throw new Exception($"A problem was encountered while calling MakeRpcRequest() for: {jsonRpcRequest.Method} with parameters: {queryParameters}. \nException: {exception.Message}");
            }
        }
Esempio n. 33
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="message"></param>
 public static void SendCommandQ(JsonRpcRequest message)
 {
     CommandQ.Enqueue(message);
 }