Base Web Page

/*
Author: Clarion Li
Date: Oct.22, 2004  (My nephew is two months old)
Purpose:
	check user login
	client call server's method(in Page or UserControl)

* /

/*
client function: 
	function CallServerMethodSkipClientValidate(methodName, methodParams)
	{                     
		document.all['__methodName'].value = methodName;
		document.all['__methodParams'].value = methodParams;
		document.forms[0].submit();
	}
	function CallServerMethod(methodName, methodParams)
	{
		if (typeof(Page_ClientValidate) != 'undefined')
		{                 
			if (!Page_ClientValidate()) return;
		}
		CallServerMethodSkipClientValidate(methodName,methodParams);
	}
	
useage:
	method on Page:	
		<INPUT οnclick="CallServerMethod('Alert','Hello');" type="button" value="Button">
			"Alert" is the public method in this Page
			"Hello" is the method "Alert"'s Parameter

		
	method on UserControls:
		<INPUT type="button" οnclick="CallServerMethodSkipClientValidate('<%=this.UniqueID%>*WUC','Hello');">
			"<%=this.UniqueID%>" is UserControls's UniqueID
			"WUC" is the method name in the UserControl
			"Hello" is the method "Alert"'s Parameter
	
 */


using System;
using System.Web.UI;

namespace WebApp4
{
	public class BasePage : Page
	{
		ServerMethodProxy smp = null;
			 
		protected override void OnInit(EventArgs e)
		{
			if (!this.CheckUser())
			{
				this.ForceLogin();
			}

			base.OnInit (e);

			smp = new ServerMethodProxy(this);
		}

		protected virtual bool CheckUser()
		{
			return true;
		}

		protected virtual void ForceLogin()
		{
			Response.Redirect("", true);
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad (e);

			if (IsPostBack)
			{
				smp.Handle();
			}
		}

	}

	public class ServerMethodProxy : IPostBackEventHandler
	{
		private System.Web.UI.Page page;

		private const string constMethodName = "__methodName";
		private const string constMethodParams = "__methodParams";

		private string methodName = null;
		private string methodParameters = null;

		public ServerMethodProxy(System.Web.UI.Page page) 
		{
			this.page = page;
			this.RegisterClientScript();
		}

		public void Handle()
		{
			methodName = this.page.Request.Form[constMethodName];
			if (methodName + "" == "")
			{
				return;
			}

			methodParameters = this.page.Request.Form[constMethodParams];

			try
			{
				System.Type t = this.page.GetType();
				while (t.BaseType != null)
				{
					if (t.FullName == "System.Web.UI.Page")
					{
						System.Reflection.FieldInfo fi = t.GetField("_registeredControlThatRequireRaiseEvent", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
						fi.SetValue(this.page, this);
						break;
					}
					t = t.BaseType;
				}
			}
			catch
			{
				InvokeServerMethod();
			}
			
		}

		private void RegisterClientScript()
		{
			this.page.RegisterHiddenField(constMethodName, "");
			this.page.RegisterHiddenField(constMethodParams, "");

			string script = @"
				<script language='javascript' type='text/javascript'>
					function CallServerMethodSkipClientValidate(methodName, methodParams)
					{                     
						document.all['constmethodName'].value = methodName;
						document.all['constmethodParams'].value = methodParams;
						document.forms[0].submit();
					}
					function CallServerMethod(methodName, methodParams)
					{
						if (typeof(Page_ClientValidate) != 'undefined')
						{                 
							if (!Page_ClientValidate()) return;
						}
						CallServerMethodSkipClientValidate(methodName,methodParams);
					}
				</script>";

			this.page.RegisterStartupScript("CallServerMethod", script.Replace("constmethodName", constMethodName).Replace("constmethodParams", constMethodParams));

		}

		private void InvokeServerMethod()
		{

			System.Reflection.MethodInfo mi = null;

			try
			{
				int starPos = methodName.IndexOf("*");
				if (starPos != -1)			//find star
				{
					string[] ss = methodName.Split('*');
					Control c = this.page.FindControl(ss[0]);		//ss[0] is UserControl's UniqueID
					if (c == null)
					{
						throw new Exception("Can't find the type: " + ss[0]);
					}
					mi = this.GetMethodByName(c.GetType().BaseType, ss[1]);			//ss[1] is Method Name;
					mi.Invoke(c, new object[] { methodParameters});
				}
				else
				{
					mi = this.GetMethodByName(this.page.GetType().BaseType, methodName);
					mi.Invoke(this.page, new object[] { methodParameters});
				}
			}
			catch (System.Reflection.TargetInvocationException ex)
			{
				if (ex.InnerException != null && ex.InnerException is System.Threading.ThreadAbortException)
				{
					return;
				}
				else
				{
					throw ex;
				}
			}
		}

		private System.Reflection.MethodInfo GetMethodByName(System.Type t, string name)
		{
			return t.GetMethod(name);
		}


		#region IPostBackEventHandler Members

		public void RaisePostBackEvent(string eventArgument)
		{
			this.InvokeServerMethod();
		}

		#endregion
	}
}
 
ServerMethodProxy for ASP.net 2.0
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;

namespace Freeborders.PLM.WebFramework
{
    public class ServerMethodProxy
    {
        private System.Web.UI.Page page;

        private const string constMethodName = "__methodName";
        private const string constMethodParams = "__methodParams";

        public ServerMethodProxy(System.Web.UI.Page page)
        {
            this.page = page;

            this.page.LoadComplete += new EventHandler(OnLoadComplete);

            this.RegisterClientScript();
        }

        void OnLoadComplete(object sender, EventArgs e)
        {
            this.InvokeServerMethod();
        }

        private void RegisterClientScript()
        {
            this.page.ClientScript.RegisterHiddenField(constMethodName, "");
            this.page.ClientScript.RegisterHiddenField(constMethodParams, "");

            string script = @"
				<script language='javascript' type='text/javascript'>
					function CallServerMethodSkipClientValidate(methodName, methodParams)
					{                     
						document.all['constmethodName'].value = methodName;
						document.all['constmethodParams'].value = methodParams;
						document.forms[0].submit();
					}
					function CallServerMethod(methodName, methodParams)
					{
						if (typeof(Page_ClientValidate) != 'undefined')
						{                 
							if (!Page_ClientValidate('')) return;
						}
						CallServerMethodSkipClientValidate(methodName,methodParams);
					}
				</script>";

            this.page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServerMethod", script.Replace("constmethodName", constMethodName).Replace("constmethodParams", constMethodParams));

        }

        private void InvokeServerMethod()
        {

            string methodName = this.page.Request.Form[constMethodName];

            if (string.IsNullOrEmpty(methodName))
            {
                return;
            }

            string methodParameters = this.page.Request.Form[constMethodParams];

            System.Reflection.MethodInfo mi = null;

            try
            {
                int userControlUniqueIDLength = methodName.LastIndexOf(":");
                if (userControlUniqueIDLength != -1)			//find user control unique ID
                {
                    string userControlUniqueID = methodName.Substring(0, userControlUniqueIDLength);
                    string serverMethodName = methodName.Substring(userControlUniqueIDLength + 1);
                    Control c = this.page.FindControl(userControlUniqueID);
                    if (c == null)
                    {
                        throw new Exception("Can't find the type: " + userControlUniqueID);
                    }
                    mi = this.GetMethodByName(c.GetType().BaseType, serverMethodName);
                    mi.Invoke(c, new object[] { methodParameters });
                }
                else
                {
                    mi = this.GetMethodByName(this.page.GetType().BaseType, methodName);
                    mi.Invoke(this.page, new object[] { methodParameters });
                }
            }
            catch (System.Reflection.TargetInvocationException ex)
            {
                if (ex.InnerException is System.Threading.ThreadAbortException)
                {
                    return;
                }
                else
                {
                    throw ex;
                }
            }
        }

        private System.Reflection.MethodInfo GetMethodByName(System.Type t, string name)
        {
            return t.GetMethod(name);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值