Create custom controls for ASP. net2.0 server controls

Source: Internet
Author: User
Tags control label ftp site
This article from: http://tech.ddvip.com/2007-05/117993461125583.html
Source code used by the instance: http://file.ddvip.com/2007_05/1179934567_ddvip_5087.rar

Summary

This article describes how to create a simple custom Server Control. With this content, you will understand the basic methods for creating and testing custom server controls using Visual Studio 2005.

Note: This article is based on ASP. NET 2.0 technology. The sample application is developed using Visual Studio 2005.

Create a simple custom Server Control

The process of creating a custom server control includes:

(1) create a web site application for testing;

(2) Add a web control library project to create a site application;

(3) Compile, compile, and test custom server controls.

(1) create a web site application for testing

There are many ways to create a web site application using Visual Studio 2005, for example, create in local file system, create in IIS support, create in FTP site, create in remote site, etc. However, in any case, developers should first open Visual Studio 2005, and then click "new website..." under the "file" menu. A dialog box such as 1 is displayed.

 

Figure 1 new website dialog box

Figure 1 shows the new website dialog box. In this dialog box, developers need to select the creation template, location, and programming language. 1. The example is created using an ASP. NET website template, a file system, and a C # programming language. After you click "OK", Visual Studio 2005 creates a folder named test1 under local D: apptest. All application files are stored in folders. By default, the test1 folder contains an empty app_data folder for storing application data files. It also contains a default. aspx and default. aspx. CS files.

After the preceding steps, a web site application is created. This web site will be used to test the Web custom Server Control created.

(2) Add a custom Server Control Project

After creating a web site application, developers must add a custom server control project, that is, the web control library project, to the current site project. The solution is to open the web site application and click "add" sub-item "New Project" in the "file" menu ". Visual Studio 2005 displays the 2 dialog box.

 

Figure 2 Add a new project dialog box

Figure 2 shows the Add project dialog box. The dialog box consists of three settings: project type, template, name, and location.

There is a tree list on the left side of the dialog box, including various project types. To create a web control library project, select "Windows" as the child node of the "Visual C #" node ". At this point, the installed template corresponding to the subnode appears on the right side of the dialog box, including Windows applications, class libraries, and Web Control libraries. Developers should select "Web control library. Finally, you need to set the name and location of the web control library project. To facilitate management, we recommend that you store the web control library project and test site project in the same folder. Therefore, in this example, set the name to "hellomycontrol" and the location to D: apptest est1. After you click the "OK" button, Visual Studio 2005 automatically creates a hellomycontrol to store files related to the web control library in the D: apptest est1 directory. In addition, Visual Studio 2005's "Solution Explorer" displays 3.

 

Figure 3 solution Resource Manager

As shown in 3, Solution Explorer contains two projects. One is the web site project created previously, and the other is the web control library project named hellomycontrol, which includes a webcustomcontrol1.cs file by default. Now you can write, compile, and test custom server controls.

(3) Write, compile, and test custom server controls

The custom Server Control welcomelabel is easy to implement. Similar to a standard label control. The welcomelabel control inherits from system. Web. UI. webcontrols. webcontrol, which defines a string-type text attribute. When the control is running, the text that combines the text property value and the current user name is displayed. For example, if you set the text property value to "hello", "Hello, XX!" is displayed! ". Developers can use the welcomelabel control as part of the site Welcome Page.

The implementation code of the welcomelabel control is included in the webcustomcontrol1.cs file. The source code of this file is as follows.

Using system;
Using system. Collections. Generic;
Using system. Security. permissions;
Using system. componentmodel;
Using system. text;
Using system. Web;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Namespace hellomycontrol
{
[
Aspnethostingpermission (securityaction. Demand, level = aspnethostingpermissionlevel. Minimal ),
Aspnethostingpermission (securityaction. inheritancedemand, level = aspnethostingpermissionlevel. Minimal ),
Defaultproperty ("text "),
Toolboxdata ("<{0}: welcomelabel runat =" server "> </{0}: welcomelabel> ")
]
Public class welcomelabel: webcontrol
{
// Implement the text attribute
[
Bindable (true), category ("appearance"), defaultvalue (""), description ("text content."), localizable (true)
]
Public Virtual string text
{
Get
{
String S = (string) viewstate ["text"];
Return (S = NULL )? String. Empty: S;
}
Set
{
Viewstate ["text"] = value;
}
}
// Rewrite the rendercontents Method
Protected override void rendercontents (htmltextwriter writer)
{
// Encode the text property value and write it into the input stream
Writer. writeencodedtext (text );
// Determine whether the Web request is valid. If valid, set the content and write it to the output stream.
If (context! = NULL)
{
// Obtain the current user name
String S = context. User. Identity. Name;
// If the current user name is not blank, analyze the user name and write it to the output stream in the specified format
If (s! = NULL & S! = String. Empty)
{
String [] split = S. Split ('\');
Int n = split. Length-1;
If (split [N]! = String. Empty)
{
Writer. Write (",");
Writer. Write (split [N]);
}
}
}
Writer. Write ("! ");
}
}
}

 

Control Base class for Code Description:

If the server control needs to render the user interface (UI) element or any other client-visible element, it should be derived from system. Web. UI. webcontrols. webcontrol (or a derived class. If the control is to be rendered with invisible elements (such as hidden elements or meta elements) in the client browser, the control should be derived from system. Web. UI. Control. In this example, the user interface elements need to be displayed. Therefore, the custom server control class welcomelabel inherits from the webcontrol base class. Because the webcontrol class is derived from control, the welcomelabel control automatically inherits the Member objects provided by the base class. Most of these objects are related to the presentation of user interface elements, for example, font, forecolor, backcolor, width, and so on. In addition, the welcomelabel control also inherits from webcontrol. Therefore, it automatically implements the theme and skin functions added by ASP. NET 2.0. In fact, because the welcomelabel control and ASP. the built-in Server Control label of NET 2.0 has many similarities. Therefore, from the perspective of function implementation, the best way is to make the welcomelabel control class inherit from the label class. However, this example inherits from the webcontrol base class to describe how to define attributes and define attribute metadata.

Text attribute of Code Description:

As shown in the source code above, welcomelabel implements a text attribute and uses the view status to store the attribute value. Use view status to save the text value of the sending-back interval. Each time a message is sent back, the page is re-created and the view status is restored. If the text value is not stored in the view state, the value is set to its default empty upon each sending. The viewstate property is inherited from webcontrol and is a dictionary that stores data values. You can enter and retrieve values by using the string key. In this example, "text" is used as the key. The items in the dictionary are converted to objects by type, and must be forcibly converted to attribute type.

Code Description-rendercontents method:

Generally, when you derive a control from webcontrol and render a single element, you should override the rendercontents method (instead of the render method) to render the content in the control tag. After the start tag of the Rendering Control and Its style attributes is displayed, the render method of webcontrol calls rendercontents. If you override the render method to write content, the control will lose the style rendering logic generated in the render method of webcontrol.

In the source code, the welcomelabel control overrides the inherited rendercontents method to present the text attribute and other content. The parameter passed into the rendercontents method is an htmltextwriter-type object, which is a utility class for methods with rendering tags and other HTML (and HTML variable) tags. Readers may have noticed that welcomelabel continuously calls the write method of the htmltextwriter object, instead of first executing String concatenation and then calling the write method. This method can improve the control performance. String concatenation requires time and memory to create strings and then write them into the stream.

Metadata attribute tag for Code Description:

As shown in the code above, the following three metadata property tags are included before the welcomelabel class declaration.

(1) aspnethostingpermissionattribute

It is a secure attribute for code access. This attribute enables the JIT compiler to check whether the code linked to welcomelabel has the aspnethostingpermission permission. All common ASP. NET classes use this attribute tag. The aspnethostingpermissionattribute should be applied to the control to perform security checks on some trusted callers.

(2) defaultpropertyattribute

It is a design-time attribute that specifies the default property of the control ). In the visualization designer, when a page developer clicks a control on the design surface, the property browser usually highlights this default property.

(3) toolboxdataattribute

It is used to specify the format string of the element. If you double-click the control in the toolbox or drag it from the toolbox to the design surface, the string becomes the control tag. For welcomelabel, this string creates this element:

<aspSample:WelcomeLabel runat="server"> </aspSample:WelcomeLabel>

 

In addition, the following metadata attributes are defined during the implementation of attribute text.

(1) bindableattribute (specified as true or false)

This metadata attribute can be used to specify whether binding an attribute to data makes sense to the visualization designer. For example, in visualstudio2005, if the property is marked as Bindable (true), the property can be displayed in the "Data Binding" dialog box. If the attribute is not marked with this attribute, the property browser determines that the value is Bindable (false ).

(2) categoryattribute

This metadata attribute is used to specify how to classify attributes in the visualization designer's property browser. For example, when page developers use the classification view of the property browser, category ("appearance") informs the property browser to display the property in the "appearance" category. You can specify the string parameter based on the existing category in the property browser or create your own category.

(3) descriptionattribute

This metadata property is used to specify a brief description of the property. In visualstudio2005, the property browser displays the description of the selected property at the bottom of the "properties" window.

(4) defaultvalueattribute

This metadata property is used to specify the default value of the property. This value should be the same as the default value returned from the property accessor (getter. In visualstudio2005, defaultvalueattribute allows page developers to call a shortcut menu in the "properties" window and click "reset" to reset the property value to its default value.

(5) localizableattribute (set to true or false)

This metadata attribute is used to specify whether the localization attribute is meaningful to the visualization designer. When an attribute is marked as localizable (true), the visualization designer will include this attribute when serializing the localized resource. When you poll a property that can be localized for the control, the designer saves the property value to a resource file or other localization source that is not specific to the region.

After compiling the source code of the welcomelabel control, compile and test the customized Server Control. To achieve this goal, developers need to reference the web control library project output in the test site, and write the relevant code to test the server control.

The method for implementing project reference in the web control library on the web site is relatively simple. First, right-click the Web Site Project name in Solution Explorer, and select "add reference..." in the pop-up menu. The window shown in 4 is displayed automatically.

 

 

Figure 4 Add reference dialog box

4. The add reference window contains five tabs, including a tab named "project. Click it to publish it to the list that contains the hellomycontrol project created above. Select this item and click "OK" to complete the project reference.

After the project reference is completed, Visual Studio 2005 automatically adds a bin folder to the Web site project and contains the hellomycontrol. dll and hellomycontrol. PDB files. The former is a control assembly, while the latter stores debugging and project status information. In this way, the Web site can smoothly use the output of the hellomycontrol project. The source code of the default. aspx file created to test the welcomelabel control is shown below.

<% @ Page Language = "C #" autoeventwireup = "true" codefile = "default. aspx. cs" inherits = "_ default" %>
<% @ Register tagprefix = "self" namespace = "hellomycontrol" assembly = "hellomycontrol" %>
<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> Create a simple custom Server Control </title>
</Head>
<Body>
<Form ID = "form1" runat = "server">
<Div>
<Self: welcomelabel text = "hello" id = "welcomelabel1" runat = "server" backcolor = "wheat" forecolor = "saddlebrown"/>
</Div>
</Form>
</Body>
</Html>

 

 

As shown in the bold code above, the page first uses the @ register command to introduce the welcomelabel control, and then uses <self: welcomelabel> to mark the location of the control and attribute settings. In the <self: welcomelabel> tag, the text, backcolor, and forecolor attributes are mainly set. They are used to define the text content, background color, and foreground color of the control, respectively.

5. The page for executing default. aspx is displayed.

 

Figure 5 sample application

Summary

This article uses a simple example to illustrate the basic process of implementing custom server controls. Through this content, you may have discovered that there is a big difference between creating custom server controls and creating common web applications. These differences are mainly reflected in the creation mode and the technology used. In subsequent articles, we will discuss in detail the use of ASP. NET 2.0 technology to create custom server controls.

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.