Exemple #1
0
        public ExplainResult Explain(ISearch search, string type, string id)
        {
            IJsonRequest request = CommandContext.RequestFactory.CreateRequest(GetUrl(type, id), HttpVerbs.Post, ExplicitRequestTimeout);

            try
            {
                var context = new SearchContext();
                search.ApplyActions(context);
                string requestBody = CommandContext.Serializer.Serialize(context.RequestBody);
                request.WriteBody(requestBody);
                using (var stringReader = new StringReader(request.GetResponse()))
                {
                    ExplainResult explain = CommandContext.Serializer.Deserialize <ExplainResult>(new JsonTextReader(stringReader));
                    return(explain);
                }
            }
            catch (WebException ex)
            {
                string message = ex.Message;
                if (ex.Response.IsNotNull())
                {
                    string end = new StreamReader(ex.Response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
                    message = message + Environment.NewLine + end;
                }
                throw new WebException(message, ex);
            }
        }
Exemple #2
0
        public TResponse SendMessage <TResponse>(IJsonRequest <TResponse> request)
            where TResponse : new()
        {
            var jsonString  = JsonConvert.SerializeObject(request);
            var requestData = Encoding.UTF8.GetBytes(jsonString);

            if (requestData.Length > sendMaxBufferLength)
            {
                throw new ArgumentException(string.Format("Request exceeds the max buffer length of {0}", sendMaxBufferLength));
            }

            lock (socket)
            {
                socket.SendAsync(new ArraySegment <byte>(requestData, 0, requestData.Length), WebSocketMessageType.Text, true, new CancellationToken(false)).Wait();
            }

            var resultArray = new ArraySegment <byte>(new byte[receiveMaxBufferLength]);
            WebSocketReceiveResult result = null;

            lock (socket)
            {
                result = socket.ReceiveAsync(resultArray, CancellationToken.None).Result;
            }

            var message = Encoding.UTF8.GetString(resultArray.Array.Take(result.Count).ToArray());

            return(JsonConvert.DeserializeObject <TResponse>(message));
        }
Exemple #3
0
        /// <summary>
        /// Запрос на выполнение json-rpc метода
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="returnType"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="JsonException">ошибочный ответ при приравнивание к типу</exception>
        public static object Invoke(Stream stream, Type returnType, IJsonRequest request)
        {
            if (returnType == null)
            {
                throw new ArgumentNullException("returnType");
            }
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            var streamer = new Streamer(stream);

            // send request
            streamer.WriteLine(request.ToString());

            // get response
            var response = streamer.ReadLine(TimeSpan.MaxValue);

            while (response == "")
            {
                response = streamer.ReadLine(TimeSpan.MaxValue);
            }

            return((new ResponseParser(response, returnType)).Result());
        }
Exemple #4
0
        /// <summary>
        /// Call json-rpc method
        /// </summary>
        /// <param name="request"></param>
        /// <returns>raw json response</returns>
        public string JsonInvoke(IJsonRequest request)
        {
            if (!IsActive)
            {
                return("{\"id\":" + "-" + ",\"error\":{\"name\":\"JSONRPCError\",\"message\":\"Connection disactive\",\"errors\":\"\"}}");
            }

            if (request == null)
            {
                return("{\"id\":" + "-" + ",\"error\":{\"name\":\"JSONRPCError\",\"message\":\"JsonRequest cannot be null\",\"errors\":\"\"}}");
            }

            lock (mSyncInvoke)
            {
                if (mRemoteMethods.Contains(request.Method))
                {
                    try
                    {
                        return((string)JsonRpcCaller.Invoke(mTcpConnection.GetStream(),
                                                            typeof(JsonBuffer),
                                                            request));
                    }
                    catch (Exception)
                    {
                        Dispose();
                        return("{\"id\":" + request.Id +
                               ",\"error\":{\"name\":\"JSONRPCError\",\"message\":\"Timeout method call\",\"errors\":\"\"}}");
                    }
                }

                return("{\"id\":" + request.Id +
                       ",\"error\":{\"name\":\"JSONRPCError\",\"message\":\"Method unavailable\",\"errors\":\"\"}}");
            }
        }
Exemple #5
0
        /// <summary>
        /// Call json-rpc method
        /// </summary>
        /// <param name="returnType"></param>
        /// <param name="request"></param>
        /// <returns>null or object of requested type</returns>
        public object Invoke(Type returnType, IJsonRequest request)
        {
            if (!IsActive)
            {
                return(null);
            }

            if (request == null)
            {
                return(null);
            }

            lock (mSyncInvoke)
            {
                if (mRemoteMethods.Contains(request.Method))
                {
                    try
                    {
                        return(JsonRpcCaller.Invoke(mTcpConnection.GetStream(),
                                                    returnType,
                                                    request));
                    }
                    catch (Exception)
                    {
                        Dispose();
                        return(null);
                    }
                }

                return(null);
            }
        }
Exemple #6
0
        public string Invoke(IJsonRequest request)
        {
            if (!mProcessingThread.IsAlive)
            {
                return(OnError(request, null));
            }

            lock (mInvokeLock)
            {
                // return "error: bad request"
                if (request == null)
                {
                    return(OnError(null, null));
                }

                // debug
                //Console.WriteLine(DateTime.Now + "\tProxyService.Invoke({0}, {1}, {2})", request.Id, request.Method, request.Args);

                // Try to get remote rpcModule for this request. If no any rpcModule to this - call InternalProcess()
                var module = mRpcModuleList.TryGetByMethod(request.Method);

                var response = (module != null) ? module.JsonInvoke(request) : InternalProcess(request);
                // debug
                //Console.WriteLine("response: " + response);

                return(response);
            }
        }
Exemple #7
0
        public string Invoke(string id, IJsonRequest request)
        {
            Controller rv;

            mDevices.TryGetValue(id, out rv);

            return(rv != null?rv.JsonInvoke(request) : null);
        }
Exemple #8
0
        private static string OnError(IJsonRequest request, string exception)
        {
            if (request != null)
            {
                if (!string.IsNullOrEmpty(exception))
                {
                    return("{\"id\":" + request.Id + ",\"error\":{\"name\":\"JSONRPCError\",\"message\":\"Bad request\",\"errors\":\"\"}}");
                }

                return("{\"id\":" + request.Id + ",\"error\":{\"name\":\"JSONRPCError\",\"message\":\"Bad request\",\"errors\":\"" + exception + "\"}}");
            }

            return("{\"id\":0,\"error\":{\"name\":\"JSONRPCError\",\"message\":\"Bad request\",\"errors\":\"\"}}");
        }
Exemple #9
0
        /// <summary>
        /// Call json-rpc method
        /// </summary>
        /// <param name="returnType"></param>
        /// <param name="request"></param>
        /// <returns>null or object of requested type</returns>
        public object Invoke(Type returnType, IJsonRequest request)
        {
            if (!IsActive)
            {
                return(null);
            }

            try
            {
                return(JsonRpcCaller.Invoke(mTcpConnection.GetStream(),
                                            returnType,
                                            request));
            }
            catch (Exception)
            {
                Dispose();
                return(null);
            }
        }
Exemple #10
0
        /// <summary>
        /// Call json-rpc method
        /// </summary>
        /// <param name="request"></param>
        /// <returns>raw json response</returns>
        public string JsonInvoke(IJsonRequest request)
        {
            if (!IsActive)
            {
                return(null);
            }

            try
            {
                return((string)JsonRpcCaller.Invoke(mTcpConnection.GetStream(),
                                                    typeof(JsonBuffer),
                                                    request));
            }
            catch (Exception)
            {
                Dispose();
                return("{\"id\":" + request.Id + ",\"error\":{\"name\":\"JSONRPCError\",\"message\":\"Timeout method call\",\"errors\":\"\"}}");
            }
        }
Exemple #11
0
        private string InternalProcess(IJsonRequest request)
        {
            JsonRpcDispatcher dispatcher;

            mInternalRpcMethods.TryGetValue(request.Method, out dispatcher);

            try
            {
                if (dispatcher != null)
                {
                    return(dispatcher.Process(request.ToString()));
                }
            }
            catch (BadRequestException e)
            {
                return(OnError(request, e.ToString()));
            }

            return(OnError(request, null));
        }
 public TResponse SendMessage <TResponse>(IJsonRequest <TResponse> request) where TResponse : new()
 {
     throw new NotImplementedException("Unable to send message to a display client");
 }
 public Ferramentas(IJsonRequest jsonRequest)
 {
     _jsonRequest = jsonRequest;
 }
Exemple #14
0
        public IRestRequest GetRequest()
        {
            Method requestMethod = Method.GET;

            if (_api is IMustPost)
            {
                requestMethod = Method.POST;
            }
            RestRequest request = new RestRequest(_api.Url, requestMethod);

            if (_api is IJsonRequest)
            {
                IJsonRequest jsonapi = _api as IJsonRequest;
                string       json    =
                    JsonConvert.SerializeObject(
                        jsonapi.JsonData,
                        new JsonSerializerSettings {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                }
                        );
                request.AddParameter("application/json", json, ParameterType.RequestBody);;
            }
            var interfaces = _api.GetType().GetInterfaces();

            foreach (var inf in interfaces)
            {
                var props = inf.GetProperties(BindingFlags.Public | BindingFlags.Instance);
                foreach (var prop in props)
                {
                    var attrs = prop.GetCustomAttributes(true);
                    foreach (var attr in attrs)
                    {
                        if (attr is QueryStringAttribute)
                        {
                            var attr1      = attr as QueryStringAttribute;
                            var paramname  = attr1.AliasName;
                            var paramvalue = prop.GetValue(_api);
                            if (paramvalue != null)
                            {
                                if (attr1.ToLowerCase)
                                {
                                    request.AddParameter(paramname, paramvalue.ToString().ToLower(), ParameterType.QueryString);
                                }
                                else
                                {
                                    request.AddParameter(paramname, paramvalue.ToString(), ParameterType.QueryString);
                                }
                            }
                            break;
                        }
                        else if (attr is FormParameterAttribute)
                        {
                            var attr1      = attr as FormParameterAttribute;
                            var paramname  = attr1.AliasName;
                            var paramvalue = prop.GetValue(_api);
                            request.AddParameter(paramname, paramvalue.ToString(), ParameterType.GetOrPost);
                        }
                    }
                }
            }

            return(request);
        }
 public HomeController(ILogger <HomeController> logger, IJsonRequest jsonRequest, IFerramentas ferramentas)
 {
     _logger      = logger;
     _jsonRequest = jsonRequest;
     _ferramentas = ferramentas;
 }
        /// <summary>
        /// Invokes the specified action by using the specified controller context.
        /// </summary>
        /// <param name="controllerContext">The controller context.</param>
        /// <param name="actionName">The name of the action to invoke.</param>
        /// <returns>The result of executing the action.</returns>
        /// <exception cref="T:System.ArgumentNullException">The <paramref name="controllerContext"/> parameter is null.</exception>
        /// <exception cref="T:System.ArgumentException">The <paramref name="actionName"/> parameter is null or empty.</exception>
        /// <exception cref="T:System.Threading.ThreadAbortException">The thread was aborted during invocation of the action.</exception>
        /// <exception cref="T:System.Exception">An unspecified error occurred during invocation of the action.</exception>
        public override bool InvokeAction(ControllerContext controllerContext, string actionName)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }
            if (String.IsNullOrEmpty(actionName))
            {
                throw new ArgumentException("������������", "actionName");
            }

            var controllerDescriptor = GetControllerDescriptor(controllerContext);
            var actionDescriptor = FindAction(controllerContext, controllerDescriptor, actionName);

            if (actionDescriptor != null)
            {
                var filterInfo = GetFilters(controllerContext, actionDescriptor);

                try
                {
                    //����Ƿ����Json�������
                    _isJsonRequest = JsonRequest.CheckJsonRequest(controllerContext.HttpContext.Request);
                    if (_isJsonRequest)
                    {
                        _jsonRequest = JsonRequest.GetJsonRequest(controllerContext.HttpContext.Request);
                    }
                    //�����֧��Json����Ŀ�����. �����������
                    if (controllerContext.Controller is IJsonControllerProvider)
                    {
                        var ctr = (IJsonControllerProvider) controllerContext.Controller;
                        ctr.JsonRequest = _jsonRequest;
                    }

                    if (controllerContext.Controller is ZxdFrameworkController)
                    {
                        ((ZxdFrameworkController) controllerContext.Controller).CurrentUser =
                            ServiceFactory.AuthorityService.CurrentUser;
                    }

                    var authContext = InvokeAuthorizationFilters(controllerContext, filterInfo.AuthorizationFilters, actionDescriptor);
                    if (authContext.Result != null)
                    {
                        // the auth filter signaled that we should let it short-circuit the request
                        InvokeActionResult(controllerContext, authContext.Result);
                    }
                    else
                    {
                        if (controllerContext.Controller.ValidateRequest)
                        {
                            ValidateRequest(controllerContext);
                        }
                        //��ȡ��Ҫ����IJ���
                        var parameters = GetParameterValues(controllerContext, actionDescriptor);
                        //ִ�з�����
                        var postActionContext = InvokeActionMethodWithFilters(controllerContext, filterInfo.ActionFilters, actionDescriptor, parameters);
                        InvokeActionResultWithFilters(controllerContext, filterInfo.ResultFilters, postActionContext.Result);
                    }
                }
                catch (ThreadAbortException)
                {
                    // This type of exception occurs as a result of Response.Redirect(), but we special-case so that
                    // the filters don't see this as an error.
                    throw;
                }
                catch (Exception ex)
                {
                    // something blew up, so execute the exception filters
                    ExceptionContext exceptionContext = InvokeExceptionFilters(controllerContext, filterInfo.ExceptionFilters, ex);
                    if (!exceptionContext.ExceptionHandled)
                    {
                        throw;
                    }
                    InvokeActionResult(controllerContext, exceptionContext.Result);
                }

                return true;
            }

            // notify controller that no method matched
            return false;
        }
 public BuscaCidadeController(IJsonRequest jsonRequest, IFerramentas ferramentas)
 {
     _jsonRequest = jsonRequest;
     _ferramentas = ferramentas;
 }