asp.net implementation of very practical custom page base class (with source code) _ Practical Skills

Source: Internet
Author: User
Tags datetime dotnet error handling exception handling httpcontext reflection static class trim

The examples in this article describe a very useful custom page base class for ASP.net implementations. Share to everyone for your reference, specific as follows:

See the previous articles (such as: "ASP.net implementation using reflection, generics, static methods to quickly get form values to model method") thought of. The following summary of the author in the development of a commonly used in a custom basepage class, nonsense not to say more, directly paste code.

First, BasePage class

1, code

Using System;
Using System.Data;
Using System.Configuration;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;
Using System.Reflection;
 Namespace DotNet.Common.WebForm {using DotNet.Common.Model;
 Using DotNet.Common.Util;
  public class BasePage:System.Web.UI.Page {public BasePage () {} protected override void OnInit (EventArgs e) {base.
   OnInit (e); Cancelformcontrolenterkey (this. Page.Form.Controls); Cancels the ENTER key for the page text box #region to cancel the Enter key feature of the page text control///<summary>///Here we add clients to the server controls in form onkeydown footstep events to prevent clothing The service control presses the ENTER key to return directly to///</summary>///<param name= "Controls" ></param> public virtual void Cancelform
   Controlenterkey (ControlCollection controls) {//page registration script used to cancel input of the ENTER key function Registerundoenterkeyscript (); foreach (Control item in controls) {//server textbox if (item. GetType () = = TyPeof (System.Web.UI.WebControls.TextBox)) {WebControl WebControl = Item as WebControl;
    WEBCONTROL.ATTRIBUTES.ADD ("onkeydown", "Return Forbidinputkeydown (Event)"); //html control else if (item. GetType () = = typeof (System.Web.UI.HtmlControls.HtmlInputText)) {HtmlInputControl HTMLControl = Item as Htmlinput
     control;
    HTMLCONTROL.ATTRIBUTES.ADD ("onkeydown", "Return Forbidinputkeydown (Event)"); //user Control else if (item is System.Web.UI.UserControl) {Cancelformcontrolenterkey (item). Controls); Recursive call}}///<summary>///register forbidinputkeydown script///</summary> private void Register Undoenterkeyscript () {string js = string.
   Empty;
   System.Text.StringBuilder sb = new System.Text.StringBuilder (); Sb.
   Append ("function forbidinputkeydown (EV) {"); Sb.
   Append ("If" (typeof (EV)!= \ "undefined\") {); Sb. Append ("If" (Ev.keycode | |
   Ev.which) {"); Sb. Append ("if" (Ev.keycode = 13 | | | Ev.which = {RETurn false;
   }"); Sb.
   Append ("}}}"); JS = sb.
   ToString (); if (!this. Page.ClientScript.IsClientScriptBlockRegistered ("Forbidinput2keydown")) this.
  Page.ClientScript.RegisterClientScriptBlock (typeof (Page), "Forbidinput2keydown", JS, True); #endregion #region///<summary>///The value of the control from the Reflection Fetch/Assignment page control and assign values to the object///</summary>///<param Name= "DataType" > Object type to be assigned </param>///<returns></returns> public virtual Baseobj getformdata ( Type DataType) {baseobj data = (baseobj) activator.createinstance (dataType);//Instantiate a class type Pgtype = this. GetType (); Identify the current page bindingflags bf = BindingFlags.Public | bindingflags.static | BindingFlags.Instance | bindingflags.nonpublic;//reflection identification propertyinfo[] Propinfos = data. GetType (). GetProperties ()///Remove All public properties foreach (PropertyInfo item in Propinfos) {FieldInfo fipage = Pgtype.getfield (ITEM.N AME, BF)//Remove a field from the page that satisfies a property if (fipage!= null)//The field of the page is not empty, representing the existence of an instantiated control class {OBJect value = null; Control Pgcontrol = (Control) fipage.getvalue (this);
     Depending on the property, the page-corresponding control is found, which requires that the page control name must correspond to the object's attribute one by one//below value Type ControlType = Pgcontrol.gettype (); if (ControlType = = typeof (label)) {value = (label) pgcontrol).
     Text.trim (); else if (ControlType = = typeof (TextBox)) {value = (textbox) Pgcontrol).
     Text.trim (); else if (ControlType = = typeof (HtmlInputText)) {value = (HtmlInputText) pgcontrol).
     Value.trim (); else if (ControlType = = typeof (HiddenField)) {value = (HiddenField) pgcontrol).
     Value.trim (); else if (ControlType = = typeof (checkbox)) {value = ((checkbox) Pgcontrol). Checked)//check box} else if (ControlType = = typeof (DropDownList))//dropdown Box {value = (DropDownList) Pgcontro L).
     SelectedValue; else if (ControlType = = typeof (RadioButtonList))//Radio box List {value = (RadioButtonList) pgcontrol).
      SelectedValue; if (Value!= NULL) {if (value). ToString (). ToUpper ()!= "TRUE" && value. ToString (). ToUpper ()!= "FALSE" value = value. ToString () = = "1"?
      True:false; } else if (ControlType = = typeof (image))//Picture {value = (image) Pgcontrol).
     IMAGEURL;
      try {object realvalue = null; if (item. Propertytype.equals (typeof (Nullable<datetime>))//generic nullable type {if (value!= null) {if (St Ring. IsNullOrEmpty (value.
        ToString ())) {realvalue = null; else {realvalue = DateTime.Parse (value.
        ToString ()); ' Else if ' (item.
      Propertytype.equals (typeof (Nullable))//nullable type {realvalue = value; else {try {realvalue = Convert.changetype (value, item.
       PropertyType);
       catch {realvalue = null; }} item.
    SetValue (data, realvalue, NULL); The catch (FormatException Fex) {DotNet.Common.Util.Logger.WriteFileLog (Fex).
      Message, HttpContext.Current.Request.PhysicalApplicationPath + "LogFile");
     Throw Fex; The catch (Exception ex) {DotNet.Common.Util.Logger.WriteFileLog (ex).
      Message, HttpContext.Current.Request.PhysicalApplicationPath + "LogFile");
     Throw ex;
  }} return data; ///<summary>///assigns values to page controls through the object's property values///</summary>///<param name= "Data" ></param> Publ IC virtual void Setformdata (Baseobj data) {Type Pgtype = this.
   GetType (); BindingFlags bf = BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic |
   bindingflags.static; propertyinfo[] Propinfos = data. GetType ().
   GetProperties (); foreach (PropertyInfo item in Propinfos) {FieldInfo MyField = Pgtype.getfield (item.
    Name, BF); if (MyField!= null) {Control mycontrol = (controls) myfield.getvalue (this); = Item. GetValue (data, NULL); Takes the property value Type Proptype = Item of the object.
     PropertyType; if (value!= null) {Type valuetype = value.
      GetType ();
       try {Type ControlType = Mycontrol.gettype (); if (ControlType = = typeof (label)) {if (valuetype = = typeof (DateTime)) {(label) mycontrol ). Text = (Convert.todatetime (value)).
        ToShortDateString (); } else {((Label) mycontrol). Text = value.
        ToString ();
         } else if (ControlType = = typeof (TextBox) {if (valuetype = = typeof (DateTime)) { ((TextBox) mycontrol). Text = (Convert.todatetime (value)).
        ToShortDateString (); } else {((TextBox) mycontrol). Text = value.
        ToString ();
        } else if (ControlType = = typeof (HtmlInputText)) {if (valuetype = = typeof (DateTime)) {((HtmlInputText) mycontrol). Value = (Convert.todatetime (value)). TOshortdatestring (); } else {((HtmlInputText) mycontrol). Value = value.
        ToString (); } else if (ControlType = = typeof (HiddenField)) {(HiddenField) mycontrol). Value = value.
       ToString ();
         else if (ControlType = = typeof (CheckBox) {if (valuetype = = typeof (Boolean))//Boolean { if (value. ToString (). ToUpper () = = "TRUE" (CheckBox) mycontrol).
         Checked = true; Else (CheckBox) mycontrol.
        Checked = false; else if (valuetype = = typeof (Int32))//Integer (Normally, 1 identity selected, 0 ID not selected) {(CheckBox) mycontrol). Checked = String.Compare (value.
        ToString (), "1") = = 0; } else if (ControlType = = typeof (DropDownList)) {try {(DropDownList) MyC Ontrol). SelectedValue = value.
        ToString (); The catch {(DropDownList) mycontrol).
        SelectedIndex =-1;
    }
       }   else if (ControlType = = typeof (RadioButton)) {if (valuetype = = typeof (Boolean))//Boolean { if (value. ToString (). ToUpper () = = "TRUE" ((RadioButton) mycontrol).
         Checked = true; Else ((RadioButton) mycontrol).
        Checked = false; else if (valuetype = = typeof (Int32))//Integer (Normally, 1 identity selected, 0 ID not selected) {(RadioButton) mycontrol). Checked = String.Compare (value.
        ToString (), "1") = = 0; } else if (ControlType = = typeof (RadioButtonList)) {try {if (valuetype = = typeof (Boolean)//Boolean {if (value). ToString (). ToUpper () = = "TRUE" ((RadioButtonList) mycontrol).
          SelectedValue = "1"; Else ((RadioButtonList) mycontrol).
         SelectedValue = "0"; Else ((RadioButtonList) mycontrol). SelectedValue = value.
        ToString (); The catch {(RadioButtonList) mycontrol). SelectedIndex=-1; } else if (ControlType = = typeof (image)) {(image) mycontrol). IMAGEURL = value.
       ToString (); } catch (FormatException Fex) {DotNet.Common.Util.Logger.WriteFileLog (Fex).
      Message, HttpContext.Current.Request.PhysicalApplicationPath + "LogFile"); The catch (Exception ex) {DotNet.Common.Util.Logger.WriteFileLog (ex).
      Message, HttpContext.Current.Request.PhysicalApplicationPath + "LogFile");
  #endregion #region Log processing///<summary>///error Handling: Write log, navigate to public error page///</summary> <param name= "E" ></param> protected override void OnError (EventArgs e) {Exception ex = this.
   Server.GetLastError (); String error = this.
   Dealexception (ex);
   DotNet.Common.Util.Logger.WriteFileLog (Error, HttpContext.Current.Request.PhysicalApplicationPath + "LogFile"); if (ex. InnerException!= null) {error = this.
    Dealexception (ex); Dotnet.coMmon.
   Util.Logger.WriteFileLog (Error, HttpContext.Current.Request.PhysicalApplicationPath + "LogFile"); } this.
   Server.ClearError (); This.
  Response.Redirect ("/error.aspx"); ///<summary>///handles exceptions to write primary exception information to the text log///</summary>///<param name= "ex" ></param>// /<returns></returns> private String Dealexception (Exception ex) {this. application["StackTrace"] = ex.
   StackTrace; This. application["Messageerror"] = ex.
   message; This. application["Sourceerror"] = ex.
   Source; This. application["TargetSite"] = ex.
   Targetsite.tostring (); String error = String. Format ("url:{0}\n method that throws an exception: {1}\n error message: {2}\n error stack: {3}\n", this. Request.rawurl, ex. TargetSite, ex. Message, ex.
   StackTrace);
  return error;

 } #endregion}}

2. Assigning values to controls using reflection

Depending on the ID of an employee (employee), the employee class inherits from the Baseobj class and assigns a value to the page control based on this client object:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Text;
Using System.Threading;
Namespace WebTest
{
 using DotNet.Common.WebForm;
 Using DotNet.Common.Model;
 Using EntCor.Hrm.Model;
 public partial class _default:basepage
 {
  protected void Page_Load (object sender, EventArgs e)
  {
   if (! IsPostBack)
   {
    Employee employee = new Employee {ID = 1, UserName = "Jeff Wong", address = "Beijing", Isleave = False , realname = "Test User", state = "2"};
    This. Setformdata (employee); Assign value to page control
   }}}


3. Assigning values to objects using reflection

Click the "Test" button to assign the value of the page control (Runat=server) to the entity object:

protected void Btnset_click (object sender, EventArgs e)
{
 Employee employee = (employee) this. Getformdata (typeof (Employee));
 StringBuilder sb = new StringBuilder ();
 Sb. Append ("Login name:" + employee.) UserName + "<br/>");
 Sb. Append ("real name:" + employee. Realname + "<br/>");
 Sb. Append ("Location:" + employee.) Address + "<br/>");
 Sb. Append ("Resignation:" + employee. Isleave + "<br/>");
 Sb. Append ("On-the-job Status:" + employee. State + "<br/>");
 This.ltrContext.Text = sb. ToString ();
}

Summarize:

(1), for more controls on the page, the reflection in this class and the method of assigning values is very useful (more disgusting is that you want to 哼唧 哼唧 to the page control by name. Kao, entity class has code generator automatic generation I'll take it. Page controls also have to be named one by one, and it is estimated that many programmers spend less time on this and do not consider the impact of reflection on performance. But from the simplicity of the code, this does seem to be out, but, I used to, the name more than a few, in the search for a stable and reliable solution, the short time seems to not choose to improve the;
(2), if the page has a user control (UserControl), the user control in the child control directly in the page is more difficult to get (you may already see the clue to the problem), The solution is to generate the entity class in the user control (this can imitate BasePage write a Basecontrol class, let the user control inherit Basecontrol, and then take the value.) Originally wanted to open a separate introduction, but found that the code similar, give up;
(3), cancel the page text box enter key you can refer to the "ASP.net implementation of the page form inside the text input box to enter the response method";
(4), exception handling see (ii).

Ii. Exception Handling

1, the Log class (oneself write a simple common text log processing Class)

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.IO;
Using System.Web; namespace DotNet.Common.WebForm {///<summary>///Log Class (commonly used in log4net, where a write text log class is implemented in a simple way)///</summary> Publ IC Static class Logutil {///<summary>///write Exception Log///</summary>///<param name= "ex" ></par am> public static void Writefilelog (String exmsg) {string path = HttpContext.Current.Request.PhysicalApplicatio
   Npath + "LogFile";
   FileStream fs = null;
   StreamWriter m_streamwriter = null; try {if (!
    Directory.Exists (Path)) {directory.createdirectory (path);
    Path = path + "\ \" + DateTime.Now.ToString ("yyyyMMdd") + ". txt";
    FS = new FileStream (path, FileMode.OpenOrCreate, FileAccess.Write);
    M_streamwriter = new StreamWriter (FS);
    M_streamWriter.BaseStream.Seek (0, Seekorigin.end);
    M_streamwriter.writeline (DateTime.Now.ToString () + "\ n"); M_streamwriter.writeline ("-----------------------------------------------------------");
    M_streamwriter.writeline ("-----------------------------------------------------------");
    M_streamwriter.writeline (EXMSG);
    M_streamwriter.writeline ("-----------------------------------------------------------");
    M_streamwriter.writeline ("-----------------------------------------------------------");
   M_streamwriter.flush ();
    finally {if (m_streamwriter!= null) {m_streamwriter.close (); } if (fs!= null) {fs.
    Close ();

 }
   }
  }
 }
}

2, Error.aspx

This comparison is not language. Often used to provide a good error page. For developers, it is recommended to display complete exception information.

Here's a page to help developers:

(1), design page

<%@ Page language= "C #" autoeventwireup= "true" codebehind= "Error.aspx.cs" inherits= "Error"%> DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
">  

(2), implementation code

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Web.UI;
Using System.Web.UI.WebControls;
public partial class ErrorPage:System.Web.UI.Page
{
 protected void Page_Load (object sender, EventArgs e)
 {
  This.lblStackTrace.Text = this. application["StackTrace"] as String;
  This.lblMessageError.Text = this. application["Messageerror"] as String;
  This.lblSourceError.Text = this. application["Sourceerror"] as String;
  This.lblTagetSiteError.Text = this. application["TargetSite"] as String;
 }
}

Full instance code code click here to download the site.

I hope this article will help you to ASP.net program design.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.