コード例 #1
0
ファイル: AjaxProcHelper.cs プロジェクト: kouweizhong/ajaxnet
        /// <summary>
        /// Runs this instance.
        /// </summary>
		internal void Run()
		{
			if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "Begin ProcessRequest");


			try
			{
				// If we are using the async handler we have to set the ASPNET username
				// to have the same user rights for the created thread.

				if(token != IntPtr.Zero)
					winctx = System.Security.Principal.WindowsIdentity.Impersonate(token);


				// We will check the custom attributes and try to invoke the method.
		
				p.Context.Response.Expires = 0;
				p.Context.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);

				// TODO: check why Opera is not working with application/json;
				// p.Context.Response.AddHeader("Content-Type", "application/json; charset=utf-8");

				p.Context.Response.ContentType = p.ContentType;
				p.Context.Response.ContentEncoding = System.Text.Encoding.UTF8;

				if(!p.IsValidAjaxToken())
				{
					// TODO: maybe we want to throw a special exception type.
					p.SerializeObject(new System.Security.SecurityException("The AjaxNet-Token is not valid."));

					if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
					return;
				}

				object[] po = null;
				object res = null;

				#region Retreive Parameters from the HTTP Request

				try
				{
					// The IAjaxProcessor will read the values either form the 
					// request URL or the request input stream.

					po = p.RetreiveParameters();
				}
				catch(Exception ex)
				{
					p.SerializeObject(ex);

					if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
					return;
				}

				#endregion 

				// Check if we have the same request already in our cache. The 
				// cacheKey will be the type and a hashcode from the parameter values.

				string cacheKey = p.Type.FullName + "|" + p.GetType().Name + "|" + p.AjaxMethod.Name + "|" + p.GetHashCode();
				if(p.Context.Cache[cacheKey] != null)
				{
					if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "Using cached result");

					p.Context.Response.AddHeader("X-" + Constant.AjaxID + "-Cache", "server");

					// Return the full output of the last cached call
					p.Context.Response.Write(p.Context.Cache[cacheKey]);

					if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
					return;
				}

				#region Reflection part of Ajax.NET

				try
				{
					if (p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "Invoking " + p.Type.FullName + "." + p.AjaxMethod.Name);

					// If this is a static method we do not need to create an instance
					// of this class. Some classes do not have a default constructor.

					if (p.AjaxMethod.IsStatic)
					{
						try
						{
							res = p.Type.InvokeMember(
								p.AjaxMethod.Name,
								System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod,
								null, null, po);
						}
						catch(Exception ex)
						{
							if(ex.InnerException != null)
								p.SerializeObject(ex.InnerException);
							else
								p.SerializeObject(ex);

							if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
							return;
						}
					}
					else
					{
						// Create an instance of the class using the default constructor that will
						// not need any argument. This can be a problem, but currently I have no
						// idea on how to specify arguments for the constructor.

						if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "Reflection Start");

						try
						{
							object c = (object)Activator.CreateInstance(p.Type, new object[]{});

							if(c != null)
							{
//								if(po == null)
//									po = new object[p.Method.GetParameters().Length];

								res = p.AjaxMethod.Invoke(c, po);
							}
						}
						catch(Exception ex)
						{
#if(WEBEVENT)
							string errorText = string.Format(Constant.AjaxID + " Error", p.Context.User.Identity.Name);
#endif

							if (ex.InnerException != null)
							{
#if(WEBEVENT)
								Management.WebAjaxErrorEvent ev = new Management.WebAjaxErrorEvent(errorText, p, po, WebEventCodes.WebExtendedBase + 100, ex.InnerException);
								ev.Raise();
#endif
								p.SerializeObject(ex.InnerException);
							}
							else
							{
#if(WEBEVENT)
								Management.WebAjaxErrorEvent ev = new Management.WebAjaxErrorEvent(errorText, p, po, WebEventCodes.WebExtendedBase + 101, ex);
								ev.Raise();
#endif
								p.SerializeObject(ex);
							}

							if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
							return;
						}

						if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "Reflection End");

					}
				}
				catch(Exception ex)
				{
					if(ex.InnerException != null)
						p.SerializeObject(ex.InnerException);
					else
						p.SerializeObject(ex);

					if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
					return;
				}

				#endregion


				try
				{
					if(res != null && res.GetType() == typeof(System.Xml.XmlDocument))
					{
						// If the return value is XmlDocument we will return it direct
						// without any convertion. On the client-side function we can
						// use .responseXML or .xml.

						p.Context.Response.ContentType = "text/xml";
						p.Context.Response.ContentEncoding = System.Text.Encoding.UTF8;

						((System.Xml.XmlDocument)res).Save(p.Context.Response.OutputStream);


						if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
						return;
					}


					string result = null;;

					System.Text.StringBuilder sb = new System.Text.StringBuilder();

					try
					{
						result = p.SerializeObject(res);
					}
					catch(Exception ex)
					{
						p.SerializeObject(ex);

						if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
						return;
					}

					if(p.ServerCacheAttributes.Length > 0)
					{
						if (p.ServerCacheAttributes[0].IsCacheEnabled)
						{
							p.Context.Cache.Add(cacheKey, result, null, DateTime.Now.Add(p.ServerCacheAttributes[0].CacheDuration), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
							if (p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "Adding result to cache for " + p.ServerCacheAttributes[0].CacheDuration.TotalSeconds + " seconds (HashCode = " + p.GetHashCode().ToString() + ")");
						}
					}

					if(p.Context.Trace.IsEnabled)
					{
						p.Context.Trace.Write(Constant.AjaxID, "Result (maybe encrypted): " + result);
						p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
					}
				}
				catch(Exception ex)
				{
					p.SerializeObject(ex);

					if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
					return;
				}
				
			}
			catch(Exception ex)
			{
				p.SerializeObject(ex);

				if(p.Context.Trace.IsEnabled) p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
				return;
			}
			finally
			{
				if(token != IntPtr.Zero)
					winctx.Undo();
			}
		}
コード例 #2
0
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"></see> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"></see> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
		protected override string  GenerateScripts(HttpContext context)
		{
            StringBuilder sb = new StringBuilder();

            string className = filename;

			if(Utility.Settings != null && Utility.Settings.UrlClassMappings.ContainsKey(filename))
			{
                className = Utility.Settings.UrlClassMappings[filename] as string;
                if (context.Trace.IsEnabled) context.Trace.Write(Constant.AjaxID, "Url match to Type: " + className);
            }

            Type type = null;

            try
            {
                type = Type.GetType(className, true);
            }
            catch (Exception ex)
            {
                if (context.Trace.IsEnabled) { context.Trace.Write(Constant.AjaxID, "Type not found: " + className); ex.ToString(); }
#if(WEBEVENT)
				string errorText = string.Format(Constant.AjaxID + " Error", context.User.Identity.Name);

				Management.WebAjaxErrorEvent ev = new Management.WebAjaxErrorEvent(errorText, WebEventCodes.WebExtendedBase + 201, ex);
				ev.Raise();
#endif
                return null;
            }

			// Ok, we do not have the javascript rendered, yet.
			// Build the javascript source and save it to the current
			// Application context.

            // type handler url
			string url = context.Request.ApplicationPath 
                + (context.Request.ApplicationPath.EndsWith("/") ? "" : "/") 
                + Utility.HandlerPath + "/" + AjaxNet.Utility.GetSessionUri() + filename + Utility.HandlerExtension;

			// find all methods that are able to be used with AjaxNet

			MethodInfo[] mi = type.GetMethods();
			MethodInfo method;
#if(NET20)
			List<MethodInfo> methods = new List<MethodInfo>();
#else
			MethodInfo[] methods;
			System.Collections.ArrayList methodList = new System.Collections.ArrayList();

			int mc = 0;
#endif

			for (int y = 0; y < mi.Length; y++)
			{
				method = mi[y];

				if (!method.IsPublic)
					continue;

				AjaxMethodAttribute[] ma = (AjaxMethodAttribute[])method.GetCustomAttributes(typeof(AjaxMethodAttribute), true);

				if (ma.Length == 0)
					continue;

				PrincipalPermissionAttribute[] ppa = (PrincipalPermissionAttribute[])method.GetCustomAttributes(typeof(PrincipalPermissionAttribute), true);
				if (ppa.Length > 0)
				{
					bool permissionDenied = true;
					for (int p = 0; p < ppa.Length && permissionDenied; p++)
					{
#if(_____NET20)
						if (Roles.Enabled)
						{
							try
							{
								if (!String.IsNullOrEmpty(ppa[p].Role) && !Roles.IsUserInRole(ppa[p].Role))
									continue;
							}
							catch (Exception)
							{
								// Should we disable this AjaxMethod of there is an exception?
								continue;
							}

						}
						else
#endif
							if (ppa[p].Role != null && ppa[p].Role.Length > 0 && context.User != null && context.User.Identity.IsAuthenticated && !context.User.IsInRole(ppa[p].Role))
								continue;

						permissionDenied = false;
					}

					if (permissionDenied)
						continue;
				}

#if(NET20)
				methods.Add(method);
#else
				//methods[mc++] = method;
				methodList.Add(method);
#endif
			}

#if(!NET20)
			methods = (MethodInfo[])methodList.ToArray(typeof(MethodInfo));
#endif

			// render client-side proxy file
			TypeJavaScriptGenerator jsp = null;

			if (Utility.Settings.TypeJavaScriptGenerator != null)
			{
				try
				{
					Type jspt = Type.GetType(Utility.Settings.TypeJavaScriptGenerator);
					if (jspt != null && typeof(TypeJavaScriptGenerator).IsAssignableFrom(jspt))
					{
						jsp = (TypeJavaScriptGenerator)Activator.CreateInstance(jspt, new object[3] { type, url, sb });
					}
				}
				catch (Exception)
				{
				}
			}

			if (jsp == null)
			{
				jsp = new TypeJavaScriptGenerator(type, url, sb);
			}

			jsp.RenderNamespace();
			jsp.RenderClassBegin();
#if(NET20)
			jsp.RenderMethods(methods.ToArray());
#else
			jsp.RenderMethods(methods);
#endif
			jsp.RenderClassEnd();

            return sb.ToString();
		}
コード例 #3
0
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"></see> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"></see> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        protected override string  GenerateScripts(HttpContext context)
        {
            StringBuilder sb = new StringBuilder();

            string className = filename;

            if (Utility.Settings != null && Utility.Settings.UrlClassMappings.ContainsKey(filename))
            {
                className = Utility.Settings.UrlClassMappings[filename] as string;
                if (context.Trace.IsEnabled)
                {
                    context.Trace.Write(Constant.AjaxID, "Url match to Type: " + className);
                }
            }

            Type type = null;

            try
            {
                type = Type.GetType(className, true);
            }
            catch (Exception ex)
            {
                if (context.Trace.IsEnabled)
                {
                    context.Trace.Write(Constant.AjaxID, "Type not found: " + className); ex.ToString();
                }
#if (WEBEVENT)
                string errorText = string.Format(Constant.AjaxID + " Error", context.User.Identity.Name);

                Management.WebAjaxErrorEvent ev = new Management.WebAjaxErrorEvent(errorText, WebEventCodes.WebExtendedBase + 201, ex);
                ev.Raise();
#endif
                return(null);
            }

            // Ok, we do not have the javascript rendered, yet.
            // Build the javascript source and save it to the current
            // Application context.

            // type handler url
            string url = context.Request.ApplicationPath
                         + (context.Request.ApplicationPath.EndsWith("/") ? "" : "/")
                         + Utility.HandlerPath + "/" + AjaxNet.Utility.GetSessionUri() + filename + Utility.HandlerExtension;

            // find all methods that are able to be used with AjaxNet

            MethodInfo[] mi = type.GetMethods();
            MethodInfo   method;
#if (NET20)
            List <MethodInfo> methods = new List <MethodInfo>();
#else
            MethodInfo[] methods;
            System.Collections.ArrayList methodList = new System.Collections.ArrayList();

            int mc = 0;
#endif

            for (int y = 0; y < mi.Length; y++)
            {
                method = mi[y];

                if (!method.IsPublic)
                {
                    continue;
                }

                AjaxMethodAttribute[] ma = (AjaxMethodAttribute[])method.GetCustomAttributes(typeof(AjaxMethodAttribute), true);

                if (ma.Length == 0)
                {
                    continue;
                }

                PrincipalPermissionAttribute[] ppa = (PrincipalPermissionAttribute[])method.GetCustomAttributes(typeof(PrincipalPermissionAttribute), true);
                if (ppa.Length > 0)
                {
                    bool permissionDenied = true;
                    for (int p = 0; p < ppa.Length && permissionDenied; p++)
                    {
#if (_____NET20)
                        if (Roles.Enabled)
                        {
                            try
                            {
                                if (!String.IsNullOrEmpty(ppa[p].Role) && !Roles.IsUserInRole(ppa[p].Role))
                                {
                                    continue;
                                }
                            }
                            catch (Exception)
                            {
                                // Should we disable this AjaxMethod of there is an exception?
                                continue;
                            }
                        }
                        else
#endif
                        if (ppa[p].Role != null && ppa[p].Role.Length > 0 && context.User != null && context.User.Identity.IsAuthenticated && !context.User.IsInRole(ppa[p].Role))
                        {
                            continue;
                        }

                        permissionDenied = false;
                    }

                    if (permissionDenied)
                    {
                        continue;
                    }
                }

#if (NET20)
                methods.Add(method);
#else
                //methods[mc++] = method;
                methodList.Add(method);
#endif
            }

#if (!NET20)
            methods = (MethodInfo[])methodList.ToArray(typeof(MethodInfo));
#endif

            // render client-side proxy file
            TypeJavaScriptGenerator jsp = null;

            if (Utility.Settings.TypeJavaScriptGenerator != null)
            {
                try
                {
                    Type jspt = Type.GetType(Utility.Settings.TypeJavaScriptGenerator);
                    if (jspt != null && typeof(TypeJavaScriptGenerator).IsAssignableFrom(jspt))
                    {
                        jsp = (TypeJavaScriptGenerator)Activator.CreateInstance(jspt, new object[3] {
                            type, url, sb
                        });
                    }
                }
                catch (Exception)
                {
                }
            }

            if (jsp == null)
            {
                jsp = new TypeJavaScriptGenerator(type, url, sb);
            }

            jsp.RenderNamespace();
            jsp.RenderClassBegin();
#if (NET20)
            jsp.RenderMethods(methods.ToArray());
#else
            jsp.RenderMethods(methods);
#endif
            jsp.RenderClassEnd();

            return(sb.ToString());
        }
コード例 #4
0
        private IHttpHandler GetHandler(HttpContext context, string filename)
        {
            Type t = null;
            Exception typeException = null;
            string className = filename;

            if (Utility.Settings != null && Utility.Settings.UrlClassMappings.ContainsKey(filename))
            {
                className = Utility.Settings.UrlClassMappings[filename] as string;
                if (context.Trace.IsEnabled) context.Trace.Write(Constant.AjaxID, "Url match to Type: " + className);
            }

            try
            {
                t = Type.GetType(className, true);
            }
            catch (Exception ex)
            {
                if (context.Trace.IsEnabled) context.Trace.Write(Constant.AjaxID, "Type not found: " + className);
                typeException = ex;
            }

            AjaxProcessor[] p = new AjaxProcessor[3];
            p[0] = new XmlHttpRequestProcessor(context, t);
            p[1] = new IFrameProcessor(context, t);
            p[2] = new ExtJSProcessor(context, t);

            for (int i = 0; i < p.Length; i++)
            {
                if (!p[i].CanHandleRequest) continue;

                if (typeException != null)
                {
#if(WEBEVENT)
					string errorText = string.Format(Constant.AjaxID + " Error", context.User.Identity.Name);

					Management.WebAjaxErrorEvent ev = new Management.WebAjaxErrorEvent(errorText, WebEventCodes.WebExtendedBase + 200, typeException);
					ev.Raise();
#endif
                    p[i].SerializeObject(new NotSupportedException("This method is either not marked with an AjaxMethod or is not available."));
                    return null;
                }

                AjaxMethodAttribute[] ma = (AjaxMethodAttribute[])p[i].AjaxMethod.GetCustomAttributes(typeof(AjaxMethodAttribute), true);

                bool useAsync = false;
                HttpSessionStateRequirement sessionReq = HttpSessionStateRequirement.ReadWrite;

                if (ma.Length > 0)
                {
                    useAsync = ma[0].UseAsyncProcessing;

                    if (ma[0].RequireSessionState != HttpSessionStateRequirement.UseDefault)
                        sessionReq = ma[0].RequireSessionState;
                }

                switch (sessionReq)
                {
                    case HttpSessionStateRequirement.Read:
                        if (!useAsync)
                            return new AjaxSyncHttpHandlerSessionReadOnly(p[i]);
                        else
                            return new AjaxAsyncHttpHandlerSessionReadOnly(p[i]);

                    case HttpSessionStateRequirement.ReadWrite:
                        if (!useAsync)
                            return new AjaxSyncHttpHandlerSession(p[i]);
                        else
                            return new AjaxAsyncHttpHandlerSession(p[i]);

                    case HttpSessionStateRequirement.None:
                        if (!useAsync)
                            return new AjaxSyncHttpHandler(p[i]);
                        else
                            return new AjaxAsyncHttpHandler(p[i]);

                    default:
                        if (!useAsync)
                            return new AjaxSyncHttpHandlerSession(p[i]);
                        else
                            return new AjaxAsyncHttpHandlerSession(p[i]);
                }
            }

            return null;
        }
コード例 #5
0
ファイル: AjaxProcHelper.cs プロジェクト: percyboy/ajaxnet
        /// <summary>
        /// Runs this instance.
        /// </summary>
        internal void Run()
        {
            if (p.Context.Trace.IsEnabled)
            {
                p.Context.Trace.Write(Constant.AjaxID, "Begin ProcessRequest");
            }


            try
            {
                // If we are using the async handler we have to set the ASPNET username
                // to have the same user rights for the created thread.

                if (token != IntPtr.Zero)
                {
                    winctx = System.Security.Principal.WindowsIdentity.Impersonate(token);
                }


                // We will check the custom attributes and try to invoke the method.

                p.Context.Response.Expires = 0;
                p.Context.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);

                // TODO: check why Opera is not working with application/json;
                // p.Context.Response.AddHeader("Content-Type", "application/json; charset=utf-8");

                p.Context.Response.ContentType     = p.ContentType;
                p.Context.Response.ContentEncoding = System.Text.Encoding.UTF8;

                if (!p.IsValidAjaxToken())
                {
                    // TODO: maybe we want to throw a special exception type.
                    p.SerializeObject(new System.Security.SecurityException("The AjaxNet-Token is not valid."));

                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                    }
                    return;
                }

                object[] po  = null;
                object   res = null;

                #region Retreive Parameters from the HTTP Request

                try
                {
                    // The IAjaxProcessor will read the values either form the
                    // request URL or the request input stream.

                    po = p.RetreiveParameters();
                }
                catch (Exception ex)
                {
                    p.SerializeObject(ex);

                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                    }
                    return;
                }

                #endregion

                // Check if we have the same request already in our cache. The
                // cacheKey will be the type and a hashcode from the parameter values.

                string cacheKey = p.Type.FullName + "|" + p.GetType().Name + "|" + p.AjaxMethod.Name + "|" + p.GetHashCode();
                if (p.Context.Cache[cacheKey] != null)
                {
                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "Using cached result");
                    }

                    p.Context.Response.AddHeader("X-" + Constant.AjaxID + "-Cache", "server");

                    // Return the full output of the last cached call
                    p.Context.Response.Write(p.Context.Cache[cacheKey]);

                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                    }
                    return;
                }

                #region Reflection part of Ajax.NET

                try
                {
                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "Invoking " + p.Type.FullName + "." + p.AjaxMethod.Name);
                    }

                    // If this is a static method we do not need to create an instance
                    // of this class. Some classes do not have a default constructor.

                    if (p.AjaxMethod.IsStatic)
                    {
                        try
                        {
                            res = p.Type.InvokeMember(
                                p.AjaxMethod.Name,
                                System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod,
                                null, null, po);
                        }
                        catch (Exception ex)
                        {
                            if (ex.InnerException != null)
                            {
                                p.SerializeObject(ex.InnerException);
                            }
                            else
                            {
                                p.SerializeObject(ex);
                            }

                            if (p.Context.Trace.IsEnabled)
                            {
                                p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                            }
                            return;
                        }
                    }
                    else
                    {
                        // Create an instance of the class using the default constructor that will
                        // not need any argument. This can be a problem, but currently I have no
                        // idea on how to specify arguments for the constructor.

                        if (p.Context.Trace.IsEnabled)
                        {
                            p.Context.Trace.Write(Constant.AjaxID, "Reflection Start");
                        }

                        try
                        {
                            object c = (object)Activator.CreateInstance(p.Type, new object[] {});

                            if (c != null)
                            {
//								if(po == null)
//									po = new object[p.Method.GetParameters().Length];

                                res = p.AjaxMethod.Invoke(c, po);
                            }
                        }
                        catch (Exception ex)
                        {
#if (WEBEVENT)
                            string errorText = string.Format(Constant.AjaxID + " Error", p.Context.User.Identity.Name);
#endif

                            if (ex.InnerException != null)
                            {
#if (WEBEVENT)
                                Management.WebAjaxErrorEvent ev = new Management.WebAjaxErrorEvent(errorText, p, po, WebEventCodes.WebExtendedBase + 100, ex.InnerException);
                                ev.Raise();
#endif
                                p.SerializeObject(ex.InnerException);
                            }
                            else
                            {
#if (WEBEVENT)
                                Management.WebAjaxErrorEvent ev = new Management.WebAjaxErrorEvent(errorText, p, po, WebEventCodes.WebExtendedBase + 101, ex);
                                ev.Raise();
#endif
                                p.SerializeObject(ex);
                            }

                            if (p.Context.Trace.IsEnabled)
                            {
                                p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                            }
                            return;
                        }

                        if (p.Context.Trace.IsEnabled)
                        {
                            p.Context.Trace.Write(Constant.AjaxID, "Reflection End");
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (ex.InnerException != null)
                    {
                        p.SerializeObject(ex.InnerException);
                    }
                    else
                    {
                        p.SerializeObject(ex);
                    }

                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                    }
                    return;
                }

                #endregion


                try
                {
                    if (res != null && res.GetType() == typeof(System.Xml.XmlDocument))
                    {
                        // If the return value is XmlDocument we will return it direct
                        // without any convertion. On the client-side function we can
                        // use .responseXML or .xml.

                        p.Context.Response.ContentType     = "text/xml";
                        p.Context.Response.ContentEncoding = System.Text.Encoding.UTF8;

                        ((System.Xml.XmlDocument)res).Save(p.Context.Response.OutputStream);


                        if (p.Context.Trace.IsEnabled)
                        {
                            p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                        }
                        return;
                    }


                    string result = null;;

                    System.Text.StringBuilder sb = new System.Text.StringBuilder();

                    try
                    {
                        result = p.SerializeObject(res);
                    }
                    catch (Exception ex)
                    {
                        p.SerializeObject(ex);

                        if (p.Context.Trace.IsEnabled)
                        {
                            p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                        }
                        return;
                    }

                    if (p.ServerCacheAttributes.Length > 0)
                    {
                        if (p.ServerCacheAttributes[0].IsCacheEnabled)
                        {
                            p.Context.Cache.Add(cacheKey, result, null, DateTime.Now.Add(p.ServerCacheAttributes[0].CacheDuration), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
                            if (p.Context.Trace.IsEnabled)
                            {
                                p.Context.Trace.Write(Constant.AjaxID, "Adding result to cache for " + p.ServerCacheAttributes[0].CacheDuration.TotalSeconds + " seconds (HashCode = " + p.GetHashCode().ToString() + ")");
                            }
                        }
                    }

                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "Result (maybe encrypted): " + result);
                        p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                    }
                }
                catch (Exception ex)
                {
                    p.SerializeObject(ex);

                    if (p.Context.Trace.IsEnabled)
                    {
                        p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                    }
                    return;
                }
            }
            catch (Exception ex)
            {
                p.SerializeObject(ex);

                if (p.Context.Trace.IsEnabled)
                {
                    p.Context.Trace.Write(Constant.AjaxID, "End ProcessRequest");
                }
                return;
            }
            finally
            {
                if (token != IntPtr.Zero)
                {
                    winctx.Undo();
                }
            }
        }
コード例 #6
0
        private IHttpHandler GetHandler(HttpContext context, string filename)
        {
            Type      t             = null;
            Exception typeException = null;
            string    className     = filename;

            if (Utility.Settings != null && Utility.Settings.UrlClassMappings.ContainsKey(filename))
            {
                className = Utility.Settings.UrlClassMappings[filename] as string;
                if (context.Trace.IsEnabled)
                {
                    context.Trace.Write(Constant.AjaxID, "Url match to Type: " + className);
                }
            }

            try
            {
                t = Type.GetType(className, true);
            }
            catch (Exception ex)
            {
                if (context.Trace.IsEnabled)
                {
                    context.Trace.Write(Constant.AjaxID, "Type not found: " + className);
                }
                typeException = ex;
            }

            AjaxProcessor[] p = new AjaxProcessor[3];
            p[0] = new XmlHttpRequestProcessor(context, t);
            p[1] = new IFrameProcessor(context, t);
            p[2] = new ExtJSProcessor(context, t);

            for (int i = 0; i < p.Length; i++)
            {
                if (!p[i].CanHandleRequest)
                {
                    continue;
                }

                if (typeException != null)
                {
#if (WEBEVENT)
                    string errorText = string.Format(Constant.AjaxID + " Error", context.User.Identity.Name);

                    Management.WebAjaxErrorEvent ev = new Management.WebAjaxErrorEvent(errorText, WebEventCodes.WebExtendedBase + 200, typeException);
                    ev.Raise();
#endif
                    p[i].SerializeObject(new NotSupportedException("This method is either not marked with an AjaxMethod or is not available."));
                    return(null);
                }

                AjaxMethodAttribute[] ma = (AjaxMethodAttribute[])p[i].AjaxMethod.GetCustomAttributes(typeof(AjaxMethodAttribute), true);

                bool useAsync = false;
                HttpSessionStateRequirement sessionReq = HttpSessionStateRequirement.ReadWrite;

                if (ma.Length > 0)
                {
                    useAsync = ma[0].UseAsyncProcessing;

                    if (ma[0].RequireSessionState != HttpSessionStateRequirement.UseDefault)
                    {
                        sessionReq = ma[0].RequireSessionState;
                    }
                }

                switch (sessionReq)
                {
                case HttpSessionStateRequirement.Read:
                    if (!useAsync)
                    {
                        return(new AjaxSyncHttpHandlerSessionReadOnly(p[i]));
                    }
                    else
                    {
                        return(new AjaxAsyncHttpHandlerSessionReadOnly(p[i]));
                    }

                case HttpSessionStateRequirement.ReadWrite:
                    if (!useAsync)
                    {
                        return(new AjaxSyncHttpHandlerSession(p[i]));
                    }
                    else
                    {
                        return(new AjaxAsyncHttpHandlerSession(p[i]));
                    }

                case HttpSessionStateRequirement.None:
                    if (!useAsync)
                    {
                        return(new AjaxSyncHttpHandler(p[i]));
                    }
                    else
                    {
                        return(new AjaxAsyncHttpHandler(p[i]));
                    }

                default:
                    if (!useAsync)
                    {
                        return(new AjaxSyncHttpHandlerSession(p[i]));
                    }
                    else
                    {
                        return(new AjaxAsyncHttpHandlerSession(p[i]));
                    }
                }
            }

            return(null);
        }