utility.cs

来自「AJAX开发工具包」· CS 代码 · 共 371 行

CS
371
字号
/*
 * 
 * MS	05-12-20	changed AjaxSettins access, now thread safe for web farms
 * MS	06-04-05	fixed sessionID on ASP.NET 2.0, new static method GetSessionUri
 * MS	06-04-12	added useAssemblyQualifiedName
 * 
 * 
 * 
 */
using System;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Collections.Specialized;

namespace AjaxPro
{
	/// <summary>
	/// Provides methods to register Ajax methods.
	/// </summary>
	public sealed class Utility
	{
		/// <summary>
		/// Set the HandlerExtension configured in web.config/configuration/system.web/httpHandlers/add/@path:
		/// </summary>
		public static string HandlerExtension = ".ashx";

		/// <summary>
		/// Set the HandlerPath configured in web.config/configuration/system.web/httpHandlers/add/@path:
		/// </summary>
		public static string HandlerPath = "ajaxpro";

		private static AjaxSettings m_Settings = null;
		private static object m_SettingsLock = new object();
		internal static bool ConverterRegistered = false;

		/// <summary>
		/// Returns the session identifier.
		/// </summary>
		/// <returns>Returns the URL part for the session identifier.</returns>
		internal static string GetSessionUri()
		{
			string cookieUri = "";

			if (System.Web.HttpContext.Current.Session != null && System.Web.HttpContext.Current.Session.IsCookieless)
			{
#if(NET20)
				cookieUri = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_ASPFILTERSESSIONID"];
#else
				cookieUri = "(" + System.Web.HttpContext.Current.Session.SessionID + ")";
#endif
			}

			if (cookieUri != null && cookieUri.Length != 0)
				cookieUri += "/";

			return cookieUri;
		}

		/// <summary>
		/// Returns the name of the class and method the AjaxMethod will be rendered to the client-side JavaScript.
		/// </summary>
		/// <param name="method">The method you want to call.</param>
		/// <returns>Returns a string separated by a comma, i.e. "MyNamespace.MyClass,MyMethod"</returns>
		[Obsolete("The recommended alternative is AjaxPro.ClientMethod.FromMethodInfo.", false)]
		public static string GetClientMethod(MethodInfo method)
		{
			ClientMethod cm = ClientMethod.FromMethodInfo(method);

			if(cm == null)
				return null;

			return cm.ClassName + "," + cm.MethodName;
		}

		/// <summary>
		/// Writes an enum representation to the current page.
		/// </summary>
		/// <param name="type">The type of the enum.</param>
		public static void RegisterEnumForAjax(Type type)
		{
			System.Web.UI.Page page = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;

			RegisterEnumForAjax(type, page);
		}

		/// <summary>
		/// Writes an enum representation to the current page.
		/// </summary>
		/// <param name="type">The type of the enum.</param>
		/// <param name="page">The page where the JavaScript shoult be rendered in.</param>
		public static void RegisterEnumForAjax(Type type, System.Web.UI.Page page)
		{
			RegisterCommonAjax(page);

			RegisterClientScriptBlock(page, Constant.AjaxID + ".AjaxEnum." + type.FullName,
				"<script type=\"text/javascript\">\r\n" + JavaScriptUtil.GetEnumRepresentation(type) + "</script>");
		}


		/// <summary>
		/// Register the specified type (class) for the current page. This will also add the common JavaScript file.
		/// </summary>
		/// <param name="type">The tpye to register i.e. RegisterTypeForAjax(typeof(WebApplication1.WebForm1));</param>
		public static void RegisterTypeForAjax(Type type)
		{
			System.Web.UI.Page page = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;

			RegisterTypeForAjax(type, page);
		}

		/// <summary>
		/// Register the specified type (class) for the current page. This will also add the common JavaScript file.
		/// </summary>
		/// <param name="type">The tpye to register i.e. RegisterTypeForAjax(typeof(WebApplication1.WebForm1));</param>
		/// <param name="page">The Page the script should rendered on.</param>
		public static void RegisterTypeForAjax(Type type, System.Web.UI.Page page)
		{
			RegisterCommonAjax(page);

			string path = type.FullName + "," + type.Assembly.FullName.Substring(0, type.Assembly.FullName.IndexOf(","));
			if(Utility.Settings.UseAssemblyQualifiedName) path = type.AssemblyQualifiedName;


			if(Utility.Settings != null && Utility.Settings.UrlNamespaceMappings.ContainsValue(path))
			{
				foreach(string key in Utility.Settings.UrlNamespaceMappings.Keys)
				{
					if(Utility.Settings.UrlNamespaceMappings[key].ToString() == path)
					{
						path = key;
						break;
					}
				}
			}

			RegisterClientScriptBlock(page, "AjaxType." + type.FullName,
				"<script type=\"text/javascript\" src=\"" + System.Web.HttpContext.Current.Request.ApplicationPath + (System.Web.HttpContext.Current.Request.ApplicationPath.EndsWith("/") ? "" : "/") + Utility.HandlerPath + "/" + GetSessionUri() + path + Utility.HandlerExtension + "\"></script>");
		}

		public static void RegisterConverterForAjax(IJavaScriptConverter converter)
		{
			Utility.Settings.JavaScriptConverters.Add(converter);
		}

		#region Internal Members

		/// <summary>
		/// Get the settings configured in web.config.
		/// </summary>
		internal static AjaxSettings Settings
		{
			get
			{
				if(m_Settings != null)
					return m_Settings;

				lock(m_SettingsLock)
				{
                    if (m_Settings != null)
                        return m_Settings;      // Ok, one other thread has already initialized this value.

					AjaxSettings settings = null;

					try
					{
#if(NET20)
						settings = (AjaxSettings)System.Configuration.ConfigurationManager.GetSection("ajaxNet/ajaxSettings");
#else
						settings = (AjaxSettings)System.Configuration.ConfigurationSettings.GetConfig("ajaxNet/ajaxSettings");
#endif
					}
					catch(Exception)
					{}

					if(settings == null)
						settings = new AjaxSettings();

					#region Default Converters

					settings.JavaScriptConverters.Add(new NameValueCollectionConverter());

					settings.JavaScriptConverters.Add(new DateTimeConverter());

					settings.JavaScriptConverters.Add(new DataRowConverter());
					settings.JavaScriptConverters.Add(new DataTableConverter());
					settings.JavaScriptConverters.Add(new DataSetConverter());
					settings.JavaScriptConverters.Add(new DataViewConverter());

					settings.JavaScriptConverters.Add(new HtmlControlConverter());

					settings.JavaScriptConverters.Add(new IListConverter());
					settings.JavaScriptConverters.Add(new IDictionaryConverter());
					settings.JavaScriptConverters.Add(new IEnumerableConverter());

					#endregion

					// now make the setting visible to all threads
					m_Settings = settings;

					return m_Settings;
				}
			}
		}

		internal static string CurrentAjaxToken
		{
			get
			{
				if(System.Web.HttpContext.Current == null || System.Web.HttpContext.Current.Request == null)
					return null;

				if(Utility.Settings == null)
					return null;

				string token = "";

				string ip = MD5Helper.GetHash(System.Web.HttpContext.Current.Request.UserHostAddress);
				string agent = MD5Helper.GetHash(System.Web.HttpContext.Current.Request.UserAgent);
				string site = MD5Helper.GetHash("Michael Schwarz" + Utility.Settings.TokenSitePassword);

				if(ip == null || ip.Length == 0 || agent == null || agent.Length == 0 || site == null || site.Length == 0)
					return null;

				token = ip.Substring(0, 5) + "-" + agent.Substring(0, 5) + "-" + site.Substring(0, 5);

				return MD5Helper.GetHash(token);
			}
		}

		/// <summary>
		/// Register the common JavaScript to the current handler.
		/// </summary>
		internal static void RegisterCommonAjax()
		{
			RegisterCommonAjax((System.Web.UI.Page)System.Web.HttpContext.Current.Handler);
		}

		/// <summary>
		/// Register the common JavaScript file for the specified page.
		/// </summary>
		/// <param name="page">The Page the client script should be rendered to.</param>
		internal static void RegisterCommonAjax(System.Web.UI.Page page)
		{
			if(page == null)
				return;

			// If there is a configuration for this fileName in
			// web.config AjaxPro section scriptReplacements we will
			// redirect to this file.

			string rootFolder = System.Web.HttpContext.Current.Request.ApplicationPath + (System.Web.HttpContext.Current.Request.ApplicationPath.EndsWith("/") ? "" : "/");

			string prototypeJs = rootFolder + Utility.HandlerPath + "/prototype" + Utility.HandlerExtension;
			string coreJs = rootFolder + Utility.HandlerPath + "/core" + Utility.HandlerExtension;
			string convertersJs = rootFolder + Utility.HandlerPath + "/converter" + Utility.HandlerExtension;

			if(Utility.Settings != null)
			{
				if(Utility.Settings.ScriptReplacements.ContainsKey("prototype"))
				{
					prototypeJs = Utility.Settings.ScriptReplacements["prototype"];
					if(prototypeJs.Length > 0 && prototypeJs.StartsWith("~/"))
						prototypeJs = rootFolder + prototypeJs.Substring(2);
				}
				if(Utility.Settings.ScriptReplacements.ContainsKey("core"))
				{
					coreJs = Utility.Settings.ScriptReplacements["core"];
					if(coreJs.Length > 0 && coreJs.StartsWith("~/"))
						coreJs = rootFolder + coreJs.Substring(2);
				}
				if(Utility.Settings.ScriptReplacements.ContainsKey("converter"))
				{
					convertersJs = Utility.Settings.ScriptReplacements["converter"];
					if(convertersJs.Length > 0 && convertersJs.StartsWith("~/"))
						convertersJs = rootFolder + convertersJs.Substring(2);
				}
			}

			if(prototypeJs.Length > 0)
				RegisterClientScriptBlock(page, Constant.AjaxID + ".prototype",
					"<script type=\"text/javascript\" src=\"" + prototypeJs + "\"></script>");

			if(coreJs.Length > 0)
				RegisterClientScriptBlock(page, Constant.AjaxID + ".core",
					"<script type=\"text/javascript\" src=\"" + coreJs + "\"></script>");

			if(convertersJs.Length > 0)
				RegisterClientScriptBlock(page, Constant.AjaxID + ".converters",
					"<script type=\"text/javascript\" src=\"" + convertersJs + "\"></script>");


			if(Settings.TokenEnabled)
			{
				RegisterClientScriptBlock(page, Constant.AjaxID + ".token",
					"<script type=\"text/javascript\">AjaxPro.token = \"" + CurrentAjaxToken + "\";</script>");
			}
		}

		internal static HybridDictionary pages = new HybridDictionary();

		internal static ListDictionary GetScripts(System.Web.UI.Page page, bool RemoveFromCollection)
		{
			lock(pages.SyncRoot)
			{
				ListDictionary scripts = (ListDictionary)pages[page];

				if(RemoveFromCollection && scripts != null)
				{
					pages.Remove(page);
				}

				if(!RemoveFromCollection && scripts == null)
				{
					scripts = new System.Collections.Specialized.ListDictionary();
					pages[page] = scripts;
				}

				return scripts;
			}
		}

		internal static ListDictionary GetScripts(System.Web.UI.Page page)
		{
			return GetScripts(page, false);
		}
        
		internal static void RegisterClientScriptBlock(System.Web.UI.Page page, string key, string script)
		{
			page.PreRender += new EventHandler(page_PreRender);
			
			ListDictionary scripts = GetScripts(page);

			if (scripts.Contains(key))
				return;
            
			scripts.Add(key, script);
		}

		private static void page_PreRender(object sender, EventArgs e)
		{
			System.Web.UI.Page page = (System.Web.UI.Page)sender;
		
			ListDictionary scripts = GetScripts(page, true);

			if (scripts == null)
				return;

			StringBuilder sb = new StringBuilder();

			sb.Append("\r\n");

			foreach(string script in scripts.Values)
			{
				sb.Append(script);
				sb.Append("\r\n");
			}

			if(page != null)
#if(NET20)
                // TODO: replace by page.RegisterClientScriptInclude
                page.RegisterClientScriptBlock(Constant.AjaxID, sb.ToString());
#else
				page.RegisterClientScriptBlock(Constant.AjaxID, sb.ToString());
#endif
		}

		#endregion
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?