Support for ASP.NET controls
G. Andrew Duthie
Graymad Enterprises, Inc
October 2003
Applicable to: Microsoft® ASP.NET Microsoft Visual Studio® .NET Microsoft .NET Framework
Summary: Learn how to build controls supported by Microsoft Visual Studio .NET design, this support allows controls to be easy to use as built-in controls in Microsoft ASP.NET.
Download DesigntimeSupportsample.msi. (Note that in the sample file, the programmer's annotation is used in English. In this article, it is translated into Chinese to facilitate the reader's understanding.)
This paper adapted from the second edition of "ASBNET IN A Nutshell" (ISBN: 0596001169), including G. Andrew Duthie and Matthew Macdonald, published by O'Reilly & Associates, Inc. 2003.
table of Contents
Introduction The type of BLOG control sample supported by the design, support the summary code list when adding design
Introduction
Microsoft® ASP.NET provides developers with a new tool for web development: the most powerful new tools: server controls. The server control enables developers to develop a fast response speed and powerful web application in a short period of time, and the time required to create similar applications in a typical ASP is similar.
ASP.NET Server Controls can provide production efficiency, one of the key reasons is that it provides a wealth of design support for server controls in the Microsoft Visual Studio® .NET development environment. Developers can drag and drop the server control from the Visual Studio .Net toolbox to the page, access their properties via the Properties window, then use in the Visual Studio HTML editor and the categories of the ASP.NET page. Microsoft IntelliSense® statement completes the function. These design-time features bring fast application development (RAD) tools for Web development, and these tools have been used by Microsoft Visual Basic® developers for many years.
ASP.NET also enables developers to further improve production efficiency by creating a custom server control to encapsulate a large number of user interface specific code (eg, login or registration form). Although developers have begun to realize the importance of developing custom controls, many people may not realize that they can also use the powerful features supported by Visual Studio design in the control to enable these controls to enable these controls to built-in controls in ASP.NET. It is easy to use. This article describes the types of design supported by Microsoft .NET Framework and Visual Studio .NET and describes how to build this supported control to developers.
Types supported during design
There are five different design support for server controls in Visual Studio .NET. They are:
Introduction to the property browser support toolbox in the category of the code, supports the IntelliSense in the HTML Editor supports the property browser in the HTML editor.
These design are provided by several different mechanisms. IntelliSense in the category of code is enabled by IDE, IDE reads metadata for your control to determine the properties and methods provided by the control and its type and parameters. To enable IntelliSense in an in-code class, you only need to write and compile your control, and then put its assembly to the bin subdirectories of the application that uses the control. The property browser in the Visual Studio .NET Editor Design view is provided with the following two ways: associate this type with an attribute and / or put the metadata characteristics with the attribute. Add metadata characteristics (referred to as feature) to your code, used to identify the category of the property, provide attribute description, and specify the preferred editor when needed. Some types of properties (such as system.drawing.color) are automatically mapped to the corresponding editor in Visual Studio .NET.
The IntelliSense and Property Browser in the HTML view of Visual Studio .NET supports by using an XSD schema, this architecture is used to describe the type associated with the control, which uses the first choice for text modified controls called Visual Studio comments. Editor and other preferred options.
Finally, you can support drag and drop the control from the Visual Studio .Net toolbox from the Visual Studio .NET toolbox by combining features and custom bitmaps with specific properties.
Blog control example
Controls for explaining the design of the design in Visual Studio .NET are called "BLOG controls" as shown in List 1 at the end of this article. This control provides a simple Web log feature utilizing XML as a storage medium. Web logs are often called Blog, which is actually a Web page for regular observation reports or comments on other issues concerning everyday life, world abstraction, current affairs politics or people. The blog entry is added via a web browser.
The Blog control is very simple, it uses the control combination to provide output to the browser. In the combination control, the CreateChildControls method (automatically called by ASP.NET "will be rewritten, using this method, we can create controls that make up the custom control UI and add them to the control collection of the control. In addition, the control also contains logic for displaying and adding Blog and creating a such file when the XML Blog stores does not exist. Several public properties of the control require developers to set up when design, including the control to redirect the URL of the page when adding a new Blog, an email address, control mode (display or addition) associated with the new blog And the color of the separation line between each blog entry. Figure 1 shows the BLOG control being running. The Add Blog is available from the ASP.NET hyperlink control, which is independent of the Blog control. The code of BlogClient.aspx is shown in Listing 2. BLOGCLIENT.ASPX's CodeBehind class, such as list 3, provides logic that changes the Blog mode when you click on Add Blog.
Figure 1: BLOG control at runtime
Figure 2 shows the appearance of the basic BLOG control at the time of design. Please note that although attributes are listed, it is not classified.
Figure 2: BLOG control at design
Support when adding design
Although it is very simple to use the Blog control on the web form page, it is not very intuitive. For example, if there is no relevant document, people who use the blog control cannot know the valid value of the Mode property can only be Display or Add. If the relevant information of the Add mode is not explicitly telling the developers of the control, they are hard to discover and use this model.
For developers using Visual Studio .NET (or other IDE supporting IntelliSense), this problem can be solved by adding design for controls. This can be achieved by integrated using the methods described above. In the challenge for supporting design-based support for custom server controls, part of the reason is from the diversity of methods required to fully support design in custom controls. The simplest, no additional encoding is the IntelliSense statement completion method in the category of the code, as shown in Figure 3, this method is suitable for BlogClient.aspx.vb. Figure 3: IntelliSense in the class with code
Unfortunately, the auto support of the statement completion is not extended to the editing web form page design view or HTML view, and Visual Studio does not provide you can view and edit attributes in the property browser without providing additional controls. Built-in support. More complicated is to support IntelliSense in the Properties Browser and Design view of the Web Form Editor, you need to use a method to support IntelliSense in the HTML view of the editor, you need another method.
To support properties browsing in the design view, how to tell Visual Studio .NET how to process properties by characteristics. To support statements in the HTML view, you need to generate a custom XSD architecture to describe the types in the control. We will discuss these two methods below.
Design view and metadata characteristics
Visual Studio .NET provides a rich support for dynamic controls and modifications using drag and drop technology, and also provides tools such as property browsers and related designers (such as color pickers). Support for these tools is provided through a range of features, you can add these features to your control. These features are used to tell Visual Studio IDE to display the properties of the control in the Properties Browser, the types belonging to the property, and which designer to set the value of the properties.
For the control version that will be supported, we will make a copy of the control file blog.vb and name it blog_dt.vb, then modify on a copy file. This can generate the design of the control, and retain the original control for comparison.
To support editing the AddRedirect property in the Properties Browser, you should add the following features before the property process, as shown in the following code segment:
Category ("behavior"), _ DESCRIPTION ("After successfully submitting new blog entries," & _ "He you should redirect" & _ "URL of the page"), _ Editor ("System.Web.ui.Design.urledge", _ Gettype (UITYPEEDITOR)> _ _ Public property addredirect () AS STRING 'Attribute process code End Property These feature declarations allow attributes to display properties in the property browser, providing attribute settings (when the property is sorted by category), providing the property description and telling the Visual Studio .NET to use the Urleditor class edit attribute, as shown in Figure 4 . Figure 4: Attribute support in the design view The characteristic syntax described here is suitable for Visual Basic .NET. In Visual Basic .NET, features are declared by the following syntax: In C #, the characteristics use the following form: [AttributeName (Attribute (AttributeParams)] Visual Basic .NET Requirements Features Declarations Its modified members are in the same row, so it is usually better to follow a Visual Basic line with a Visual Basic row in the characteristics to improve readability: Public membername () In C # and Visual Basic, you can declare multiple features in a pair of [] or <> brackets, and the characteristics are separated between commas. In Visual Basic .NET, if they appear in different rows, you must use the Visual Basic row receipt. It is located in the same statement. Add toolbox support In addition to setting the properties of the attribute level, you can also set the characteristics of certain classes and assemblies. For example, you can use the assembly level of tagprefix to specify the tag prefix, which is used by any controls included in the assembly. After that, when you add an instance of the control from the Visual Studio toolbox, Visual Studio .NET will automatically insert this tag prefix. The following code snippet shows the syntax of the TagPrefix feature. This feature should be placed within the class module of the control, but should be outside the class and namespace declaration (note that in the Visual Basic .NET project, the namespace is defined in the project level, so you don't have to worry about how The assembly characteristics are placed outside the namespace declaration). In the following characteristics, the first parameter of the TagPrefix feature is the namespace of the control, and the second parameter is the text you want to use for tag prefix. To integrate control into the Visual Studio .NET environment, you should add ToolBoxData feature (this feature to tell Visual Studio .NET) Add to the class that controls the control from the toolbox inserted from the toolbox: Public class blog_dt Inherits Panel Implements inamingcontainer 'Control implementation END CLASS When you insert the control from the toolbox to the page, the tag prefix specified by the TagPrefix feature will insert the {0} placeholder, while other text will be inserted as it is. You can also provide your own custom icon to display in the toolbox. To this end, you need to create a bitmap of 16 x 16 pixel size (the pixels in the lower left use transparent color), which is the same as the class containing the control (ie classname.bmp). Use the Add Existing Item command to add this bitmap to the project, then use the property browser to set its build Action to Embedded Resource, as shown in Figure 5. Figure 5: Setting Build Action (Create Action) After the compilation is completed, the control will automatically insert the @Register directive, tag prefix, and tag name when adding controls from the toolbox to a page, and displays a custom icon in the toolbox, as shown in Figure 6. Indicated. To add a control to the Visual Studio .Net toolbox, you should complete the following steps: In the Design view, select the Web Forms tab of the Visual Studio .NET toolbox. Right-click anywhere on this tab and select Add / REMOVE ITEMS (Customize Toolbox [Custom Toolbox]) in Visual Studio .NET 2002. Select the .NET Framework Components tab, and then click Browse. Browse to the location where the compiled control assembly is located, select it and click Open. Click OK. Figure 6: Custom control in the toolbox Add the control to the toolbox, you can add it to the web form page by double-clicking on the control or dragging it from the toolbox to the Web Form page. Whenever case, Visual Studio .NET automatically inserts the correct @register directive (including the assembly level-based feature setting tagprefix), and will use the tag name specified in the ToolboxData property to generate a set of tags. Add designer As mentioned earlier, the Blog control does not have any visual interface in the design view of the web form editor. This makes it difficult to choose the control on the page, which is more difficult to understand the appearance of the control at runtime. In order to solve this problem, we can add designer support to make the HTML when designing the blog controls close to the runtime. Note that you can also generate designers that can be output when the control is completely reproduced, but this is quite complex and exceeds the scope of this article. All server control designers are derived from class system.web.ui.design.controlDesigner, which provides a large number of ways, and you can rewrite these methods to provide design-time rendering for your control. The following code returns a getDesigntimehtml method to return a simple HTML displayed when designing. Note that this example shows the entire designer class of the Blog control, you can simply add it to the existing blog_dt.vb class file. Public Class BlogDesigner Inherits ControlDesigner Public overrides function getdesigntimehtml () AS STRING Return " blog h1>
"
END FUNCTION
END CLASS
To bind the designer to the Blog_dt class, we use Designer features, as shown in the following segment. Note that this code has also added a Description feature that describes the control function.
"Web log / new entry from XML files."), _ Designer ("BlogControl.blogdesigner), _ ToolboxData ("<{0}: blog_dt runat = server> {0}: blog_dt>")> _public class blog_dt Inherits Panel Implements inamingcontainer As you can see, the BlogDesigner class is very simple, but it adds a lot of content to the control in the design on the Web Form page, as shown in Figure 7. Figure 7: Rendering when adding design Listing 4 shows the code of the blog control, which has been updated using features to enable support for control design in the design view and property browser. Note that this example adds a plurality of USING instructions to import the namespaces you need to support our features and designer classes. This new list also adds an enumeration for the MODE attribute value. HTML view support: custom architecture and Visual Studio comments Although the features described above help us provide design-time support for the Blog control, an important issue is missing here: IntelliSense support for tags and features in the HTML view of the Web Form Editor. This is a great negligence for more comfortable developers who think that in the HTML environment is more comfortable than in the environment of "seeing", this is a more comfortable developer. Because the HTML view of the web form editor determines which elements and features on the web form page, we need to provide an XSD architecture that describes the BLOG control and its support. You can also add a comment in this architecture to tell Visual Studio .NET's related information and what we want element. Listing 5 includes part of the BLOG control-specific XSD architecture. The actual architecture file (available in the sample code of this article) also includes a panel control (Blog_dt control is the type definition of the type definition that is derived) and other required features and type definitions. These definitions are replicated from the ASP.xsd architecture file created for built-in ASP.NET server controls. Note that the ASP.xsd architecture file should not be modified directly, and only the required types and features should be copied into your custom architecture file. Although this seems to be redundant, if you edit the asp.xsd directly, the file will be overwritten when you install the .NET Framework or service package, and your custom input will be lost. In Listing 5, pay attention to the targetNamespace and XMLNs feature on the root architectural elements, which are used to define an XML namespace for the control's architecture. The values of TargetNameSpace and XMLNS feature will also be used in the web form page to "bind" the architecture. Note that list 5 uses VS: Builder annotations to tell Visual Studio .NET to use the URL generator for the AddRedirect feature, and use a color generator for the SeparatorColor feature. The VS: Builder Comment is one of the comments that can be used to modify the architecture. Table 1 lists the most common notes. Table 1: Common Visual Studio .NET Comments Note Use effective value vs: absolutePositioning on the root To allow Visual Studio .NET to read your custom architecture, you need to add an XMLNS feature to the
Note that this code uses a BlogControl prefix with XMLNS feature to indicate that the architecture applies to controls with the BlogControl tag prefix. This can be called by the prefix that is set to use the TagPrefix feature (for instructions for this feature, please see "Metadata Characteristics" section in the article). The value of the XMLNS feature should be the same as the value of the targetnamespace feature defined in the architecture root element.
After the XMLNS feature is bound to the architecture, you can type an open "<" character and make the Blog control to be completed by the statement, as shown in Figure 8. At this point, you should also obtain a statement that has been defined attributes, including a valid value of the MODE property, and the generator specified by the annotation in the XSD file.
Figure 8: Formation completed in the HTML view
summary
This article describes the design of the ASP.NET server control in Visual Studio .NET, also describes how developers use this support function in their own custom controls. Although it supports relatively concise while adding design in the control, it is necessary to make full use of these features, but you need to master a variety of different techniques. A particularly lacking knowledge is how to bind a custom XSD architecture to the page. When writing this article, there is no built-in support for the XMLNs feature required to connect the page and the control XSD architecture. So, you also need to manually add this feature. I hope that the future Visual Studio .NET version can automate this process. The sample code in this article contains a Visual Studio .NET project that is supported by the BLOG control base and design, and includes a client project that describes how to use each control. To run the BlogControlClient project, you need to create a virtual directory BLogControlClient in IIS, then mapped to your hard drive to save the BlogControlClient project folder.
Thanks to the Microsoft Visual Studio .Net team's Rob Caron, he gave great help during the creation and binding process I wrote a custom XSD architecture.
about the author
G. Andrew Duthie is the founder and person in charge of Graymad Enterprises, Inc. (English), providing training and consulting services for Microsoft Web development technology. Since Active Server Pages, Andrew has been engaged in the development of multi-layer web applications. He has written a lot of books on ASP.NET, including: "Microsoft ASNET Step By Step", "Microsoft ASP.NET Programming With Microsoft Visual Basic" and "ASP.NET IN A Nutshell". Andrew often presents a speech in some major activities, including "Software Development", "DEV-Connections Family of Conferences", "Microsoft Developer Days", and "VSLive!". He also published a speech on the .NET user group as an International .NET Association (English) Speaker's Bureau. You can learn more about Andrew from our company's Web Site Graymad Enterprises, Inc. (English).
This paper is based on the second edition of "ASBNET INA NUTSHELL" (ISBN: 0596001169), which includes G. Andrew Duthie and Matthew MacDonald, published by O'Reilly & Associates, Inc. 2003.
Code list
Listing 1: blog.vb
'Supports Color Structure
Imports system.drawing
'Support StreamWriter type
Imports system.io
Imports System.Web.ui
'Support Using HTML controls
Imports System.Web.ui.htmlControls
'Support using web controls
Imports System.Web.ui.WebControls
Public Class Blog
Inherits Panel
Implements inamingcontainer
Protected Blogds as DataSetProtected Titletb As TextBox
Protected BlogText As TextBox
Private _addredirect as string
Private_email as string
Private _mode as string
Private _separatorcolor as color = color.black
Public property addredirect () AS STRING
Get
Return Me._AddRedirect
END GET
Set (byval value as string)
Me._addredirect = value
End set
End Property
Public property email () AS STRING
Get
Return me._email
END GET
Set (byval value as string)
Me._email = Value
End set
End Property
Public property mode () AS STRING
Get
Return me._mode
END GET
Set (byval value as string)
ME._MODE = VALUE
End set
End Property
Public property separatorcolor () As Color
Get
Return me._separatorcolor
END GET
SET (ByVal Value As Color)
Me._separatorcolor = value
End set
End Property
Protected Overrides Sub Oninit (Byval E As Eventargs)
LoadData ()
MyBase.oninit (e)
End Sub
Protected Overrides Sub CreateChildControls ()
IF not me._mode = "add" then
DisplayBlogs ()
Else
Newblog ()
END IF
End Sub
Protected sub loadingdata ()
Blogds = new dataset ()
Try
Blogds.readxml (page.server.mappath ("blog.xml"))
Catch fnfex as filenotfoundexception
CreateBlankfile ()
LoadData ()
END TRY
End Sub
Protected sub displayblogs ()
Dim Blogdate as datetime
DIM CurrentDate as datetime = new datetime ()
Dim blogrows as datartment = _
Blogds.tables (0) .ROWS
Dim BlogDR As DataRow
For Each Blogdr in BlogRows
DIM bdate as string = blogdr ("date"). Tostring ()
Blogdate = new datetime _
(Convert.Toint32 (bdate.substring (4, 4)), _
Convert.TOINT32 (Bdate.substring (0, 2)), _
Convert.TOINT32 (BDATE.SUBSTRING (2, 2)))))
IF not currentdate = blogdate then
DIM Tempdate as label = new label () tempdate.text = blogdate.tolongdateString ()
Tempdate.font.size = fontunit.large
Tempdate.font.bold = true
Me.Controls.add (Tempdate)
Me.Controls.add_
(New LiteralControl ("> "))
Currentdate = blogdate
END IF
Dim Anchor as htmlanchor = new htmlanchor ()
Anchor.name = "#" & blogdr ("anchorid"). TOSTRING ()
Me.Controls.add (anchor)
DIM TITLE As label = new label ()
Title.text = blogdr ("title"). Tostring ()
Title.font.size = fontunit.larger
Title.font.bold = true
Me.Controls.add (title)
Me.Controls.add (New LitralControl ("
"))))))
Dim BlogText as LiteralControl = _
New LiteralControl ("
Blogdr ("text"). Tostring () & " div>")
Me.Controls.add (BlogText)
Me.Controls.add (New LitralControl))))))
Dim email as hyperlink = new hyperlink ()
Email.navigateURL = "MAILTO:" & _
Blogdr ("email"). Tostring ()
Email.text = "e-mail me"
Me.Controls.add (email)
Me.Controls.add (New LiteralControl ("|"))
Dim Anchorlink As HyperLink = New HyperLink ()
Anchorlink.naviGateURL = _
Page.Request.url.tostring () & "#" & _
Blogdr ("anchorid"). Tostring ()
Anchorlink.Text = "LINK"
Me.Controls.add (Anchorlink)
Me.Controls.add (new _
LiteralControl ("
NEXT
End Sub
Protected subnewblog ()
DIM TITLE As label = new label ()
Title.text = "CREATE New Blog"
Title.font.size = fontunit.largertitle.font.bold = TRUE
Me.Controls.add (title)
Me.Controls.add (New LiteralControl ("BRA)))
Dim Titlelabel as label = new label ()
Titlelabel.Text = "Title:"
Titlelabel.Font.Bold = true
Me.Controls.add (Titlelabel)
Titletb = new textbox ()
Me.Controls.add (Titletb)
Me.Controls.add (New LitralControl ("")))
Dim BlogTextLabel as label = new label ()
BlogTextLabel.Text = "Text:"
BlogtextLabel.Font.Bold = true
Me.Controls.add (BlogTextLabel)
Blogtext = new textbox ()
Blogtext.textMode = TextBoxMode.multiline
BlogText.Rows = 10
BlogText.columns = 40
Me.Controls.add (BlogText)
Me.Controls.add (New LitralControl ("")))
DIM Submit as button = new button ()
Submit.text = "Submit"
AddHandler Submit.click, Addressof Me.Submit_Click
Me.Controls.add (SUBMIT)
End Sub
Protected Sub Submit_Click (Byval Sender As Object, _
ByVal e as evenTargs)
EnsureChildControls ()
Addblog ()
End Sub
Protected sub addblog ()
Dim Newblogdr As DataRow
Newblogdr = blogds.tables (0) .newrow ()
Newblogdr ("Date") = formatdate (datetime.today)
Newblogdr ("Title") = Titletb.Text
Newblogdr ("text") = blogText.text
Newblogdr ("anchorid") = guid.newguid (). Tostring ()
Newblogdr ("email") = _Email
Blogds.tables (0) .rows.insertat (newblogdr, 0)
Blogds.writexml (page.server.mappath ("blog.xml"))
Page.Response.Redirect (_ADDREDIRECT)
End Sub
Protected Function Formatdate (Byval Dt As DateTime)
As string
DIM RETSTRING AS STRING
Retstring = string.format ("{0: D2}", DT.MONTH)
Retstring & = string.format ("{0: D2}", DT.day) RetString & = String.Format ("{0: D2}", Dt.Year)
Return Retstring
END FUNCTION
Public Sub CreateBlankfile ()
Dim newxml as streamwriter = _
File.createtext (page.server.mappath ("blog.xml"))
Newxml.writeline ("
Newxml.writeline_
("")
Newxml.writeline ("
NEWXML.WRITELINE ("
"The creation date of the blog ->")
Newxml.writeline ("
Formatdate (DateTime.today) & " date>")
Newxml.writeline_
("
NEWXML.WRITELINE ("
"Should Contain The Blog Text, Including Any" & _
Desired HTML Tags -> ")
Newxml.writeline ("
"INDICES That The file blog.xml was not" & _
"Found.a Default Version of this File Has" & _
"Been Created for you.you can modify the" & _
"FIELDS in this file as desired.if you set" & _
"The Blog Control to Add Mode (Add The" & _
"Attribute Mode = 'Add' to the Control'S" & _
"Declaration), The Control Will" & _
"Automatic Or Populate the XML File WHEN" & _
"You Submit the form. text>")
Newxml.writeline ("
"Will Be Autopopulate by the Control ->")
Newxml.writeline ("
NEWXML.WRITELINE ("")
Newxml.writeline ("
"Valid Email Address emil>")
NEWXML.WRITELINE (" blog>")
NEWXML.WRITELINE (" blogs>")
NEWXML.CLOSE ()
End Sub
END CLASS
Listing 2: BlogClient.aspx
<% @ Register tagprefix = "cc1" namespace = "blogControl"
AskEMBLY = "BlogControl"%>
<% @ Page language = "vb" autoeventwireup = "false"
Codebehind = "blogclient.aspx.vb"
Inherits = "BlogControlClient.webform1"%>
Transitional // en ">
hEAD>