Esempio n. 1
0
        /// <summary>
        /// Sends request to specified url
        /// </summary>
        /// <typeparam name="T">Some type for response deserialization</typeparam>
        /// <param name="jsonRpc">Request body</param>
        /// <param name="jsonSerializerSettings">Specifies json settings</param>
        /// <param name="token">Throws a <see cref="T:System.OperationCanceledException" /> if this token has had cancellation requested.</param>
        /// <returns>Typed JsonRpcResponse</returns>
        public async Task <JsonRpcResponse <T> > ExecuteAsync <T>(IJsonRpcRequest jsonRpc, JsonSerializerSettings jsonSerializerSettings, CancellationToken token)
        {
            if (string.IsNullOrEmpty(UrlToConnect))
            {
                return(null);
            }

            var stringResponse = string.Empty;

            try
            {
                var response = await RepeatPost(jsonRpc.Message, token, MaxRepeatRequest);

                response.EnsureSuccessStatusCode();

                stringResponse = await response.Content.ReadAsStringAsync();

                var prop = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(stringResponse, jsonSerializerSettings);
                prop.RawRequest  = jsonRpc.Message;
                prop.RawResponse = stringResponse;
                return(prop);
            }
            catch (Exception e)
            {
                var resp = new JsonRpcResponse <T>(e)
                {
                    RawRequest  = jsonRpc.Message,
                    RawResponse = stringResponse
                };

                return(resp);
            }
        }
Esempio n. 2
0
        public static IJsonRpcRequest Parse(IHttpContext context)
        {
            IJsonRpcRequest request = Parse(context.Request);

            request.HttpContext = context;
            return(request);
        }
Esempio n. 3
0
        private async Task <JsonRpcResponse <T> > RepeatExecuteAsync <T>(IJsonRpcRequest jsonRpc, JsonSerializerSettings jsonSerializerSettings, byte loop, CancellationToken token)
        {
            if (string.IsNullOrEmpty(UrlToConnect))
            {
                return new JsonRpcResponse <T>(new ArgumentNullException(nameof(UrlToConnect)))
                       {
                           RawRequest = jsonRpc.Message
                       }
            }
            ;

            try
            {
                var content = new StringContent(jsonRpc.Message, Encoding.UTF8, "application/json");

                var response = await HttpClient.PostAsync(UrlToConnect, content, loop, token).ConfigureAwait(false);

                var stringResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                var prop = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(stringResponse, jsonSerializerSettings);
                prop.RawRequest  = jsonRpc.Message;
                prop.RawResponse = stringResponse;
                return(prop);
            }
            catch (Exception ex)
            {
                return(new JsonRpcResponse <T>(ex)
                {
                    RawRequest = jsonRpc.Message
                });
            }
        }
    }
Esempio n. 4
0
        public JsonRpcResponse Execute(IJsonRpcRequest jsonRpc, CancellationToken token)
        {
            SendData(Socket, jsonRpc.Message);
            var responce = ReceiveData(Socket);
            var prop     = JsonRpcResponse.FromString(responce, _jsonSerializerSettings);

            return(prop);
        }
Esempio n. 5
0
        public void ParseRequestWithoutIdShouldReturnNotification()
        {
            IRequest request = A.Fake <IRequest>();

            A.CallTo <string>(() => request.HttpMethod).Returns("POST");
            A.CallTo <Stream>(() => request.InputStream).Returns(GetNotificationStream());
            IJsonRpcRequest msg = JsonRpcMessage.Parse(request);

            Expect.IsInstanceOfType <JsonRpcNotification>(msg);
        }
Esempio n. 6
0
        public void ParseRequestArrayShouldReturnRpcBatch()
        {
            IRequest request = A.Fake <IRequest>();

            A.CallTo <string>(() => request.HttpMethod).Returns("POST");
            A.CallTo <Stream>(() => request.InputStream).Returns(GetRequestBatch());
            IJsonRpcRequest msg = JsonRpcMessage.Parse(request);

            Expect.IsInstanceOfType <JsonRpcBatch>(msg);
        }
Esempio n. 7
0
        /// <summary>
        /// Sends request to specified url
        /// </summary>
        /// <typeparam name="T">Some type for response deserialization</typeparam>
        /// <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>Typed JsonRpcResponse</returns>
        /// <exception cref="T:System.OperationCanceledException">The token has had cancellation requested.</exception>
        public JsonRpcResponse <T> Execute <T>(IJsonRpcRequest jsonRpc, CancellationToken token)
        {
            if (string.IsNullOrEmpty(_url))
            {
                return(null);
            }

            var response = Execute(jsonRpc, token);

            return(response.ToTyped <T>(_jsonSerializerSettings));
        }
Esempio n. 8
0
        protected internal static IJsonRpcRequest Parse(IRequest request)
        {
            IJsonRpcRequest result = null;

            using (StreamReader sr = new StreamReader(request.InputStream))
            {
                string json = sr.ReadToEnd();
                result = Parse(json);
            }

            return(result);
        }
Esempio n. 9
0
        protected override bool Post(IHttpContext context)
        {
            IJsonRpcRequest request = JsonRpcMessage.Parse(context);
            bool            result  = false;

            if (request != null)
            {
                JsonRpcResponse response = request.Execute();
                IRenderer       renderer = RendererFactory.CreateRenderer(context.Request);
                renderer.Render(response.GetOutput(), context.Response.OutputStream);
            }
            return(result);
        }
        /// <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);
        }
Esempio n. 11
0
        /// <summary>
        /// Parse the Json as an RpcMessage the
        /// specific type of the message will depend
        /// on the json itself as described here http://www.jsonrpc.org/specification
        /// </summary>
        /// <returns></returns>
        protected internal static IJsonRpcRequest Parse(string json)
        {
            IJsonRpcRequest result = null;
            JToken          parsed = JToken.Parse(json);
            JArray          batch;

            if (parsed.Is <JObject>())
            {
                result = ParseRequest(parsed, json);
            }
            else if (parsed.Is <JArray>(out batch))
            {
                result = ParseBatch(batch);
            }

            return(result);
        }
Esempio n. 12
0
        public void ParseRequestWithOrderedParams()
        {
            IRequest request = A.Fake <IRequest>();

            A.CallTo <string>(() => request.HttpMethod).Returns("POST");
            A.CallTo <Stream>(() => request.InputStream).Returns(GetRequestWithOrderedParamsStream());
            IJsonRpcRequest msg = JsonRpcMessage.Parse(request);

            Expect.IsInstanceOfType <JsonRpcRequest>(msg);
            JsonRpcRequest rpcRequest = (JsonRpcRequest)msg;

            Expect.IsTrue(rpcRequest.RpcParams.Ordered);
            Expect.IsTrue(rpcRequest.RpcParams.By.Position != null);
            Expect.IsFalse(rpcRequest.RpcParams.Named);
            Expect.IsTrue(rpcRequest.RpcParams.By.Name == null);
            Expect.IsNotNull(rpcRequest.Params);
            Expect.IsTrue(rpcRequest.Params.Is <JArray>(), "Params should have been a JArray");
        }
Esempio n. 13
0
        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);
        }
Esempio n. 14
0
        /// <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)
        {
            if (string.IsNullOrEmpty(_url))
            {
                return(null);
            }

            var content  = new StringContent(jsonRpc.Message);
            var response = _client.PostAsync(_url, content, token).Result;

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var stringResponse = response.Content.ReadAsStringAsync().Result;
                var prop           = JsonRpcResponse.FromString(stringResponse, _jsonSerializerSettings);
                return(prop);
            }

            return(new JsonRpcResponse {
                Error = new HttpResponseError((int)response.StatusCode, "Http Error")
            });
        }
Esempio n. 15
0
        /// <summary>
        /// Sends request to specified url
        /// </summary>
        /// <typeparam name="T">Some type for response deserialization</typeparam>
        /// <param name="jsonRpc">Request body</param>
        /// <param name="jsonSerializerSettings">Specifies json settings</param>
        /// <param name="token"></param>
        /// <returns>Typed JsonRpcResponse</returns>
        public Task <JsonRpcResponse <T> > ExecuteAsync <T>(IJsonRpcRequest jsonRpc, JsonSerializerSettings jsonSerializerSettings, CancellationToken token)
        {
            return(Task.Run(() =>
            {
                if (!OpenIfClosed(token))
                {
                    if (token.IsCancellationRequested)
                    {
                        return new JsonRpcResponse <T>(new OperationCanceledException())
                        {
                            RawRequest = jsonRpc.Message
                        }
                    }
                    ;
                    return new JsonRpcResponse <T>(new TimeoutException())
                    {
                        RawRequest = jsonRpc.Message
                    };
                }

                var waiter = new ManualResetEvent(false);
                lock (_manualResetEventDictionary)
                {
                    _manualResetEventDictionary.Add(jsonRpc.Id, waiter);
                }

                _webSocket.Send(jsonRpc.Message);

                WaitHandle.WaitAny(new[] { token.WaitHandle, waiter }, WaitResponceTimeout);

                lock (_manualResetEventDictionary)
                {
                    if (_manualResetEventDictionary.ContainsKey(jsonRpc.Id))
                    {
                        _manualResetEventDictionary.Remove(jsonRpc.Id);
                    }
                    waiter.Dispose();
                }

                lock (_responseDictionary)
                {
                    if (_responseDictionary.ContainsKey(jsonRpc.Id))
                    {
                        var json = _responseDictionary[jsonRpc.Id];
                        _responseDictionary.Remove(jsonRpc.Id);
                        var response = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(json, jsonSerializerSettings);
                        response.RawResponse = json;
                        response.RawRequest = jsonRpc.Message;
                        return response;
                    }
                }

                if (token.IsCancellationRequested)
                {
                    return new JsonRpcResponse <T>(new OperationCanceledException())
                    {
                        RawRequest = jsonRpc.Message
                    }
                }
                ;
                return new JsonRpcResponse <T>(new TimeoutException())
                {
                    RawRequest = jsonRpc.Message
                };
            }, token));
        }
        /// <summary>
        /// Sends request to specified url
        /// </summary>
        /// <typeparam name="T">Some type for response deserialization</typeparam>
        /// <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>Typed JsonRpcResponse</returns>
        /// <exception cref="T:System.OperationCanceledException">The token has had cancellation requested.</exception>
        public JsonRpcResponse <T> Execute <T>(IJsonRpcRequest jsonRpc, CancellationToken token)
        {
            var response = Execute(jsonRpc, token);

            return(response.ToTyped <T>(_jsonSerializerSettings));
        }
Esempio n. 17
0
 /// <summary>
 /// Sends request to specified url.
 /// </summary>
 /// <typeparam name="T">Some type for response deserialization</typeparam>
 /// <param name="jsonRpc">Request body</param>
 /// <param name="jsonSerializerSettings">Specifies json settings</param>
 /// <param name="token">Throws a <see cref="T:System.OperationCanceledException" /> if this token has had cancellation requested.</param>
 /// <returns>Typed JsonRpcResponse</returns>
 public async Task <JsonRpcResponse <T> > RepeatExecuteAsync <T>(IJsonRpcRequest jsonRpc, JsonSerializerSettings jsonSerializerSettings, CancellationToken token)
 {
     return(await RepeatExecuteAsync <T>(jsonRpc, jsonSerializerSettings, HttpClient.MaxRequestRepeatCount, token).ConfigureAwait(false));
 }
Esempio n. 18
0
        public Task<Response> SendRequestAsync(IJsonRpcRequest userJsonRpcRequest)
        {
            var jsonRpcRequest = JsonRpcRequest.Factory.CreateJsonRpcRequest(userJsonRpcRequest.GetCommand(), userJsonRpcRequest.GetContent());
            var jsonRpcJObject = JObject.FromObject(jsonRpcRequest);
            var streamCommand = JObjectStreamCommand.Factory.Create(jsonRpcJObject);

            var requestTaskCompletionSource = new TaskCompletionSource<Response>();

            _sendToClientQueue.Enqueue(streamCommand);

            if (!_incompleteJsonRpcRequests.TryAdd(jsonRpcRequest.Id, requestTaskCompletionSource))
            {
                // this shouldn't throw
                throw new Exception();
            }

            return requestTaskCompletionSource.Task;
        }