Learn how to create server controls (for more information, please advise)

Source: Internet
Author: User
Tags control label
Using system; using system. collections. generic; using system. componentmodel; using system. LINQ; using system. text; using system. web; using system. web. ui; using system. web. UI. webcontrols; using system. security. permissions; namespace servercontrol {// <summary> /// if the user name appears in the title sent by the user's browser, welcomelabel appends the user name to the text string. /// </Summary> // [aspnethostingpermission (securityaction. demand, Level = aspnethostingpermissionlevel. minimal)] // [aspnethostingpermission (securityaction. inheritancedemand, level = aspnethostingpermissionlevel. minimal)] [parsechildren (true, "text")] [defaultproperty ("text")] [toolboxdata ("<{0 }: servercontrolxin runat = \ "Server \"> </{0}: servercontrolxin> ")] public class servercontrolxin: webcontrol {[Binda Ble (true)] [category ("appearance")] [defaultvalue ("first control")] [description ("Server Control")] [localizable (true)] public String text {get {string S = (string) viewstate ["text"]; Return (S = NULL )? String. empty: S) ;}set {viewstate ["text"] = value ;}} protected override void rendercontents (htmltextwriter writer) {// encode the text by line. writeencodedtext (text); // use the write method in hemltextwriter to write the content to the stream writer. write ("Xin, forget, is your eyes light like water, shallow indulge in my life of joy and sorrow... "); Writer. Write (text );}}}

Tip:
1. [parsechildren (true, "text")] and toolboxdata labels must be used together. Otherwise, even if the default style is defined in toolboxdata, they cannot be displayed as double tags.
2. After the generated DLL file is added to the bin and toolbox, if it is a new project, you need to re-reference it to add the toolbox. Otherwise, it is a single tag for unknown reasons.
3. If [parsechildren (false, "text")] is false, text between tags is not displayed.

Viewstate:
Working principle: After processing the request, the page framework will collect the status of all the space trees and create an object graph. The viewstate dictionary is also in it, and then serialize the object graph into a string
An implicit variable is sent to the client. When the browser returns the webpage to the server, the page framework reads and parallelizes the hidden information, and then writes it to the viewstate Dictionary of the control one by one.

Types that can be stored: int32, Boolean, String, unit, and color can be stored in viewstate, and optimized for arrary, arrarylist, and hashtable objects of the above types. If not
The above types are converted into a string through the type converter. If no converter is available, the. NET Framework will convert the string in binary format, but the cost is very high.

Simple attributes: it can be easily converted to attributes of a text (string) expression.
Complex attributes: Non-numeric type and non-string reference type and set type.
Declarative Persistence: declarative syntax.

The rendering method in control:
Control calls three methods in sequence:
Each page has a control tree. To generate a control tree, the page creates an htmltext class instance, which encapsulates a response stream and then passes the object to the rendercontrol method,
This method verifies the visible value of the control to determine whether to display it. If it is to be displayed, the other two methods will be called in order, recursively create all controls with the value of "true.

        public void RenderControl(HtmlTextWriter writer)        {            if (Visible)            {                Render(writer);            }        }        protected virtual void Render(HtmlTextWriter writer)        {            RenderChildren(writer);        }        protected virtual void RenderChildren(HtmlTextWriter writer)        {            foreach (Control c in Controls)            {                c.RenderControl();            }        }

Control lifecycle: In my understanding, when the server control is submitted, it will return to the initial state and be restored after the server returns to the status.
1. instantiation: a page or another control instantiates it by calling its constructor. the Declaration syntax of the ASPX page creates a control tree. Subsequent steps will only happen when the control is added to this control tree.
2. Initialization: The oninit method is called by default for pages in the control tree and all controls.
3. Start to track view status: This phase occurs at the end of initialization. The page automatically calls the trackviewstate method of the Control. This method ensures that the attributes saved by viewstate are used at the end of the lifecycle.
Is saved in the view status of the control.
4. Load view status (only used for the return process): At this stage, the page framework automatically loads the viewstate field, which generally does not have to be implemented here.
5. Load the return data option (only used for the return process, optional): only when the control implements the ipostbackdatahandler interface and participates in the return data. The corresponding method loadpostdata.
6. load: before this stage, the control has returned to the final state of the previous lifecycle, corresponding to the overload method-onload. If you only want to implement the logic during initialization, then if (ispostback = false ){........}
7. trigger a modification event (only used for the callback process, optional): only when the control implements the ipostbackdatahandler interface and participates in the callback data. The status of the control is changed by sending back, for example, textbox.
8. triggering a return event (only used for the return process, optional): This event occurs only when the control implements the ipostbackdatahandler interface and participates in the return data. Through the raiscpostbackevent method that implements the interface,
Implement logic to map client events to server events. For example, button.
9. prerender: in this phase, by executing the onprerender method, any operations required before the control is generated.
10. save view State: If you want to customize State management, the saveviewstate method is reloaded in this phase and only valid for enableviewstate. After this phase, no changes to the control will be saved.
11. Generate (render): Reload the control render method or a rendering interface in the rendering method of webcontrol on the output stream.
12. unlond: in this phase, the page is cleared by calling page_unload. By default, the page and control in the control tree will trigger the unload event.
13. Release (dispose): Reload the dispose method to release the occupied controls.

Optimize event implementation: Use event properties to replace private domains
Because 1. The original example is: public event eventhandler click. the compiler will generate a private domain, and each event will be declared as a waste of memory. 2. add and remove methods in the Compiler
It will mark the thread security in the same bit, that is, when the delegate is added or deleted from the event, the thread will lock, which will increase the overhead of the system.
Implementation of event attributes:
1. Statement

// Private Static read-only event object Private Static readonly object eventclicknext = new object (); // event attribute public event eventhandler clicknext {Add {events. addhandler (eventclicknext, value);} remove {events. removehandler (eventclickprevious, value );}}

2. Use

/// <Summary> /// callback processing /// </Summary> /// <Param name = "eventargument"> </param> void ipostbackeventhandler. raisepostbackevent (string eventargument) {// eventargument receives the value of the variable hidden in page _ eventargument, // It is page. the second parameter in getpostbackeventreference, if (eventargument = "previous") {onpreviousclick (eventargs. empty);} else if (eventargument = "Next") {onnextclick (eventargs. empty); }}/// <summary> // The previous button window/ /// </Summary> /// <Param name = "eventargument"> </param> private void onnextclick (eventargs) {eventhandler nextclick = (eventhandler) events [eventclicknext]; if (nextclick! = NULL) {nextclick (this, eventargs );}}

Tip:
In readercontent and addattributestoreader, attribute/event methods can be added to controls, for example:

/// <Summary> /// Add the client style /// </Summary> /// <Param name = "Writer"> output stream </param> protected override void addattributestorender (htmltextwriter writer) {base. addattributestorender (writer); writer. addstyleattribute (htmltextwriterstyle. fontsize, "30"); writer. addattriover ("onmouseover", "this. style. textdecoration = 'underline'; status = '"+ statusbartext +"'; "); writer. addattriout ("onmouseout", "this. style. textdecoration = 'none'; status = '';", false );}

Generate on the client:

Onmouseover = "This. style. textdecoration = 'underline'; status = 'Good man: When the battlefield is dead, the horse is wrapped in a corpse, and the wife is beaten... '; ">

To directly execute the JS script in the control, add "javascript:", for example:

protected override void RenderContents(HtmlTextWriter writer)        {            //  CheckBox            writer.AddAttribute(HtmlTextWriterAttribute.Type, "checkbox");            writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "javascript:alert('AAAAA');");            writer.RenderBeginTag(HtmlTextWriterTag.Input);            writer.RenderEndTag();            //  TextBox            base.RenderContents(writer);        }

 

Complex attributes

Sub-attributes: for example, attributes in textbox
For example, the font attributes include font-size, font-color, font-name, and font is of the fontinfo type. This class has attributes such as size, color, and name.

Public class webcontrol: Control {// fontinfo is a class with attributes such as size, name, and color in the class. // enter the sub-attributes and serialize the sub-attributes to [designerserializationvisibility (designerserializationvisibility. content)] // flag whether the current attribute is modified [policyparentproperty (true)] public fontinfo font {}} // type converter, expandableobjectconverter -- collapse attribute [typeconverter (typeof (expandableobjectconverter)] public sealed class fontinfo {// tag the current attribute when changing [policyparentproperty (true)] public string name {}}

Internal Attributes: for example, headerstyle in the DataGrid

        <asp:DataGrid runat="server">            <HeaderStyle ForeColor=""/>        </asp:DataGrid>

Mandatory attribute identifier:
[Parsechildren (true)]: tells the page parser to parse the content in the control label into attributes.
[Persistchildren (false)]: tells the page parser to understand internal content as attributes rather than subcontrols.
This parameter can be omitted when the control inherits webcontrol.

// Serializable content [designerserializationvisibility (designerserializationvisibility. content)] // tag attribute change [policyparentproperty (true)] // Save the attribute permanently as an internal attribute [persistencemode (persistencemode. innerproperty)] Public Virtual tableitemstyle headerstyle {}

Canconvertfrom: converts the string type to xxxx.
Canconvertings: converts the string type to xxxx.
Convertfrom: Creates and returns the XXXX object instance based on the input string.
Convertor: Convert to string based on the received XXX parameter.

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.