private static async Task <JsonResponse> ProcessInternal(string sessionId, string jsonRpc, JsonRequest jsonRequest, object jsonRpcContext) { var handler = Handler.GetSessionHandler(sessionId); var jsonResponse = new JsonResponse(); if (jsonRequest == null) { jsonResponse.Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32700, "Parse error", "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.")); } else if (jsonRequest.Method == null) { jsonResponse.Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32601, "Invalid Request", "Missing property 'method'")); } else { jsonResponse.Id = jsonRequest.Id; var data = await handler.Handle(jsonRequest, jsonRpcContext); if (data == null) { return(null); } jsonResponse.Error = data.Error; jsonResponse.Result = data.Result; } return(jsonResponse); }
public static void BindService(string sessionID, Object instance) { var item = instance.GetType(); // var item = typeof(T); var methods = item.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Where(m => m.GetCustomAttributes(typeof(JsonRpcMethodAttribute), false).Length > 0); foreach (var meth in methods) { Dictionary <string, Type> paras = new Dictionary <string, Type>(); Dictionary <string, object> defaultValues = new Dictionary <string, object>(); // dictionary that holds default values for optional params. var paramzs = meth.GetParameters(); List <Type> parameterTypeArray = new List <Type>(); for (int i = 0; i < paramzs.Length; i++) { string paramName; var paramAttrs = paramzs[i].GetCustomAttributes(typeof(JsonRpcParamAttribute), false); if (paramAttrs.Length > 0) { paramName = ((JsonRpcParamAttribute)paramAttrs[0]).JsonParamName; if (string.IsNullOrEmpty(paramName)) { paramName = paramzs[i].Name; } } else { paramName = paramzs[i].Name; } // reflection attribute information for optional parameters //http://stackoverflow.com/questions/2421994/invoking-methods-with-optional-parameters-through-reflection paras.Add(paramName, paramzs[i].ParameterType); if (paramzs[i].IsOptional) // if the parameter is an optional, add the default value to our default values dictionary. { defaultValues.Add(paramName, paramzs[i].DefaultValue); } } var resType = meth.ReturnType; paras.Add("returns", resType); // add the return type to the generic parameters list. var atdata = meth.GetCustomAttributes(typeof(JsonRpcMethodAttribute), false); foreach (JsonRpcMethodAttribute handlerAttribute in atdata) { var methodName = handlerAttribute.JsonMethodName == string.Empty ? meth.Name : handlerAttribute.JsonMethodName; var newDel = Delegate.CreateDelegate(System.Linq.Expressions.Expression.GetDelegateType(paras.Values.ToArray()), instance /*Need to add support for other methods outside of this instance*/, meth); var handlerSession = Handler.GetSessionHandler(sessionID); handlerSession.MetaData.AddService(methodName, paras, defaultValues, newDel); } } }
/// <summary> /// The callback will be returned to the user, who needs to invoke it in concrete /// service implementation. Call should be made directly from same thread as /// service method is executed. /// </summary> /// <param name="sessionId">Handler session id</param> /// <returns></returns> public static Action <JsonResponse> GetAsyncProcessCallback(string sessionId = "") { Handler handler; if ("" == sessionId) { handler = Handler.GetSessionHandler(Handler.DefaultSessionId()); } else { handler = Handler.GetSessionHandler(sessionId); } return(handler.GetAsyncCallback()); }
private void buildService(string sessionID) { // get the registerMethod. // Method that matches Func<T,R> var regMethod = typeof(Handler).GetMethod("Register"); // var assem = Assembly.GetExecutingAssembly(); // var TypesWithHandlers = assem.GetTypes().Where(f => f.GetCustomAttributes(typeof(JsonRpcAttribute), false).Length > 0); var item = this.GetType(); var methods = item.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Where(m => m.GetCustomAttributes(typeof(JsonRpcMethodAttribute), false).Length > 0); foreach (var meth in methods) { Dictionary <string, Type> paras = new Dictionary <string, Type>(); Dictionary <string, object> defaultValues = new Dictionary <string, object>(); // dictionary that holds default values for optional params. var paramzs = meth.GetParameters(); List <Type> parameterTypeArray = new List <Type>(); for (int i = 0; i < paramzs.Length; i++) { // reflection attribute information for optional parameters //http://stackoverflow.com/questions/2421994/invoking-methods-with-optional-parameters-through-reflection paras.Add(paramzs[i].Name, paramzs[i].ParameterType); if (paramzs[i].IsOptional) // if the parameter is an optional, add the default value to our default values dictionary. { defaultValues.Add(paramzs[i].Name, paramzs[i].DefaultValue); } } var resType = meth.ReturnType; paras.Add("returns", resType); // add the return type to the generic parameters list. var atdata = meth.GetCustomAttributes(typeof(JsonRpcMethodAttribute), false); foreach (JsonRpcMethodAttribute handlerAttribute in atdata) { var methodName = handlerAttribute.JsonMethodName == string.Empty ? meth.Name : handlerAttribute.JsonMethodName; var newDel = Delegate.CreateDelegate(System.Linq.Expressions.Expression.GetDelegateType(paras.Values.ToArray()), this /*Need to add support for other methods outside of this instance*/, meth); var handlerSession = Handler.GetSessionHandler(sessionID); regMethod.Invoke(handlerSession, new object[] { methodName, newDel }); handlerSession.MetaData.AddService(methodName, paras, defaultValues); } } }
public static Handler InitMethodHandler(string sessionID, MethodInfo method, object instance) { Dictionary <string, Type> paras = new Dictionary <string, Type>(); Dictionary <string, object> defaultValues = new Dictionary <string, object>(); // dictionary that holds default values for optional params. var paramzs = method.GetParameters(); List <Type> parameterTypeArray = new List <Type>(); for (int i = 0; i < paramzs.Length; i++) { // reflection attribute information for optional parameters //http://stackoverflow.com/questions/2421994/invoking-methods-with-optional-parameters-through-reflection paras.Add(paramzs[i].Name, paramzs[i].ParameterType); if (paramzs[i].IsOptional) // if the parameter is an optional, add the default value to our default values dictionary. { defaultValues.Add(paramzs[i].Name, paramzs[i].DefaultValue); } } var resType = method.ReturnType; paras.Add("returns", resType); // add the return type to the generic parameters list. var handlerSession = Handler.GetSessionHandler(sessionID); var atdata = method.GetCustomAttributes(typeof(JsonRpcMethodAttribute), false); foreach (JsonRpcMethodAttribute handlerAttribute in atdata) { var methodName = handlerAttribute.JsonMethodName == string.Empty ? method.DeclaringType.FullName + "." + method.Name : handlerAttribute.JsonMethodName; var newDel = Delegate.CreateDelegate(System.Linq.Expressions.Expression.GetDelegateType(paras.Values.ToArray()), instance /*Need to add support for other methods outside of this instance*/, method); handlerSession.Register(methodName, newDel); //regMethod.Invoke(handlerSession, new object[] { methodName, newDel }); handlerSession.MetaData.AddService(methodName, paras, defaultValues, method); } return(handlerSession); }
private static async Task <string> ProcessInternal(string sessionId, string jsonRpc, object jsonRpcContext) { var handler = Handler.GetSessionHandler(sessionId); JsonRequest[] batch = null; bool singleBatch; try { batch = DeserializeRequest(jsonRpc, out singleBatch); } catch (Exception ex) { return(Newtonsoft.Json.JsonConvert.SerializeObject(new JsonResponse { Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32700, "Parse error", ex)) })); } JsonResponse[] jsonResponses = await ProcessInternal(sessionId, jsonRpc, batch, jsonRpcContext); return(SerializeResponse(jsonResponses, singleBatch)); }
private static async Task <JsonResponse[]> ProcessInternal(string sessionId, string jsonRpc, JsonRequest[] jsonRequests, object jsonRpcContext) { var handler = Handler.GetSessionHandler(sessionId); if (jsonRequests.Length == 0) { return(new JsonResponse[] { new JsonResponse { Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32600, "Invalid Request", "Batch of calls was empty.")) } }); } List <JsonResponse> jsonResponses = null; for (var i = 0; i < jsonRequests.Length; i++) { var jsonRequest = jsonRequests[i]; var jsonResponse = await ProcessInternal(sessionId, jsonRpc, jsonRequest, jsonRpcContext); // single rpc optimization if (jsonRequests.Length == 1 && (jsonResponse.Id != null || jsonResponse.Error != null)) { return(new JsonResponse[] { jsonResponse }); } if (jsonResponses == null) { jsonResponses = new List <JsonResponse>(); } jsonResponses.Add(jsonResponse); } return(jsonResponses.ToArray()); }
/// <summary> /// For exceptions thrown after the routed method has been called. /// Allows you to specify an error handler that will be invoked prior to returning the JsonResponse to the client. /// You are able to modify the error that is returned inside the provided handler. /// </summary> /// <param name="sessionId"></param> /// <param name="handler"></param> public static void SetErrorHandler(string sessionId, Func <JsonRequest, JsonRpcException, JsonRpcException> handler) { Handler.GetSessionHandler(sessionId).SetErrorHandler(handler); }
/// <summary> /// Sets the PreProcessing Handler on a specific session /// </summary> /// <param name="sessionId"></param> /// <param name="handler"></param> public static void SetBeforeProcessHandler(string sessionId, PreProcessHandler handler) { Handler.GetSessionHandler(sessionId).SetPreProcessHandler(handler); }
/// <summary> /// For exceptions thrown during parsing and prior to a routed method being called. /// Allows you to specify an error handler that will be invoked prior to returning the JsonResponse to the client. /// You are able to modify the error that is returned inside the provided handler. /// </summary> /// <param name="sessionId"></param> /// <param name="handler"></param> public static void SetParseErrorHandler(string sessionId, Func <string, JsonRpcException, JsonRpcException> handler) { Handler.GetSessionHandler(sessionId).SetParseErrorHandler(handler); }
internal static void ProcessJsonRpcState(string sessionId, JsonRpcStateAsync async, object jsonRpcContext = null) { var context = async.AsyncState; JsonRequest[] rpcBatch = null; JsonResponse[] responseBatch = null; JsonRequest rpc = null; var handler = Handler.GetSessionHandler(sessionId); var callback = string.Empty; var response = new JsonResponse(); response.Result = null; response.Error = null; string json = async.JsonRpc; if (isSingleRpc(json)) { try { if (json.Length > 0) { rpc = Newtonsoft.Json.JsonConvert.DeserializeObject <JsonRequest>(json); if (rpc == null) { response.Result = null; response.Id = null; response.Error = handler.ProcessParseException(json, new JsonRpcException(-32700, "Parse error", "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.")); } else { response.Id = rpc.Id; if (rpc.Method == null) { response.Result = null; response.Id = rpc.Id; response.Error = handler.ProcessParseException(json, new JsonRpcException(-32600, "Invalid Request", "Missing property 'method'")); } } } else { response.Result = null; response.Id = null; response.Error = handler.ProcessParseException(json, new JsonRpcException(-32600, "Invalid Request", "The JSON sent is not a valid Request object.")); } } catch (Exception ex) { response.Result = null; if (rpc != null) { response.Id = rpc.Id; } response.Error = handler.ProcessParseException(json, new JsonRpcException(-32700, "Parse error", ex)); var result = Newtonsoft.Json.JsonConvert.SerializeObject(response); async.Result = result; async.SetCompleted(); return; } if (response.Error == null && rpc != null && rpc.Method != null) { var data = Handler.GetSessionHandler(sessionId).Handle(rpc, jsonRpcContext); if (data != null) { response.Error = data.Error; response.Result = data.Result; var result = ""; if (response.Id != null) // dont return a result for notifications { result = Newtonsoft.Json.JsonConvert.SerializeObject(response); } async.Result = result; async.SetCompleted(); return; } } var err = Newtonsoft.Json.JsonConvert.SerializeObject(response); async.Result = err; async.SetCompleted(); } else // this is a batch of requests { try { rpcBatch = Newtonsoft.Json.JsonConvert.DeserializeObject <JsonRequest[]>(json); responseBatch = new JsonResponse[rpcBatch.Length]; for (int i = 0; i < rpcBatch.Length; i++) { responseBatch[i] = new JsonResponse(); if (rpcBatch[i] == null) { responseBatch[i].Result = null; responseBatch[i].Id = null; responseBatch[i].Error = handler.ProcessParseException(json, new JsonRpcException(-32700, "Parse error", "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.")); } else { responseBatch[i].Id = rpcBatch[i].Id; if (rpcBatch[i].Method == null) { responseBatch[i].Result = null; responseBatch[i].Error = handler.ProcessParseException(json, new JsonRpcException(-32600, "Invalid Request", "Missing property 'method'")); } } } } catch (Exception ex) { response.Result = null; if (rpc != null) { response.Id = rpc.Id; } response.Error = handler.ProcessParseException(json, new JsonRpcException(-32700, "Parse error", ex)); var result = Newtonsoft.Json.JsonConvert.SerializeObject(response); async.Result = result; async.SetCompleted(); return; } // we should have a batch of RPC at this point var respBuilder = new StringBuilder(); for (int i = 0; i < rpcBatch.Length; i++) { if (i == 0) { respBuilder.Append("["); } if (rpcBatch[i] == null || rpcBatch[i].Method == null) { responseBatch[i].Error = handler.ProcessParseException(json, new JsonRpcException(-32600, "Invalid Request", "Missing property 'method'")); } else if (responseBatch[i].Error == null) { var data = handler.Handle(rpcBatch[i], jsonRpcContext); if (data != null) { responseBatch[i].Error = data.Error; responseBatch[i].Result = data.Result; } } // dont return a response for notifications. if (responseBatch[i].Id != null || responseBatch[i].Error != null) { var result = Newtonsoft.Json.JsonConvert.SerializeObject(responseBatch[i]); respBuilder.Append(result); if (i != rpcBatch.Length - 1) { respBuilder.Append(','); } } if (i == rpcBatch.Length - 1) { respBuilder.Append("]"); var str = respBuilder.ToString(); async.Result = str; async.SetCompleted(); // let IIS think we are completed now. return; } } // if we made it this far, then there were no items in the array response.Id = null; response.Result = null; response.Error = handler.ProcessParseException(json, new JsonRpcException(3200, "Invalid Request", "Batch of calls was empty.")); var err = Newtonsoft.Json.JsonConvert.SerializeObject(response); async.Result = err; async.SetCompleted(); } }
public static Task <string> Process(string sessionId, string jsonRpc, object context = null) { var task = Task <string> .Factory.StartNew((_) => { // use invariant culture - we have to set it explicitly for every thread we create to // prevent any floating-point problems (mostly because of number formats in non en-US cultures). Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; var tup = (Tuple <string, string, object>)_; string _sessionId; string _jsonRpc; object _jsonRpcContext = null; _sessionId = tup.Item1; _jsonRpc = tup.Item2; _jsonRpcContext = tup.Item3; var handler = Handler.GetSessionHandler(_sessionId); JsonRequest[] rpcBatch = null; JsonResponse[] responseBatch = null; JsonRequest rpc = null; var callback = string.Empty; var response = new JsonResponse(); response.Result = null; response.Error = null; string json = _jsonRpc; if (isSingleRpc(json)) { try { if (json.Length > 0) { rpc = Newtonsoft.Json.JsonConvert.DeserializeObject <JsonRequest>(json); if (rpc == null) { response.Result = null; response.Id = null; response.Error = handler.ProcessParseException(json, new JsonRpcException(-32700, "Parse error", "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.")); } else { response.Id = rpc.Id; if (rpc.Method == null) { response.Result = null; response.Id = rpc.Id; response.Error = handler.ProcessParseException(json, new JsonRpcException(-32600, "Invalid Request", "Missing property 'method'")); } } } else { response.Result = null; response.Id = null; response.Error = handler.ProcessParseException(json, new JsonRpcException(-32600, "Invalid Request", "The JSON sent is not a valid Request object.")); } } catch (Exception ex) { response.Result = null; if (rpc != null) { response.Id = rpc.Id; } response.Error = handler.ProcessParseException(json, new JsonRpcException(-32700, "Parse error", ex)); var result = Newtonsoft.Json.JsonConvert.SerializeObject(response); return(result); } if (response.Error == null && rpc != null && rpc.Method != null) { var data = handler.Handle(rpc, _jsonRpcContext); if (data != null) { response.Error = data.Error; response.Result = data.Result; var result = ""; if (response.Id != null)// dont return a result for notifications { result = Newtonsoft.Json.JsonConvert.SerializeObject(response); } return(result); } } var err = Newtonsoft.Json.JsonConvert.SerializeObject(response); return(err); } else // this is a batch of requests { try { rpcBatch = Newtonsoft.Json.JsonConvert.DeserializeObject <JsonRequest[]>(json); responseBatch = new JsonResponse[rpcBatch.Length]; for (int i = 0; i < rpcBatch.Length; i++) { responseBatch[i] = new JsonResponse(); if (rpcBatch[i] == null) { responseBatch[i].Result = null; responseBatch[i].Id = null; responseBatch[i].Error = handler.ProcessParseException(json, new JsonRpcException(-32700, "Parse error", "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.")); } else { responseBatch[i].Id = rpcBatch[i].Id; if (rpcBatch[i].Method == null) { responseBatch[i].Result = null; responseBatch[i].Error = handler.ProcessParseException(json, new JsonRpcException(-32600, "Invalid Request", "Missing property 'method'")); } } } } catch (Exception ex) { response.Result = null; if (rpc != null) { response.Id = rpc.Id; } response.Error = handler.ProcessParseException(json, new JsonRpcException(-32700, "Parse error", ex)); var result = Newtonsoft.Json.JsonConvert.SerializeObject(response); return(result); } // we should have a batch of RPC at this point var respBuilder = new StringBuilder(); for (int i = 0; i < rpcBatch.Length; i++) { if (i == 0) { respBuilder.Append("["); } if (rpcBatch[i] == null || rpcBatch[i].Method == null) { responseBatch[i].Error = handler.ProcessParseException(json, new JsonRpcException(-32600, "Invalid Request", "Missing property 'method'")); } else if (responseBatch[i].Error == null) { var data = Handler.GetSessionHandler(_sessionId).Handle(rpcBatch[i], _jsonRpcContext); if (data != null) { responseBatch[i].Error = data.Error; responseBatch[i].Result = data.Result; } } // dont return a response for notifications. if (responseBatch[i].Id != null || responseBatch[i].Error != null) { var result = Newtonsoft.Json.JsonConvert.SerializeObject(responseBatch[i]); respBuilder.Append(result); if (i != rpcBatch.Length - 1) { respBuilder.Append(','); } } if (i == rpcBatch.Length - 1) { respBuilder.Append("]"); var str = respBuilder.ToString(); return(str); } } // if we made it this far, then there were no items in the array response.Id = null; response.Result = null; response.Error = handler.ProcessParseException(json, new JsonRpcException(3200, "Invalid Request", "Batch of calls was empty.")); var err = Newtonsoft.Json.JsonConvert.SerializeObject(response); return(err); } }, new Tuple <string, string, object>(sessionId, jsonRpc, context)); return(task); }
private static string ProcessInternal(string sessionId, string jsonRpc, object jsonRpcContext) { var handler = Handler.GetSessionHandler(sessionId); JsonRequest[] batch = null; try { if (isSingleRpc(jsonRpc)) { var foo = JsonConvert.DeserializeObject <JsonRequest>(jsonRpc); batch = new[] { foo }; } else { batch = JsonConvert.DeserializeObject <JsonRequest[]>(jsonRpc); } } catch (Exception ex) { return(Newtonsoft.Json.JsonConvert.SerializeObject(new JsonResponse { Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32700, "Parse error", ex)) })); } if (batch.Length == 0) { return(Newtonsoft.Json.JsonConvert.SerializeObject(new JsonResponse { Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(3200, "Invalid Request", "Batch of calls was empty.")) })); } var singleBatch = batch.Length == 1; StringBuilder sbResult = null; for (var i = 0; i < batch.Length; i++) { var jsonRequest = batch[i]; var jsonResponse = new JsonResponse(); if (jsonRequest == null) { jsonResponse.Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32700, "Parse error", "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.")); } else if (jsonRequest.Method == null) { jsonResponse.Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32600, "Invalid Request", "Missing property 'method'")); } else { jsonResponse.Id = jsonRequest.Id; var data = handler.Handle(jsonRequest, jsonRpcContext); if (data == null) { continue; } jsonResponse.JsonRpc = data.JsonRpc; jsonResponse.Error = data.Error; jsonResponse.Result = data.Result; } if (jsonResponse.Result == null && jsonResponse.Error == null) { // Per json rpc 2.0 spec // result : This member is REQUIRED on success. // This member MUST NOT exist if there was an error invoking the method. // Either the result member or error member MUST be included, but both members MUST NOT be included. jsonResponse.Result = new Newtonsoft.Json.Linq.JValue((Object)null); } // special case optimization for single Item batch if (singleBatch && (jsonResponse.Id != null || jsonResponse.Error != null)) { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteStartObject(); if (!string.IsNullOrEmpty(jsonResponse.JsonRpc)) { writer.WritePropertyName("jsonrpc"); writer.WriteValue(jsonResponse.JsonRpc); } if (jsonResponse.Error != null) { writer.WritePropertyName("error"); writer.WriteRawValue(JsonConvert.SerializeObject(jsonResponse.Error)); } else { writer.WritePropertyName("result"); writer.WriteRawValue(JsonConvert.SerializeObject(jsonResponse.Result)); } writer.WritePropertyName("id"); writer.WriteValue(jsonResponse.Id); writer.WriteEndObject(); return(sw.ToString()); //return JsonConvert.SerializeObject(jsonResponse); } else if (jsonResponse.Id == null && jsonResponse.Error == null) { // do nothing sbResult = new StringBuilder(0); } else { // write out the response if (i == 0) { sbResult = new StringBuilder("["); } sbResult.Append(JsonConvert.SerializeObject(jsonResponse)); if (i < batch.Length - 1) { sbResult.Append(','); } else if (i == batch.Length - 1) { sbResult.Append(']'); } } } return(sbResult.ToString()); }
private static void AsyncProcessInternal(string sessionId, string jsonRpc, object jsonRpcContext, Action <string> callback) { Handler handler = Handler.GetSessionHandler(sessionId); Tuple <JsonRequest>[] batch = null; if (isSingleRpc(jsonRpc)) { batch = new[] { Tuple.Create(JsonConvert.DeserializeObject <JsonRequest>(jsonRpc)) }; } else { batch = JsonConvert.DeserializeObject <JsonRequest[]>(jsonRpc) .Select(request => new Tuple <JsonRequest>(request)) .ToArray(); } if (batch.Length == 0) { callback.Invoke(JsonConvert.SerializeObject(new JsonResponse { Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(3200, "Invalid Request", "Batch of calls was empty.")) })); } foreach (var tuple in batch) { JsonRequest jsonRequest = tuple.Item1; JsonResponse jsonResponse = new JsonResponse(); if (jsonRequest == null) { jsonResponse.Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32700, "Parse error", "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.")); } else { jsonResponse.Id = jsonRequest.Id; if (jsonRequest.Method == null) { jsonResponse.Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32600, "Invalid Request", "Missing property 'method'")); } else { handler.Handle(jsonRequest, jsonRpcContext, delegate(JsonResponse a) { a.Id = jsonRequest.Id; if (a.Id != null || a.Error != null) { callback.Invoke(JsonConvert.SerializeObject(a)); } } ); } } } }
private static string ProcessInternal(string sessionId, IEnumerable <JsonRequest> request, object jsonRpcContext) { var handler = Handler.GetSessionHandler(sessionId); Tuple <JsonRequest, JsonResponse>[] batch = null; batch = request .Select(r => new Tuple <JsonRequest, JsonResponse>(r, new JsonResponse())) .ToArray(); if (batch.Length == 0) { return(JsonConvert.SerializeObject(new JsonResponse { Error = handler.ProcessParseException("", new JsonRpcException(3200, "Invalid Request", "Batch of calls was empty.")) })); } foreach (var tuple in batch) { var jsonRequest = tuple.Item1; var jsonResponse = tuple.Item2; if (jsonRequest == null) { jsonResponse.Error = handler.ProcessParseException("", new JsonRpcException(-32700, "Parse error", "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.")); } else { jsonResponse.Id = jsonRequest.Id; if (jsonRequest.Method == null) { jsonResponse.Error = handler.ProcessParseException("", new JsonRpcException(-32600, "Invalid Request", "Missing property 'method'")); } else { var data = handler.Handle(jsonRequest, jsonRpcContext); if (data == null) { continue; } jsonResponse.Error = data.Error; jsonResponse.Result = data.Result; } } } var responses = new string[batch.Count(x => x.Item2.Id != null || x.Item2.Error != null)]; var idx = 0; foreach (var resp in batch.Where(x => x.Item2.Id != null || x.Item2.Error != null)) { responses[idx++] = JsonConvert.SerializeObject(resp.Item2); } return(responses.Length == 0 ? string.Empty : responses.Length == 1 ? responses[0] : string.Format("[{0}]", string.Join(",", responses))); }
public static List <JsonResponse> ProcessReturnResponse(string sessionId, JsonRequest request, object jsonRpcContext = null) { var handler = Handler.GetSessionHandler(sessionId); List <JsonResponse> responselist = new List <JsonResponse>(); Tuple <JsonRequest, JsonResponse>[] batch = null; batch = new[] { Tuple.Create(request, new JsonResponse()) }; if (batch.Length == 0) { responselist.Add(new JsonResponse { Error = handler.ProcessParseException("", new JsonRpcException(3200, "Invalid Request", "Batch of calls was empty.")) }); return(responselist); } foreach (var tuple in batch) { var jsonRequest = tuple.Item1; var jsonResponse = tuple.Item2; if (jsonRequest == null) { jsonResponse.Error = handler.ProcessParseException("", new JsonRpcException(-32700, "Parse error", "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.")); jsonResponse.Success = false; } else { jsonResponse.Id = jsonRequest.Id; if (jsonRequest.Method == null) { jsonResponse.Error = handler.ProcessParseException("", new JsonRpcException(-32600, "Invalid Request", "Missing property 'method'")); jsonResponse.Success = false; } else { var data = handler.Handle(jsonRequest, jsonRpcContext); if (data == null) { continue; } jsonResponse.Error = data.Error; jsonResponse.Result = data.Result; jsonResponse.Success = jsonResponse.Error == null; } } responselist.Add(jsonResponse); } var responses = new string[batch.Count(x => x.Item2.Id != null || x.Item2.Error != null)]; //foreach (var resp in batch.Where(x => x.Item2.Id != null || x.Item2.Error != null)) //{ // responselist.Add(resp.Item2); //} return(responselist); }
private static string ProcessInternal(string sessionId, string jsonRpc, object jsonRpcContext) { var handler = Handler.GetSessionHandler(sessionId); try { Tuple <JsonRequest, JsonResponse>[] batch = null; if (isSingleRpc(jsonRpc)) { batch = new[] { Tuple.Create(JsonConvert.DeserializeObject <JsonRequest>(jsonRpc), new JsonResponse()) }; } else { batch = JsonConvert.DeserializeObject <JsonRequest[]>(jsonRpc) .Select(request => new Tuple <JsonRequest, JsonResponse>(request, new JsonResponse())) .ToArray(); } if (batch.Length == 0) { return(Newtonsoft.Json.JsonConvert.SerializeObject(new JsonResponse { Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(3200, "Invalid Request", "Batch of calls was empty.")) })); } foreach (var tuple in batch) { var jsonRequest = tuple.Item1; var jsonResponse = tuple.Item2; if (jsonRequest == null) { jsonResponse.Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32700, "Parse error", "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.")); } else { jsonResponse.Id = jsonRequest.Id; if (jsonRequest.Method == null) { jsonResponse.Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32600, "Invalid Request", "Missing property 'method'")); } else { var data = handler.Handle(jsonRequest, jsonRpcContext); if (data == null) { continue; } jsonResponse.Error = data.Error; jsonResponse.Result = data.Result; } } } var responses = new string[batch.Count(x => x.Item2.Id != null || x.Item2.Error != null)]; var idx = 0; foreach (var resp in batch.Where(x => x.Item2.Id != null || x.Item2.Error != null)) { if (resp.Item2.Result == null && resp.Item2.Error == null) { // Per json rpc 2.0 spec // result : This member is REQUIRED on success. // This member MUST NOT exist if there was an error invoking the method. // Either the result member or error member MUST be included, but both members MUST NOT be included. resp.Item2.Result = new Newtonsoft.Json.Linq.JValue((Object)null); } responses[idx++] = JsonConvert.SerializeObject(resp.Item2); } return(responses.Length == 0 ? string.Empty : responses.Length == 1 ? responses[0] : string.Format("[{0}]", string.Join(",", responses))); } catch (Exception ex) { return(Newtonsoft.Json.JsonConvert.SerializeObject(new JsonResponse { Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32700, "Parse error", ex)) })); } }