Example #1
0
        public void ProcessRequest(HttpContext context)
        {
            DirectProvider provider = this.GetProvider(context, this.ProviderName);
            string         data     = string.Empty;
            string         type     = "text/javascript";

            // TotalBytes hangs sometimes, since it accesses the InputStream, which tries to complete loading in another thread
            // when not everything in the stream.
            // Use ContentLength instead...

            // This used to check for string.IsNullOrEmpty(context.Request["extAction"])) but in order to eliminate that from the hanging
            // candidates we've removed it, since we do not need form post at this stage.
            // When we do need it, making it more targetted may be an idea, such as content.Request.Form["extAction"] etc.
            if (context.Request.ContentLength == 0)
            {
                data = provider.ToString();
            }
            else
            {
                DirectExecutionResponse resp = DirectProcessor.Execute(provider, context.Request, this.GetConverters());
                data = resp.Data;
                if (resp.IsUpload)
                {
                    type = "text/html";
                }
            }

            context.Response.ContentType = type;
            context.Response.Write(data);
        }
Example #2
0
        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);
        }
Example #3
0
 /// <summary>
 /// Configure the provider by adding the available API methods.
 /// </summary>
 /// <param name="assembly">The assembly to automatically generate parameters from.</param>
 /// <param name="exclusions">A list of classes to exclude.</param>
 public void Configure(Assembly assembly, IEnumerable <object> exclusions)
 {
     if (!this.Configured)
     {
         List <Type> types = new List <Type>();
         foreach (Type type in assembly.GetTypes())
         {
             if (DirectProvider.CheckType(exclusions, type))
             {
                 types.Add(type);
             }
         }
         this.Configure(types);
     }
 }
        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);
        }
Example #5
0
        /// <summary>
        /// Adds a provider to the cache.
        /// </summary>
        /// <param name="provider"></param>
        public void Add(DirectProvider provider)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

            // Double lock checking...
            if (!this.ContainsProvider(provider.Name))
            {
                lock (_SyncLock)
                {
                    if (!this.ContainsProvider(provider.Name))
                    {
                        _Providers.Add(provider.Name, provider);
                    }
                }
            }
        }
Example #6
0
        /// <summary>
        /// Adds a provider to the cache.
        /// </summary>
        /// <param name="provider"></param>
        public void Add(DirectProvider provider)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

            // Double lock checking...
            if (!this.ContainsProvider(provider.Name))
            {
                lock (_SyncLock)
                {
                    if (!this.ContainsProvider(provider.Name))
                    {
                        _Providers.Add(provider.Name, provider);
                    }
                }
            }
        }
Example #7
0
        public void ProcessRequest(HttpContext context)
        {
            string apiName = ConfigurationManager.AppSettings[NameConfig];
            string routerUrl = ConfigurationManager.AppSettings[RouterConfig];
            string ns = ConfigurationManager.AppSettings[NamespaceConfig] ?? "";
            string assemblyName = ConfigurationManager.AppSettings[AssemblyConfig];

            if (String.IsNullOrEmpty(apiName) || String.IsNullOrEmpty(routerUrl))
            {
                string s = "window.alert('Configuration Error:\\n\\nExtDirect_ApiName or ExtDirect_RouterUrl are not defined.\\nPlease add them to appSettings section in your configuration file.');";
                context.Response.Write(s);
                context.Response.End();
            }

            context.Response.ContentType = "text/javascript";

            DirectProviderCache cache = DirectProviderCache.GetInstance();
            DirectProvider provider;

            cache.Clear();
            if (!cache.ContainsKey(apiName))
            {
                provider = new DirectProvider()
                {
                    Name = apiName,
                    Url = routerUrl
                };
                if (!string.IsNullOrEmpty(ns))
                {
                    provider.Namespace = ns;
                }
                provider.Configure(System.Reflection.Assembly.Load(assemblyName));
                cache.Add(apiName, provider);
            }
            else
            {
                provider = cache[apiName];
            }

            context.Response.Write(provider.ToString());

        }
Example #8
0
 private DirectProvider GetProvider(HttpContext context, string name)
 {
     DirectProviderCache cache = DirectProviderCache.GetInstance();
     if (!cache.ContainsKey(name))
     {
         DirectProvider provider = new DirectProvider()
         {
             Name = name,
             Url = context.Request.Path,
             Namespace = this.Namespace,
             Timeout = this.Timeout,
             MaxRetries = this.MaxRetries,
             AutoNamespace = this.AutoNamespace,
             Id = this.Id
         };
         this.ConfigureProvider(provider);
         cache.Add(name, provider);
     }
     return cache[name];
 }
Example #9
0
        public void ProcessRequest(HttpContext context)
        {
            string apiName      = ConfigurationManager.AppSettings[NameConfig];
            string routerUrl    = ConfigurationManager.AppSettings[RouterConfig];
            string ns           = ConfigurationManager.AppSettings[NamespaceConfig] ?? "";
            string assemblyName = ConfigurationManager.AppSettings[AssemblyConfig];

            if (String.IsNullOrEmpty(apiName) || String.IsNullOrEmpty(routerUrl))
            {
                string s = "window.alert('Configuration Error:\\n\\nExtDirect_ApiName or ExtDirect_RouterUrl are not defined.\\nPlease add them to appSettings section in your configuration file.');";
                context.Response.Write(s);
                context.Response.End();
            }

            context.Response.ContentType = "text/javascript";

            DirectProviderCache cache = DirectProviderCache.GetInstance();
            DirectProvider      provider;

            cache.Clear();
            if (!cache.ContainsKey(apiName))
            {
                provider = new DirectProvider()
                {
                    Name = apiName,
                    Url  = routerUrl
                };
                if (!string.IsNullOrEmpty(ns))
                {
                    provider.Namespace = ns;
                }
                provider.Configure(System.Reflection.Assembly.Load(assemblyName));
                cache.Add(apiName, provider);
            }
            else
            {
                provider = cache[apiName];
            }

            context.Response.Write(provider.ToString());
        }
Example #10
0
        private DirectProvider GetProvider(HttpContext context, string name)
        {
            DirectProviderCache cache = DirectProviderCache.GetInstance();

            if (!cache.ContainsProvider(name))
            {
                DirectProvider provider = new DirectProvider()
                {
                    Name          = name,
                    Url           = context.Request.Path,
                    Namespace     = this.Namespace,
                    Timeout       = this.Timeout,
                    MaxRetries    = this.MaxRetries,
                    AutoNamespace = this.AutoNamespace,
                    Id            = this.Id
                };
                this.ConfigureProvider(provider);
                cache.Add(provider);
            }
            return(cache[name]);
        }
Example #11
0
        public void ProcessRequest(HttpContext context)
        {
            DirectProvider provider = this.GetProvider(context, this.ProviderName);
            string         data     = string.Empty;
            string         type     = "text/javascript";

            if (context.Request.TotalBytes == 0 && string.IsNullOrEmpty(context.Request["extAction"]))
            {
                data = provider.ToString();
            }
            else
            {
                DirectExecutionResponse resp = DirectProcessor.Execute(provider, context.Request, this.GetConverters());
                data = resp.Data;
                if (resp.IsUpload)
                {
                    type = "text/html";
                }
            }
            context.Response.ContentType = type;
            context.Response.Write(data);
        }
Example #12
0
 /// <summary>
 /// Configure the provider given a list of action classes.
 /// </summary>
 /// <param name="provider">The provider to configure.</param>
 /// <param name="items">The list of classes to interrogate.</param>
 protected void Configure(DirectProvider provider, IEnumerable <object> items)
 {
     provider.Configure(items);
 }
Example #13
0
 /// <summary>
 /// Configure the provider using reflection by getting the appropriate methods from an assembly.
 /// </summary>
 /// <param name="provider">The provider to configure.</param>
 /// <param name="assembly">The assembly to interrogate.</param>
 /// <param name="exclusions">A list of classes to exclude.</param>
 protected void Configure(DirectProvider provider, Assembly assembly, IEnumerable <object> exclusions)
 {
     provider.Configure(assembly, exclusions);
 }
Example #14
0
 /// <summary>
 /// Configure the provider with the appropriate set of methods.
 /// </summary>
 /// <param name="provider">The provider to be configured.</param>
 /// <remarks>This method is virtual to allow for custom configurations.</remarks>
 protected virtual void ConfigureProvider(DirectProvider provider)
 {
     provider.Configure(new object[] { this });
 }
Example #15
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
            {
                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);
        }
 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;
 }
Example #17
0
 /// <summary>
 /// Configure the provider given a list of action classes.
 /// </summary>
 /// <param name="provider">The provider to configure.</param>
 /// <param name="items">The list of classes to interrogate.</param>
 protected void Configure(DirectProvider provider, IEnumerable<object> items)
 {
     provider.Configure(items);
 }
Example #18
0
 /// <summary>
 /// Configure the provider using reflection by getting the appropriate methods from an assembly.
 /// </summary>
 /// <param name="provider">The provider to configure.</param>
 /// <param name="assembly">The assembly to interrogate.</param>
 /// <param name="exclusions">A list of classes to exclude.</param>
 protected void Configure(DirectProvider provider, Assembly assembly, IEnumerable<object> exclusions)
 {
     provider.Configure(assembly, exclusions);
 }
Example #19
0
 /// <summary>
 /// Configure the provider using reflection by getting the appropriate methods from an assembly.
 /// </summary>
 /// <param name="provider">The provider to configure.</param>
 /// <param name="assembly">The assembly to interrogate.</param>
 protected void Configure(DirectProvider provider, Assembly assembly)
 {
     this.Configure(provider, assembly, null);
 }
Example #20
0
 /// <summary>
 /// Configure the provider with the appropriate set of methods.
 /// </summary>
 /// <param name="provider">The provider to be configured.</param>
 /// <remarks>This method is virtual to allow for custom configurations.</remarks>
 protected virtual void ConfigureProvider(DirectProvider provider)
 {
     provider.Configure(new object[] { this });
 }
Example #21
0
 /// <summary>
 /// Configure the provider using reflection by getting the appropriate methods from an assembly.
 /// </summary>
 /// <param name="provider">The provider to configure.</param>
 /// <param name="assembly">The assembly to interrogate.</param>
 protected void Configure(DirectProvider provider, Assembly assembly)
 {
     this.Configure(provider, assembly, null);
 }
Example #22
0
        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;
        }
        /// <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);
        }
        /// <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;
        }
Example #25
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
            {
                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;
        }