コード例 #1
0
ファイル: DirectProcessor.cs プロジェクト: westy/Ext.Direct
        private static DirectResponse ProcessRequest(DirectProvider provider, DirectRequest request)
        {
            DirectResponse r = new DirectResponse(request);

            try
            {
                r.Result = provider.Execute(request);
            }
            catch (Exception ex)
            {
                // Build our error message
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(ex.Message);

                Exception innerEx = ex.InnerException;
                while (innerEx != null)
                {
                    sb.AppendLine(innerEx.Message);
                    innerEx = innerEx.InnerException;
                }

                r.ExceptionMessage = sb.ToString();
                r.Type             = DirectResponse.ResponseExceptionType;
            }
            return(r);
        }
コード例 #2
0
        private void SanitizeDates(MethodInfo method, DirectRequest request)
        {
            int      idx = 0;
            DateTime d;

            foreach (ParameterInfo p in method.GetParameters())
            {
                if (p.ParameterType == typeof(DateTime))
                {
                    object o = request.Data[idx];
                    if (o != null)
                    {
                        if (DateTime.TryParse(o.ToString(), out d))
                        {
                            request.Data[idx] = d;
                        }
                        else
                        {
                            throw new DirectException(String.Format("Unable to parse date parameter: '{0}'",
                                                                    request.Data[idx]));
                        }
                    }
                    else
                    {
                        throw new DirectException(String.Format("Unable to parse date parameter: '{0}'",
                                                                request.Data[idx]));
                    }
                }
                ++idx;
            }
        }
コード例 #3
0
 public DirectResponse(DirectRequest request)
 {
     this.Type = request.Type;
     this.TransactionId = request.TransactionId;
     this.Action = request.Action;
     this.Method = request.Method;
     this.IsUpload = request.IsUpload;
 }
コード例 #4
0
ファイル: DirectResponse.cs プロジェクト: westy/Ext.Direct
 public DirectResponse(DirectRequest request)
 {
     this.Type          = request.Type;
     this.TransactionId = request.TransactionId;
     this.Action        = request.Action;
     this.Method        = request.Method;
     this.IsUpload      = request.IsUpload;
 }
コード例 #5
0
        internal object Execute(DirectRequest request)
        {
            DirectAction action = this.actions[request.Action];

            if (action == null)
            {
                throw new DirectException("Unable to find action, " + request.Action);
            }
            DirectMethod method = action.GetMethod(request.Method);

            if (method == null)
            {
                throw new DirectException("Unable to find action, " + request.Method);
            }
            Type type = action.Type;

            if (request.Data == null)
            {
                if (method.Parameters > 0)
                {
                    throw new DirectException("Parameters length does not match");
                }
            }
            else
            {
                if (request.Data.Length > 1 && method.IsForm)
                {
                    throw new DirectException("Form methods can only have a single parameter.");
                }
                else if (request.Data.Length != method.Parameters)
                {
                    throw new DirectException("Parameters length does not match");
                }
            }
            try
            {
                this.SanitizeDates(method.Method, request);
                object[] param = request.Data;
                if (method.ParseAsJson)
                {
                    param = new object[] { method.GetParseData(request.RequestData) };
                }
                return(method.Method.Invoke(type.Assembly.CreateInstance(type.FullName), param));
            }
            catch (Exception ex)
            {
                throw new DirectException("Error occurred while calling Direct method: " + ex.Message);
            }
        }
コード例 #6
0
        private static DirectResponse ProcessRequest(DirectProvider provider, DirectRequest request)
        {
            DirectResponse r = new DirectResponse(request);

            try
            {
                r.Result = provider.Execute(request);
            }
            catch (DirectException ex)
            {
                r.ExceptionMessage = ex.Message;
                r.Type             = DirectResponse.ResponseExceptionType;
            }
            return(r);
        }
コード例 #7
0
ファイル: DirectProvider.cs プロジェクト: westy/Ext.Direct
 private void SanitizeDates(MethodInfo method, DirectRequest request)
 {
     int idx = 0;
     DateTime d;
     foreach (ParameterInfo p in method.GetParameters())
     {
         if (p.ParameterType == typeof(DateTime))
         {
             object o = request.Data[idx];
             if (o != null)
             {
                 if (DateTime.TryParse(o.ToString(), out d))
                 {
                     request.Data[idx] = d;
                 }
                 else
                 {
                     throw new DirectException(String.Format("Unable to parse date parameter: '{0}'",
                                                             request.Data[idx]));
                 }
             }
             else
             {
                 throw new DirectException(String.Format("Unable to parse date parameter: '{0}'",
                                                         request.Data[idx]));
             }
         }
         ++idx;
     }
 }
コード例 #8
0
ファイル: DirectProvider.cs プロジェクト: westy/Ext.Direct
        internal object Execute(DirectRequest request)
        {
            DirectAction action = this.actions[request.Action];
            if (action == null)
            {
                throw new DirectException("Unable to find action, " + request.Action);
            }
            DirectMethod method = action.GetMethod(request.Method);
            if (method == null)
            {
                throw new DirectException("Unable to find action, " + request.Method);
            }
            Type type = action.Type;
            if (request.Data == null)
            {
                if (method.Parameters > 0)
                {
                    throw new DirectException("Parameters length does not match");
                }
            }
            else
            {
                if (request.Data.Length > 1 && method.IsForm)
                {
                    throw new DirectException("Form methods can only have a single parameter.");
                }
                else if (request.Data.Length != method.Parameters)
                {
                    throw new DirectException("Parameters length does not match");
                }
            }

            this.SanitizeDates(method.Method, request);

            object[] param = request.Data;

            if ((param != null) && (!request.IsUpload))
            {
                // If any of the parameters of the method we are calling are classes
                // or have the JsonObject attribute then we need to deserialize them...
                var methodParams = method.Method.GetParameters();

                Type parameterType;
                for (int i = 0; i < methodParams.Length; ++i)
                {
                    // Is parameter a class or marked as a JsonObject?
                    parameterType = methodParams[i].ParameterType;

                    if ((parameterType != typeof(String)) && 
                        (parameterType.IsClass || 
                        Utility.HasAttribute(parameterType, typeof(JsonObjectAttribute))))
                    {
                        // Allow class parameters to be null
                        if (param[i] != null)
                        {
                            param[i] = JsonConvert.DeserializeObject(param[i].ToString(), parameterType);
                        }
                    }
                }
            }

            return method.Method.Invoke(type.Assembly.CreateInstance(type.FullName), param);
        }
コード例 #9
0
        /// <summary>
        /// Processes an incoming request.
        /// </summary>
        /// <param name="provider">The provider that triggered the request.</param>
        /// <param name="httpRequest">The http information.</param>
        /// <returns>The result from the client method.</returns>
        internal static DirectExecutionResponse Execute(DirectProvider provider, HttpRequest httpRequest, IEnumerable<JsonConverter> converters)
        {
            List<DirectResponse> responses = new List<DirectResponse>();
            if (!String.IsNullOrEmpty(httpRequest[DirectRequest.RequestFormAction]))
            {
                DirectRequest request = new DirectRequest()
                {
                    Action = httpRequest[DirectRequest.RequestFormAction] ?? string.Empty,
                    Method = httpRequest[DirectRequest.RequestFormMethod] ?? string.Empty,
                    Type = httpRequest[DirectRequest.RequestFormType] ?? string.Empty,
                    IsUpload = Convert.ToBoolean(httpRequest[DirectRequest.RequestFormUpload]),
                    TransactionId = Convert.ToInt32(httpRequest[DirectRequest.RequestFormTransactionId]),
                    Data = new object[] { httpRequest }
                };
                responses.Add(DirectProcessor.ProcessRequest(provider, request));
            }
            else
            {
                UTF8Encoding encoding = new UTF8Encoding();
                string json = encoding.GetString(httpRequest.BinaryRead(httpRequest.TotalBytes));
                /**************************************************************************************
                 skygreen:解决bug:Self referencing loop
                 参考:http://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop-detected-for-type
                 **************************************************************************************/
                if (substr_count(json,"data")>1)
                {
                    List<DirectRequest> requests = JsonConvert.DeserializeObject<List<DirectRequest>>(json);
                    if (requests.Count > 0)
                    {
                        JArray raw = JArray.Parse(json);
                        int i = 0;
                        foreach (DirectRequest request in requests)
                        {
                            request.RequestData = (JObject)raw[i];
                            responses.Add(DirectProcessor.ProcessRequest(provider, request));
                            ++i;
                        }
                    }
                    else
                    {
                        DirectRequest request = JsonConvert.DeserializeObject<DirectRequest>(json);
                        request.RequestData = JObject.Parse(json);
                        responses.Add(DirectProcessor.ProcessRequest(provider, request));
                    }
                }
                else
                {
                    DirectRequest request = JsonConvert.DeserializeObject<DirectRequest>(json);
                    request.RequestData = JObject.Parse(json);
                    responses.Add(DirectProcessor.ProcessRequest(provider, request));
                }
            }
            DirectExecutionResponse response = new DirectExecutionResponse();

            JsonSerializerSettings outputSettings = new JsonSerializerSettings() { 
                DefaultValueHandling = DefaultValueHandling.Ignore,
                ReferenceLoopHandling =ReferenceLoopHandling.Ignore
            };
            foreach (JsonConverter converter in converters)
            {
                outputSettings.Converters.Add(converter);
            }
            if (responses.Count > 1 || !responses[0].IsUpload)
            {
                response.Data = JsonConvert.SerializeObject(responses, Formatting.None, outputSettings);
            }
            else
            {
                response.IsUpload = true;
                string outputJson = JsonConvert.SerializeObject(responses[0], Formatting.None, outputSettings);
                response.Data = String.Format("<html><body><textarea>{0}</textarea></body></html>", outputJson.Replace("&quot;", "\\&quot;"));
            }
            return response;
        }
コード例 #10
0
 private static DirectResponse ProcessRequest(DirectProvider provider, DirectRequest request)
 {
     DirectResponse r = new DirectResponse(request);
     try
     {
         r.Result = provider.Execute(request);
     }
     catch (DirectException ex)
     {
         r.ExceptionMessage = ex.Message;
         r.Type = DirectResponse.ResponseExceptionType;
     }
     return r;
 }
コード例 #11
0
ファイル: DirectProcessor.cs プロジェクト: westy/Ext.Direct
        /// <summary>
        /// Processes an incoming request.
        /// </summary>
        /// <param name="provider">The provider that triggered the request.</param>
        /// <param name="httpRequest">The http information.</param>
        /// <returns>The result from the client method.</returns>
        internal static DirectExecutionResponse Execute(DirectProvider provider, HttpRequest httpRequest, IEnumerable<JsonConverter> converters)
        {
            List<DirectResponse> responses = new List<DirectResponse>();
            if (!String.IsNullOrEmpty(httpRequest[DirectRequest.RequestFormAction]))
            {
                DirectRequest request = new DirectRequest()
                {
                    Action = httpRequest[DirectRequest.RequestFormAction] ?? string.Empty,
                    Method = httpRequest[DirectRequest.RequestFormMethod] ?? string.Empty,
                    Type = httpRequest[DirectRequest.RequestFormType] ?? string.Empty,
                    IsUpload = Convert.ToBoolean(httpRequest[DirectRequest.RequestFormUpload]),
                    TransactionId = Convert.ToInt32(httpRequest[DirectRequest.RequestFormTransactionId]),
                    Data = new object[] { httpRequest }
                };
                responses.Add(DirectProcessor.ProcessRequest(provider, request));
            }
            else
            {
                string json = null;
                using (var reader = new StreamReader(httpRequest.InputStream, Encoding.UTF8))
                {
                    json = reader.ReadToEnd();
                }

                try
                {
                    // Force into an array shape
                    if (!json.StartsWith("["))
                    {
                        json = String.Format("[{0}]", json);
                    }

                    // Get raw array data
                    JArray raw = JArray.Parse(json);

                    // And also deserialize the requests
                    List<DirectRequest> requests = JsonConvert.DeserializeObject<List<DirectRequest>>(json);

                    int i = 0;
                    foreach (DirectRequest request in requests)
                    {
                        request.RequestData = (JObject)raw[i];
                        responses.Add(DirectProcessor.ProcessRequest(provider, request));
                        ++i;
                    }
                }
                catch (Exception ex)
                {
                    responses.Add(new DirectResponse(String.Format("An exception occurred when attempting to decode the requests: {0}", ex)));
                }
            }

            DirectExecutionResponse response = new DirectExecutionResponse();
            JsonSerializerSettings outputSettings = new JsonSerializerSettings()
            {
                DefaultValueHandling = DefaultValueHandling.Ignore,
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            foreach (JsonConverter converter in converters)
            {
                outputSettings.Converters.Add(converter);
            }

            // Updated this to guard against having no responses at all.
            // Was before I added the above else, but good practice anyway...
            if (responses.Count > 1 || ((responses.Count > 0) && !responses[0].IsUpload))
            {
                response.Data = JsonConvert.SerializeObject(responses, Formatting.None, outputSettings);
            }
            else if (responses.Count > 0)
            {
                response.IsUpload = true;
                string outputJson = JsonConvert.SerializeObject(responses[0], Formatting.None, outputSettings);
                response.Data = String.Format("<html><body><textarea>{0}</textarea></body></html>", outputJson.Replace("&quot;", "\\&quot;"));
            }
            return response;
        }
コード例 #12
0
ファイル: DirectProcessor.cs プロジェクト: westy/Ext.Direct
        private static DirectResponse ProcessRequest(DirectProvider provider, DirectRequest request)
        {
            DirectResponse r = new DirectResponse(request);
            try
            {
                r.Result = provider.Execute(request);
            }
            catch (Exception ex)
            {
                // Build our error message
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(ex.Message);

                Exception innerEx = ex.InnerException;
                while (innerEx != null)
                {
                    sb.AppendLine(innerEx.Message);
                    innerEx = innerEx.InnerException;
                }

                r.ExceptionMessage = sb.ToString();
                r.Type = DirectResponse.ResponseExceptionType;
            }
            return r;
        }
コード例 #13
0
        internal object Execute(DirectRequest request)
        {
            DirectAction action = this.actions[request.Action];

            if (action == null)
            {
                throw new DirectException("Unable to find action, " + request.Action);
            }
            DirectMethod method = action.GetMethod(request.Method);

            if (method == null)
            {
                throw new DirectException("Unable to find action, " + request.Method);
            }
            Type type = action.Type;

            if (request.Data == null)
            {
                if (method.Parameters > 0)
                {
                    throw new DirectException("Parameters length does not match");
                }
            }
            else
            {
                if (request.Data.Length > 1 && method.IsForm)
                {
                    throw new DirectException("Form methods can only have a single parameter.");
                }
                else if (request.Data.Length != method.Parameters)
                {
                    throw new DirectException("Parameters length does not match");
                }
            }

            this.SanitizeDates(method.Method, request);

            object[] param = request.Data;

            if ((param != null) && (!request.IsUpload))
            {
                // If any of the parameters of the method we are calling are classes
                // or have the JsonObject attribute then we need to deserialize them...
                var methodParams = method.Method.GetParameters();

                Type parameterType;
                for (int i = 0; i < methodParams.Length; ++i)
                {
                    // Is parameter a class or marked as a JsonObject?
                    parameterType = methodParams[i].ParameterType;

                    if ((parameterType != typeof(String)) &&
                        (parameterType.IsClass ||
                         Utility.HasAttribute(parameterType, typeof(JsonObjectAttribute))))
                    {
                        // Allow class parameters to be null
                        if (param[i] != null)
                        {
                            param[i] = JsonConvert.DeserializeObject(param[i].ToString(), parameterType);
                        }
                    }
                }
            }

            return(method.Method.Invoke(type.Assembly.CreateInstance(type.FullName), param));
        }
コード例 #14
0
        /// <summary>
        /// Processes an incoming request.
        /// </summary>
        /// <param name="provider">The provider that triggered the request.</param>
        /// <param name="httpRequest">The http information.</param>
        /// <returns>The result from the client method.</returns>
        internal static DirectExecutionResponse Execute(DirectProvider provider, HttpRequest httpRequest, IEnumerable <JsonConverter> converters)
        {
            List <DirectResponse> responses = new List <DirectResponse>();

            if (!String.IsNullOrEmpty(httpRequest[DirectRequest.RequestFormAction]))
            {
                DirectRequest request = new DirectRequest()
                {
                    Action        = httpRequest[DirectRequest.RequestFormAction] ?? string.Empty,
                    Method        = httpRequest[DirectRequest.RequestFormMethod] ?? string.Empty,
                    Type          = httpRequest[DirectRequest.RequestFormType] ?? string.Empty,
                    IsUpload      = Convert.ToBoolean(httpRequest[DirectRequest.RequestFormUpload]),
                    TransactionId = Convert.ToInt32(httpRequest[DirectRequest.RequestFormTransactionId]),
                    Data          = new object[] { httpRequest }
                };
                responses.Add(DirectProcessor.ProcessRequest(provider, request));
            }
            else
            {
                UTF8Encoding         encoding = new UTF8Encoding();
                string               json     = encoding.GetString(httpRequest.BinaryRead(httpRequest.TotalBytes));
                List <DirectRequest> requests = JsonConvert.DeserializeObject <List <DirectRequest> >(json);
                if (requests.Count > 0)
                {
                    JArray raw = JArray.Parse(json);
                    int    i   = 0;
                    foreach (DirectRequest request in requests)
                    {
                        request.RequestData = (JObject)raw[i];
                        responses.Add(DirectProcessor.ProcessRequest(provider, request));
                        ++i;
                    }
                }
                else
                {
                    DirectRequest request = JsonConvert.DeserializeObject <DirectRequest>(json);
                    request.RequestData = JObject.Parse(json);
                    responses.Add(DirectProcessor.ProcessRequest(provider, request));
                }
            }
            DirectExecutionResponse response       = new DirectExecutionResponse();
            JsonSerializerSettings  outputSettings = new JsonSerializerSettings()
            {
                DefaultValueHandling = DefaultValueHandling.Ignore
            };

            foreach (JsonConverter converter in converters)
            {
                outputSettings.Converters.Add(converter);
            }
            if (responses.Count > 1 || !responses[0].IsUpload)
            {
                response.Data = JsonConvert.SerializeObject(responses, Formatting.None, outputSettings);
            }
            else
            {
                response.IsUpload = true;
                string outputJson = JsonConvert.SerializeObject(responses[0], Formatting.None, outputSettings);
                response.Data = String.Format("<html><body><textarea>{0}</textarea></body></html>", outputJson.Replace("&quot;", "\\&quot;"));
            }
            return(response);
        }
コード例 #15
0
ファイル: DirectProcessor.cs プロジェクト: westy/Ext.Direct
        /// <summary>
        /// Processes an incoming request.
        /// </summary>
        /// <param name="provider">The provider that triggered the request.</param>
        /// <param name="httpRequest">The http information.</param>
        /// <returns>The result from the client method.</returns>
        internal static DirectExecutionResponse Execute(DirectProvider provider, HttpRequest httpRequest, IEnumerable <JsonConverter> converters)
        {
            List <DirectResponse> responses = new List <DirectResponse>();

            if (!String.IsNullOrEmpty(httpRequest[DirectRequest.RequestFormAction]))
            {
                DirectRequest request = new DirectRequest()
                {
                    Action        = httpRequest[DirectRequest.RequestFormAction] ?? string.Empty,
                    Method        = httpRequest[DirectRequest.RequestFormMethod] ?? string.Empty,
                    Type          = httpRequest[DirectRequest.RequestFormType] ?? string.Empty,
                    IsUpload      = Convert.ToBoolean(httpRequest[DirectRequest.RequestFormUpload]),
                    TransactionId = Convert.ToInt32(httpRequest[DirectRequest.RequestFormTransactionId]),
                    Data          = new object[] { httpRequest }
                };
                responses.Add(DirectProcessor.ProcessRequest(provider, request));
            }
            else
            {
                string json = null;
                using (var reader = new StreamReader(httpRequest.InputStream, Encoding.UTF8))
                {
                    json = reader.ReadToEnd();
                }

                try
                {
                    // Force into an array shape
                    if (!json.StartsWith("["))
                    {
                        json = String.Format("[{0}]", json);
                    }

                    // Get raw array data
                    JArray raw = JArray.Parse(json);

                    // And also deserialize the requests
                    List <DirectRequest> requests = JsonConvert.DeserializeObject <List <DirectRequest> >(json);

                    int i = 0;
                    foreach (DirectRequest request in requests)
                    {
                        request.RequestData = (JObject)raw[i];
                        responses.Add(DirectProcessor.ProcessRequest(provider, request));
                        ++i;
                    }
                }
                catch (Exception ex)
                {
                    responses.Add(new DirectResponse(String.Format("An exception occurred when attempting to decode the requests: {0}", ex)));
                }
            }

            DirectExecutionResponse response       = new DirectExecutionResponse();
            JsonSerializerSettings  outputSettings = new JsonSerializerSettings()
            {
                DefaultValueHandling = DefaultValueHandling.Ignore,
                ContractResolver     = new CamelCasePropertyNamesContractResolver()
            };

            foreach (JsonConverter converter in converters)
            {
                outputSettings.Converters.Add(converter);
            }

            // Updated this to guard against having no responses at all.
            // Was before I added the above else, but good practice anyway...
            if (responses.Count > 1 || ((responses.Count > 0) && !responses[0].IsUpload))
            {
                response.Data = JsonConvert.SerializeObject(responses, Formatting.None, outputSettings);
            }
            else if (responses.Count > 0)
            {
                response.IsUpload = true;
                string outputJson = JsonConvert.SerializeObject(responses[0], Formatting.None, outputSettings);
                response.Data = String.Format("<html><body><textarea>{0}</textarea></body></html>", outputJson.Replace("&quot;", "\\&quot;"));
            }
            return(response);
        }
コード例 #16
0
 internal object Execute(DirectRequest request)
 {
     DirectAction action = this.actions[request.Action];
     if (action == null)
     {
         throw new DirectException("Unable to find action, " + request.Action);
     }
     DirectMethod method = action.GetMethod(request.Method);
     if (method == null)
     {
         throw new DirectException("Unable to find action, " + request.Method);
     }
     Type type = action.Type;
     if (request.Data == null)
     {
         if (method.Parameters > 0)
         {
             throw new DirectException("Parameters length does not match");
         }
     }
     else
     {
         if (request.Data.Length > 1 && method.IsForm)
         {
             throw new DirectException("Form methods can only have a single parameter.");
         }
         else if (request.Data.Length != method.Parameters)
         {
             throw new DirectException("Parameters length does not match");
         }
     } 
     try
     {
         this.SanitizeDates(method.Method, request);
         object[] param = request.Data;
         if (method.ParseAsJson)
         {
             param = new object[] { method.GetParseData(request.RequestData) };
         }
         return method.Method.Invoke(type.Assembly.CreateInstance(type.FullName), param);
     }
     catch (Exception ex)
     {
         throw new DirectException("Error occurred while calling Direct method: " + ex.Message);
     }
 }