荔园在线

荔园之美,在春之萌芽,在夏之绽放,在秋之收获,在冬之沉淀

[回到开始] [上一篇][下一篇]


发信人: Jobs (温少), 信区: Visual
标  题: Building Web Controls for ASP+
发信站: BBS 荔园晨风站 (Sun Sep 17 01:05:55 2000), 转信



       Building Web Controls for ASP+

It has been just a little over three short years since Microsoft
released ASP 0.9 to the web development community revolutionizing web
application design with it's simple paradigm of script code embedded
within an HTML page. We are now just a few months away from a major
upgrade to the ASP architecture (downloadable in alpha form today. For
an overview of the new features in ASP+ view the article by Alex Homer
on this site and visit http://msdn.microsoft.com/net). The goal of this
article is not to teach the basics of ASP+ but to focus on one exciting
aspect of ASP+, the ability to author custom server side web controls
that when processed by the web server return standard HTML to the
browser.

The Benefits of Server Side Web Controls
Before we examine the mechanics of authoring a custom server side ASP+
web control we should examine their benefits.

A server side web control is represented within the ASP+ page as a
custom tag with attributes. For example the Microsoft intrinsic custom
calendar control would be included on a page by inserting the tag
<asp:Calendar runat="server">. This simplicity allows content authors to
use server side web controls without having to worry about Program ID's
or CLSID's.
Server side web controls can encapsulate functionality whose code and
complexity is hidden from the control user thus preventing unintentional
modification, which was always a potential problem with ASP's Design
Time Controls.
Cross browser compatible pages can be developed since these controls can
be written to return only HTML, DHTML or XML to the browser.

Properties of the control are accessible to server side code without
having to utilize the Request and Response objects simplifying data
validation code. For example to access the values entered into text
fields to calculate a loan repayment we could simply write the following
code:

LoanCalculator.vb
<%@ Page Language="vb" %>

<html>
   <head>
   <script Runat="server">
      Sub Calculate(src As Object,e As EventArgs)
         Dim irate As Double
         Dim npayments As Double
         Dim lvalue As Double
         irate = ((Cdbl(txtAPR.Text))/100)/12
         npayments = Cdbl(txtPeriod.Text)
         lvalue = -(Cdbl(txtAmount.Text))
         txtPayment.Text = Cstr(Pmt(irate,npayments,lvalue))
      End sub
  </script>

  </head>
  <body>

   <form method="POST" runat="server">
     Loan Amount ($):<asp:TextBox id="txtAmount" Runat="server"/><br>
     Period (months):<asp:TextBox id="txtPeriod" Runat="server"/><br>
     APR (%):    <asp:TextBox id="txtAPR" Runat="server"/><br>
     Payment:    <asp:TextBox id="txtPayment" Runat="server"/><br>
<asp:Button id="btnCalculate" Text="Calculate" OnClick="Calculate"
Runat="server"/><br>
   </form>
  </body>
</html>

The code listed above would be contained in a file with an .aspx
extension and would be invoked from a browser in the same manner that an
ASP page is invoked.

Note that in the Calculate subroutine, we are using server side code to
access the Text property of the four text boxes directly instead of
accessing the POST 'ed data via the Response object, as would
traditionally be the case in ASP script code. This is possible because
we are using server side text box controls. A similar calculation could
have been performed with client script but if the calculation were a
sensitive business rule then that business rule would be exposed in the
page source at the browser. Another important issue to note in this code
is the data type sensitivity of all the new .NET languages.

The Basics of Authoring a Server Side Web Control
We can author server side web controls in any .NET compatible language.
Typical choices might be VB.NET or C#. The following code illustrates
some basic server side web control code written in VB.NET. This simple
control will render the web servers' date and time at the browser.

ServerDate.vb
Imports System
Imports System.Web.UI

Namespace ASPToday

   Public Class ServerDate
      Inherits System.Web.UI.Control

        Private Sub InitializeComponent()

      End Sub

         Overrides Public Sub Render(ByVal output As
System.Web.UI.HtmlTextWriter)
         'Note ability below to Dim and assign variable on same line
         Dim datenow As Date = Now()
         output.Write("Server date and time is: " + CStr(datenow))
      End Sub

   End Class

End Namespace

If we dissect this example line by line we can learn the fundamental
aspects of authoring a server side web control with VB.NET.

The first two lines contain Imports statements specifying the namespaces
containing the classes we are going to use in our control. These
statements can be omitted if we prefix every class used with its
namespace, but if we import the namespace then we can use just the
classname unless there would still be ambiguity. There is definite
similarity between this, the import statement in Java, and the concept
of setting a Type Library reference in VB6.

The next line makes our class a member of the ASPToday namespace. This
provides a mechanism by which users of our control class can
differentiate it from any identically named control class. Java
programmers will recognize a similarity between namespaces and Java
packages and VB6 programmers can think of namespaces as roughly the
equivalent of the Project Name set when developing a COM component used
to specify the first half of the component Prog ID.

Next we define the name of our control class, in this case ServerDate.
This is going to be the tag name used to instantiate the control on an
ASP+ page. We also identify via the Inherits keyword that our class
subclasses the System.Web.UI.Control class. Since we "imported" the
System.UI.Web namespace we could have just used the Control classname
here instead. It really is a matter of preference as to which mechanism
you use although I personally think prefixing the namespace results in
more readable and maintainable code. Remember then that when we subclass
another class we inherit the parent classes methods and properties and
can then choose to override some of those methods if we wish. If you
examine the .NET SDK documentation for the System.Web.UI.Control class
you will find some member methods marked with the "final" modifier -
these methods cannot be overridden.

In the case of a server side web control we will almost certainly
override the Render method. The Render method produces the output of the
control whenever it is encountered on an ASP+ page. The Render method
receives a parameter of type System.Web.UI.HtmlTextWriter that gives the
ability to write data out to the browser. In this case we are simply
writing out the system date and time and of course since this code will
be executed at the web server this would be that system's date and time.
If you do not have the Preview edition of Visual Studio .NET you will
need to use the vbc.exe command line compiler to compile the .vb file
into a .dll, this can then be placed in the same directory as the .aspx
file or in the Web Applications \bin directory. One of the benefits of
the new .NET framework is that component registration is not required.


Using a Custom Server Side Web Control
The code below would form the contened environment, and that VBScript has been
replaced with VB.NET
(or any other .NET compatible language).

The second line indicates that we shall be using classes located in the
ASPToday namespace. Our ServerDate class is a member of this namespace.

The third line allows us to associate a short alias with a namespace. In
this case the alias aspt will be associated with the ASPToday namespace.
This alias is referred to as a TagPrefix.

The remainder of the code is straightforward HTML except for the line
that invokes our custom server side web control:

<aspt:ServerDate Runat="server"/>

The TagPrefix and classname identify the control to be used and the
Runat="server" attribute indicates that the code behind the control
should execute on the web servode:


ServerDateMod.vb
Imports System
Imports System.Web.UI
Imports System.Web.UI.Control
Imports System.ComponentModel

Namespace ASPToday

   Public Class ServerDateMod
      Inherits System.Web.UI.Control

      Dim _DateFormat As String

      Property <DefaultValue("mm,dd,yyyy")> [DateFormat]() As String
         Get
            Return _DateFormat
         End Get

         Set
            _DateFormat = Value
         End Set
      End Property

           Overrides Public Sub Render(ByVal output As
System.Web.UI.HtmlTextWriter)
        output.Write(Format(Now(), _DateFormat))
     End Sub

   End Class

End Namespace

The key differences to be noted in this example compared to the previous
example are the assignment of a member variable _DateFormatt="MM/dd/yyyy"
Runat="server" />
  </body>
</html>

Subclassing an Existing Control
One of the benefits of working with an Object Oriented API such as the
.NET framework and with an Objected Oriented language such as VB.NET is
that we can inherit functionality from existing classes and then
override or extend that functionality. The .NET framework includes a
number of predefined web control classes that we can inherit from and
build upon. In this final example we shall look at authoring a web
control          Return _DateFormat
        End Get

        Set
          _DateFormat = Value
        End Set
      End Property

      Overrides Public Sub PreRender()
        Me.Text = Format(Now(), _DateFormat)
      End Sub

   End Class

End Namespace

In both prior examples (ServerDate and ServerDateMod) our class
inherited it's functionality from System.Web.UI.Control which provides a
great deal of basic functionality but we were entirely responsible for
producing the "visual" output from the control by overriding the Render
method. Had we not overridden the Render method our control would have
produced no visible output. In the example above we are inheriting
functionality from a class (System.Web.UI.WebControls.TextBox), which
already has a functt="server" />

  </body>
</html>

This time however the server's date would be displayed in a text box. It
is important to remember that not only do we inherit the functionality
of the TextBox class but we inherit all of its properties and attributes
our own server side web controls which
when placed on an ASP+ page will render output to the browser. For
maximum cross browser compatibility we should restrict the output
produced by our control to HTML 3.2 and basic client side JavaScript.
One of the most attractive features of these controls is their ability
to encapsulate complex processing logic and hide this from the control
user. For example a control could be written to connect to a database,
retrieve a set of data and render it as an HTML table. All the control
user would have to do is include the control on their ASP+ page and
perhaps set a couple of attributes to identify the database, and the
table in the database without having to know a single line of ADO+ code.



--


   我想超越这平凡的生活,注定我暂时漂泊!

   我无法停止我内心的狂热,对未来的执着!

※ 来源:·BBS 荔园晨风站 bbs.szu.edu.cn·[FROM: 192.168.18.211]


[回到开始] [上一篇][下一篇]

荔园在线首页 友情链接:深圳大学 深大招生 荔园晨风BBS S-Term软件 网络书店