Beispiel #1
0
        private RpcResponse DeserilizeSingleRequest(string json)
        {
            JToken         token      = JToken.Parse(json);
            JsonSerializer serializer = JsonSerializer.Create(this.JsonSerializerSettings);

            switch (token.Type)
            {
            case JTokenType.Object:
                RpcResponse response = token.ToObject <RpcResponse>(serializer);
                return(response);

            case JTokenType.Array:
                return(token.ToObject <List <RpcResponse> >(serializer).SingleOrDefault());

            default:
                throw new Exception("Cannot parse rpc response from server.");
            }
        }
Beispiel #2
0
 /// <summary>
 /// Parses and returns the result of the rpc response as the type specified.
 /// Otherwise throws a parsing exception
 /// </summary>
 /// <typeparam name="T">Type of object to parse the response as</typeparam>
 /// <param name="response">Rpc response object</param>
 /// <param name="returnDefaultIfNull">Returns the type's default value if the result is null. Otherwise throws parsing exception</param>
 /// <returns>Result of response as type specified</returns>
 public static T GetResult <T>(this RpcResponse response, bool returnDefaultIfNull = true)
 {
     if (response.Result == null)
     {
         if (!returnDefaultIfNull && default(T) != null)
         {
             throw new RpcClientParseException($"Unable to convert the result (null) to type '{typeof(T)}'");
         }
         return(default(T));
     }
     try
     {
         return(response.Result.ToObject <T>());
     }
     catch (Exception ex)
     {
         throw new RpcClientParseException($"Unable to convert the result to type '{typeof(T)}'", ex);
     }
 }
Beispiel #3
0
        private List <RpcResponse> DeserilizeBulkRequests(string json)
        {
            JToken         token      = JToken.Parse(json);
            JsonSerializer serializer = JsonSerializer.Create(this.JsonSerializerSettings);

            switch (token.Type)
            {
            case JTokenType.Object:
                RpcResponse response = token.ToObject <RpcResponse>(serializer);
                return(new List <RpcResponse> {
                    response
                });

            case JTokenType.Array:
                return(token.ToObject <List <RpcResponse> >(serializer));

            default:
                throw new Exception("Cannout deserilize rpc response from server.");
            }
        }
Beispiel #4
0
        /// <summary>
        /// Sends the a http request to the server, posting the request in json format
        /// </summary>
        /// <param name="request">Request object that will goto the rpc server</param>
        /// <param name="route">(Optional) Route that will append to the base url if the request method call is not located at the base route</param>
        /// <returns>The response for the sent request</returns>
        private async Task <TResponse> SendAsync <TRequest, TResponse>(TRequest request, string route = null)
        {
            try
            {
                using (HttpClient httpClient = this.GetHttpClient())
                {
                    httpClient.BaseAddress = this.BaseUrl;

                    string              rpcRequestJson      = JsonConvert.SerializeObject(request, this.JsonSerializerSettings);
                    HttpContent         httpContent         = new StringContent(rpcRequestJson, this.Encoding ?? Encoding.UTF8, this.ContentType ?? "application/json");
                    HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(route, httpContent).ConfigureAwait(false);

                    httpResponseMessage.EnsureSuccessStatusCode();

                    string responseJson = await httpResponseMessage.Content.ReadAsStringAsync();

                    try
                    {
                        return(JsonConvert.DeserializeObject <TResponse>(responseJson, this.JsonSerializerSettings));
                    }
                    catch (JsonSerializationException)
                    {
                        RpcResponse rpcResponse = JsonConvert.DeserializeObject <RpcResponse>(responseJson, this.JsonSerializerSettings);
                        if (rpcResponse == null)
                        {
                            throw new RpcClientUnknownException($"Unable to parse response from the rpc server. Response Json: {responseJson}");
                        }
                        throw rpcResponse.Error.CreateException();
                    }
                }
            }
            catch (Exception ex) when(!(ex is RpcClientException) && !(ex is RpcException))
            {
                throw new RpcClientUnknownException("Error occurred when trying to send rpc requests(s)", ex);
            }
        }
Beispiel #5
0
        /// <summary>
        /// Sends the a http request to the server, posting the request in json format
        /// </summary>
        /// <param name="request">Request object that will goto the rpc server</param>
        /// <param name="deserializer">Function to deserialize the json response</param>
        /// <param name="route">(Optional) Route that will append to the base url if the request method call is not located at the base route</param>
        /// <param name="resultTypeResolver">(Optional) Function that will determine the deserialization type for the result based on request id. Otherwise the result will be a json string.</param>
        /// <returns>The response for the sent request</returns>
        private async Task <List <RpcResponse> > SendAsync(IList <RpcRequest> requests, string route = null, Func <RpcId, Type> resultTypeResolver = null)
        {
            if (!requests.Any())
            {
                throw new ArgumentException("There must be at least one rpc request when sending.");
            }
            try
            {
                string requestJson;
                if (requests.Count == 1)
                {
                    requestJson = this.JsonSerializer.Serialize(requests.Single());
                }
                else
                {
                    requestJson = this.JsonSerializer.SerializeBulk(requests);
                }
                Uri uri            = new Uri(this.BaseUrl, route);
                var requestContext = new RequestEventContext(route, requests.ToList(), requestJson);
                ResponseEventContext responseContext = null;
                if (this.Events.OnRequestStartAsync != null)
                {
                    await this.Events.OnRequestStartAsync(requestContext);
                }

                Stopwatch stopwatch = Stopwatch.StartNew();
                try
                {
                    string responseJson;
                    try
                    {
                        responseJson = await this.TransportClient.SendRequestAsync(uri, requestJson);
                    }
                    finally
                    {
                        stopwatch.Stop();
                    }
                    if (string.IsNullOrWhiteSpace(responseJson))
                    {
                        throw new RpcClientParseException("Server did not return a rpc response, just an empty body.");
                    }
                    List <RpcResponse> responses = null;
                    try
                    {
                        if (requests.Count == 1)
                        {
                            Type        resultType = resultTypeResolver?.Invoke(requests.First().Id);
                            RpcResponse response   = this.JsonSerializer.Deserialize(responseJson, resultType);
                            responses = new List <RpcResponse> {
                                response
                            };
                        }
                        else
                        {
                            responses = this.JsonSerializer.DeserializeBulk(responseJson, resultTypeResolver);
                        }
                        responseContext = new ResponseEventContext(stopwatch.Elapsed, responseJson, responses);
                        return(responses);
                    }
                    catch (Exception ex)
                    {
                        responseContext = new ResponseEventContext(stopwatch.Elapsed, responseJson, responses, ex);
                        throw new RpcClientParseException($"Unable to parse response from server: '{responseJson}'", ex);
                    }
                }
                finally
                {
                    if (this.Events.OnRequestCompleteAsync != null)
                    {
                        await this.Events.OnRequestCompleteAsync(responseContext, requestContext);
                    }
                }
            }
            catch (Exception ex) when(!(ex is RpcClientException) && !(ex is RpcException))
            {
                throw new RpcClientUnknownException("Error occurred when trying to send rpc requests(s)", ex);
            }
        }
Beispiel #6
0
 /// <summary>
 /// Sends the specified rpc request to the server (Wrapper for other SendRequestAsync)
 /// </summary>
 /// <param name="method">Rpc method that is to be called</param>
 /// <param name="route">(Optional) Route that will append to the base url if the request method call is not located at the base route</param>
 /// <param name="paramMap">Map of parameters for the rpc method</param>
 /// <typeparam name="T">The deserialization type for the response result.</typeparam>
 /// <returns>The rpc response for the sent request</returns>
 public async Task <RpcResponse <T> > SendRequestWithMapAsync <T>(string method, string route, IDictionary <string, object> paramMap)
 {
     return(RpcResponse <T> .FromResponse(await this.SendRequestWithMapAsync(method, route, paramMap, typeof(T))));
 }
Beispiel #7
0
 /// <summary>
 /// Sends the specified rpc request to the server (Wrapper for other SendRequestAsync)
 /// </summary>
 /// <param name="method">Rpc method that is to be called</param>
 /// <param name="route">(Optional) Route that will append to the base url if the request method call is not located at the base route</param>
 /// <param name="paramList">List of parameters (in order) for the rpc method</param>
 /// <typeparam name="T">The deserialization type for the response result.</typeparam>
 /// <returns>The rpc response for the sent request</returns>
 public async Task <RpcResponse <T> > SendRequestWithListAsync <T>(string method, string route, IList <object> paramList)
 {
     return(RpcResponse <T> .FromResponse(await this.SendRequestWithListAsync(method, route, paramList, typeof(T))));
 }
Beispiel #8
0
 public List <RpcResponse <T> > GetResponses <T>()
 {
     return(this.responses
            .Select(r => RpcResponse <T> .FromResponse(r.Value))
            .ToList());
 }
Beispiel #9
0
 public RpcResponse <T> GetResponse <T>(RpcId id)
 {
     return(RpcResponse <T> .FromResponse(this.responses[id]));
 }