Making Your ASP.NET Applications Interactive


Practically all Web-based business applications offer some form of interaction with their end users. That interaction may be in the form of hyperlinks , input fields, Submit buttons , or some type of navigation feature. Providing the right type of interaction for your Web site is important. Because interaction design affects your users' experience, you can easily see the connection that this topic has with the concern for adding value to your application's user interface.

Deciding among the many types of user interface interaction then becomes a developer's challenge. Among the many application design considerations, the following three points are arguably the most critical:

  • Making the application responsive

  • Providing user validation

  • Managing state and cache

In the sections that follow, I discuss the first two points in the preceding list. You will explore the role that the various .NET Framework control classes can play to help you achieve your design goals. I focus on the third point in the next chapter (Chapter 15).

Making the Application Responsive

If you are developing applications for an intranet community, you have already been greeted with the reality that end users do not like to wait. When you are building an application to serve the Internet community, your users' expectations will vary. For example, if a user is stuck with a slow dial-up connection, your application's lack of responsiveness is potentially hidden. However, just wait until your user switches to a lightning-fast Internet connection. At some point, the user may even get a broadband solution. When that happens, the true bottlenecks will be revealed.

Cross-Reference  

In Chapter 13, I acknowledged that several categories of controls existed that are all available to the ASP.NET developer. In that chapter, I also introduced the entire hierarchy of control classes that are derived from the System.Web.UI.Control base class.

Hopefully, you would have used the .NET Framework and ASP.NET to remove any processing latency found in your application. In every design decision, your choice of user interface control could impact the performance of your application. In other words, you need to carefully consider your needs before you freely drag and drop controls from the VS .NET IDE Toolbox.

Tip  

If you do consider the use of a client-side script, keep a couple of things in mind. Some users configure their Web browsers to have scripting capability disabled. Additionally, remember to refer back to the special Page methods that are available to help insert your script code into the .aspx file (see the section "The System.Web.UI.Page Class and Client-Side Scripts" in Chapter 13). Your choice to use or not to use a client-side script can result in a missed opportunity. The more proficient you become with the use of client-side scripts (e.g., JavaScript) for some of your client-side processing needs, the more choices you will have when developing for responsiveness.

Server Controls: To Use or Not to Use?

You might have the initial impression that you should use server controls at every opportunity. Actually, the exact opposite is true. You should use server controls only when you need to. If your Web Form user interface requires only simple display rendering, then strongly consider using an HTML tag. Generally speaking, try to avoid any unneeded trips (or rather, round-trips) to the Web server. The HTML tags alone will process on the client side, in the client's browser.

Note  

The namespaces System.Web.UI.HtmlControls and System.Web.UI.WebControls both provide server controls.

In cases when your user interface design includes the need to communicate with the server (e.g., you need to store or retrieve data from the database), you will want to use server controls. Additionally, if your business requirements call for the need to programmatically manipulate the attributes of your HTML tags, handle control events, or maintain view-state between postback events, server controls may be a good choice for you. [4]

Note  

In Chapter 13, I pointed out that the HTML tab in the VS .NET Toolbox displays HTML elements. Understand that if you take an HTML element and add the runat ="server" HTML attribute to that element, you have basically created a server control (an HTML server control). In contrast, the controls displayed on the Web Forms tab in the VS .NET Toolbox are already server controls (rather, Web server controls). Either way, as far as where the processing takes place, a server control is a server control.

HTML Server Controls vs. Web Server Controls

Assume that you already know that the classes found in the System.Web.UI.WebControls namespace offer a much richer object model than those offered by the System.Web.UI.HtmlControls namespace. You can then review a few other advantages that Web server controls offer over HTML server controls. For example, with Web server controls

  • The output (HTML, and possibly client script) generated by the server as part of the server process can be multibrowser compatible. Web server controls are able to render based on the capabilities of the browser.

  • The exposed object model (properties, methods, and so forth) against which you program is more consistent across controls. This leads to a more productive programming experience.

  • You can gain access to advanced controls such as the AdRotator, Calendar, DataGrid, and Repeater. Additionally, you gain access to advanced validation classes such as the ValidationSummary and BaseValidator classes.

  • There is a one-to-one mapping with the respective user interface elements. HTML server controls, on the other hand, are not consistent. In some cases they have a one-to-many mapping. In some of the cases where a one-to-one mapping does exist with HTML server controls, the name used in the Toolbox does not match the name of the resulting HTML element. [5]

To be fair, there is at least one advantage that HTML server controls offer: backward compatibility. Some will seek out the HTML controls to speed up an upgrade of their legacy Web applications (those built with classic ASP and Visual Basic 6.0). Otherwise, Web server controls are going to be your best bet ”that is, when you need a server control.

Controls, Controls, Controls, and More Controls

Among the common categories of HTML server controls and Web server controls, you have many choices ” certainly enough choices to get you off to a powerful developing start. All of them, in one way or another, seek to add value to your ASP.NET applications. Nevertheless, at some point you will come across the need to explore some of the other categories of controls.

You will find the following categories of controls briefly summarized in the sections that follow:

  • Literal controls

  • User controls

  • Composite controls

  • Custom controls

Literal Controls

ASP.NET uses these controls to store all the text-based data found on a Web page that does not require server processing. This would include all of the HTML elements and all other readable text. By accessing the object model of the literal control class, you can add and remove the text-based contents.

You will come across two "literal" controls ” literally ” that both inherit directly from the System.Web.UI.Control base class: System.Web.UI.LiteralControl and System.Web.UI.WebControls.Literal . ASP.NET itself creates the literal control class System.Web.UI.LiteralControl on your behalf (you can create it in your server-side code). You can find the System.Web.UI.WebControls.Literal literal control class in the Toolbox [6] (in the Web Forms tab).

By the way, you can view the Literal literal control as a lightweight alternative to the Label server control. On the other hand, you can instantiate the LiteralControl literal control in your server-side code and add it to the Page.Controls collection. Explicit use of either will depend on your needs.

User Controls

The UserControl class is also part of the System.Web.UI namespace. You work with user controls as you would a Page class. Notice that both the UserControl class and the Page class inherit from the System.Web.UI.TemplateControl class. You can add user controls to your project as text-based files that use a suffix of .ascx.

Use the UserControl class when you want to capture a Web page user interface that you want to reuse on multiple pages in the same project. You can place one or more user controls onto a Web page. It may help if you think of user controls as miniature pages. (See the upcoming sidebar titled "Looks Like a Page, Acts Like a Page, but They Called It a User Control.")

Composite Controls

When you take two or more existing server controls, inherit from their respective base classes, and assemble them together to create a new control, you have created a composite control. Microsoft has apparently used this approach to create some of their advanced server controls, for example, the LinkButton class. The LinkButton class appears to be the combination of a HyperLink control and a Button control, taking on characteristics of both controls.

Custom Controls

Similar to a composite control, a custom control is a control that you create yourself. Where the custom control differs is that rather than combining existing controls to create a new control, you typically just code your program logic to inherit from one targeted base control class. You then add your own logic to extend the capabilities found in the base class.

start sidebar
Looks Like a Page, Acts Like a Page, but They Called It a User Control

As you work with user controls (those .ascx files), you will discover that these objects look and act a lot like pages ”perhaps miniature pages. Why then, you may ask, did Microsoft decide to call them "user controls"? As much as I may take stabs at the various naming decisions made by Microsoft, there is usually a good reason behind their decisions.

There they sat, I imagine, around a big table (in a dark, smoke-filled room) talking about how the page is itself a control. Then, after much debate, they decided that it was reasonable to describe a miniature "page" that you create and design yourself to be a user control.

If they had invited me to the naming session meeting, I could have pointed out to them that it is not the user control that is misleadingly labeled; rather, the page is. I could have suggested to the Microsoft marketing folks that they could have appended the word "control" to the word "page" to create the term "page control." Having done so, then they could have either kept the term "user control" or gone with a term like "miniature page control." What do you think: "page control" and "miniature page control"?

You know, I wonder why Microsoft has not called me yet. Nevertheless, to help clear up the user control versus page confusion, keep the following points in mind:

  • Both the Page class ( System.Web.UI.Page ) and UserControl class ( System.Web.UI.UserControl ) inherit from the same base class
    ( System.Web.UI.TemplateControl ).

  • Pages can be requested directly via an HTTP request. User controls, on the other hand, are hosted on pages (or inside of other user controls). You pro- grammatically can make use of the properties and methods of user controls from your hosting page's server-side code.

  • Even though VS .NET offers a great "Add New Item" option for adding Web user controls to projects, you can create a user control manually.

  • You can convert an existing page to a user control by performing the following steps:

    1. Change the .aspx suffix extension to .ascx.

    2. Remove the <!DOCTYPE>, <HTML>, <BODY>, and <FORM> markup tags.

    3. Change the HTML @Page directive to be an HTML @Control directive.

    4. Change your code-behind logic to inherit System.Web.UI.UserControl instead of System.Web.UI.Page.

    5. Add a ClassName to the @Control directive for strong typing ability.

  • The UserControl object experiences page-level events (Page Init, Page Load, and so forth) similar to those experienced by the Page object.

  • With a couple of exceptions, using a user control is similar to using a Web server control (e.g., it includes the runat="server" attribute). Rather than dragging and dropping from the Toolbox, you can drag and drop from the Solution Explorer. When you use the drag-and-drop approach, an @Register directive is added to the "hosting" .aspx page file for you.

end sidebar
 

With such a varied offering of Control classes, the .NET Framework and ASP.NET have an answer to practically all of your user interface development needs. Basically, the Control classes offer opportunities for code reuse. Code reuse translates into increased developer productivity. Increased developer productivity means more time to concentrate on incorporating the right kind of value-added features to your user interface. The focus then returns to the user and the user's experience.

The following section continues that focus on the user in presenting the topic of validation. You will learn about yet another available choice for adding value to your user interface.

Providing User Validation

When you create an online application and you are designing the user interface, there is a thought process that takes place. There is that moment when you try to put yourself into the shoes of the end user. You may find yourself wondering, "If I were a user, what would I do in this scenario?"

Positioning yourself on the receiving end of that question, you make design considerations to support this anticipated end-user interaction. Experience then teaches you that the end user will not always "behave" as the user interface expects them to. So, you have learned to code defensively.

As a result, typical design considerations for online applications will include the need to validate the input received from the user. Although this is done on the end user's behalf, your user's perception of the validation logic is usually equivalent to the amount of value that has actually been added to the application. The type of interactive validation feedback delivered by your application's user interface easily influences the perceptions held by the end user.

Note  

Most mainframe CICS developers will recall enhancing CICS BMS map processing by adding user validation logic. Some of us used the infamous symbolic cursor positioning technique (moving a “1 to the length attribute) for the field being validated , whereas others relied on manipulating the field's extended attributes using IBM's standard DFHBMSCA copybook. Given the tools available, both approaches were acceptable means of providing feedback to the end- user community.

As luck would have it, ASP.NET provides two .NET Framework classes to assist with user validation: System.Web.UI.WebControls.BaseValidator and System.Web.UI.WebControls.ValidationSummary .

.NET Supports User Validation

I'll begin by briefly reviewing the .NET Framework classes that you can use for ASP.NET user validation. The System.Web.UI.WebControls.BaseValidator class serves as a base class from which five classes are derived: [7]

  • System.Web.UI.WebControls.CompareValidator: Compares a fixed value to the value present in a targeted input control.

  • System.Web.UI.WebControls.RangeValidator: Compares an Input control's value to that of two fixed values using the two fixed values as a range.

  • System.Web.UI.WebControls.CustomValidator: As the name of this class implies, you can create your own validating algorithm.

  • System.Web.UI.WebControls.RegularExpressionValidator: Compares the value of an Input control against a regular expression pattern. You have the flexibility to provide your own expression. Optionally, you can use the pre- packaged expressions provided by the Web Forms Designer.

  • System.Web.UI.WebControls.RequiredFieldValidator: Simply checks to verify that a nonblank value has been entered or that a selection has been made.

Each validation control can be "tied" to an Input control on the Web page. Typically, you use the validator control to write an error message or display an error indicator to alert the user. You can use the System.Web.UI.WebControls.ValidationSummary class (which inherits directly from the System.Web.UI.WebControls.WebControl class) to display a summary of validation errors produced by one or more of the actual validation controls.

To help with your understanding of the validation controls, I have included several of the validation server controls in a sample application. Let's take a look at some code.

Code Sample to Demonstrate User Validation

Using the ASP.NET Web Application project template in VS .NET, I created a new project. In the New Project window, I entered the name MyWebUseValidationCobol . As shown in Figure 14-6, you can find the validation server controls under the Web Forms tab in the VS .NET IDE Toolbox. I dragged and dropped a few of them onto the Web Form from the Toolbox (rather than typing in the HTML by hand).


Figure 14-6: The validation server controls as seen in the VS .NET IDE Toolbox

As shown in Figure 14-7, I placed a collection of controls onto the Web Form. I used the HTML tab in the Toolbox for my labels (HTML elements). I used the Web Forms tab in the Toolbox for the server controls (e.g., the TextBox controls, a Button control, and the validation controls).

click to expand
Figure 14-7: The sample application MyWebUseValidationCobol after all labels, TextBox controls, and validator controls have been added

After I placed all of the controls onto the Web Form, I proceeded to change the properties on each validator control. In the sample application, each validator control will be "associated" to the TextBox control that is immediately to the left of the validator control. I accomplished this "control association" by right-clicking each validator control and selecting Properties (see Figure 14-8) while in Design view. I then edited the ControlToValidate property and other properties.

click to expand
Figure 14-8: Updating the ControlToValidate property. Optionally, you can edit the HTML directly to modify each control's properties as needed.

As for the remaining properties, I will leave the color set to its default color (red) and use simple error messages. In your real-life development, you would typically create user-friendly messages. You could switch over to the HTML view and browse or edit the actual HTML statements.

I have included snippets of the generated HTML in Listings 14-4 through 14-6 for your viewing pleasure . To view this HTML in your ASP.NET Web application's WebForm1.aspx file, use the HTML tab.

The Forms Designer generated the HTML in Listing 14-4 as I was working with the TextBox server controls in Design view. Notice the use of the runat="server" attribute.

Listing 14-4: A Code Snippet from the MyWebUseValidationCobol Sample
start example
 . . . <asp:TextBox id="TextBox1" style="Z-INDEX: 102; LEFT: 213px;        POSITION: absolute; TOP: 64px"        runat="server" Width="60px" Height="37px"> </asp:TextBox> <asp:TextBox id="TextBox2" style="Z-INDEX: 103; LEFT: 202px;        POSITION: absolute; TOP: 118px"        runat="server" Width="59px" Height="37px"> </asp:TextBox> <asp:TextBox id="TextBox3" style="Z-INDEX: 105; LEFT: 287px;        POSITION: absolute; TOP: 177px"        runat="server" Width="73px"> </asp:TextBox> <asp:TextBox id="TextBox4" style="Z-INDEX: 106; LEFT: 269px;        POSITION: absolute; TOP: 222px"        runat="server" Width="76px" Height="33px"> </asp:TextBox> . . . 
end example
 

Listing 14-5 shows the HTML snippet generated on behalf of the Label that I dragged and dropped from the HTML tab of the Toolbox. Notice the absence of the runat="server" attribute.

Listing 14-5: The HTML Generated on Behalf of the Label
start example
 . . . <DIV style="DISPLAY: inline; Z-INDEX: 107; LEFT: 46px; WIDTH: 86px; POSITION:        absolute; TOP: 63px; HEIGHT: 32px"        ms_positioning="FlowLayout">CompareValidator </DIV> <DIV style="DISPLAY: inline; Z-INDEX: 112; LEFT: 51px; WIDTH: 86px; POSITION:        absolute; TOP: 121px; HEIGHT: 32px"        ms_positioning="FlowLayout">RangeValidator </DIV> <DIV style="DISPLAY: inline; Z-INDEX: 109; LEFT: 48px; WIDTH: 86px; POSITION:        absolute; TOP: 175px; HEIGHT: 32px"       ms_positioning="FlowLayout">RegularExpressionValidator </DIV> <DIV style="DISPLAY: inline; Z-INDEX: 110; LEFT: 48px; WIDTH: 86px; POSITION:        absolute; TOP: 223px; HEIGHT: 32px"       ms_positioning="FlowLayout">RequiredFieldValidator </DIV> <DIV style="DISPLAY: inline; Z-INDEX: 111; LEFT: 51px; WIDTH: 86px; POSITION:        absolute; TOP: 279px; HEIGHT: 32px"        ms_positioning="FlowLayout">SummaryValidator </DIV> . . . 
end example
 

Listing 14-6 shows a portion of the HTML generated as a result of placing each validation server control on the Web Form and using the Forms Designer to manipulate the Properties window. Notice that the runat="server" attribute is included to indicate that these controls are server controls.

Listing 14-6: The HTML Generated As a Result of Placing Each Validation Server Control on the Web Form
start example
 . . . <asp:CompareValidator id="CompareValidator1"        style="Z-INDEX: 113; LEFT: 299px; POSITION: absolute; TOP: 72px"        runat="server" ErrorMessage="Value not Equal to 9"        ControlToValidate="TextBox1" ValueToCompare="9"> </asp:CompareValidator> <asp:RangeValidator id="RangeValidator1"        style="Z-INDEX: 114; LEFT: 303px; POSITION: absolute; TOP: 128px"        runat="server" ErrorMessage="Value is higher than 10"        ControlToValidate="TextBox2" MaximumValue="10"> </asp:RangeValidator> <asp:RegularExpressionValidator id="RegularExpressionValidator1"        style="Z-INDEX: 116; LEFT: 385px; POSITION: absolute; TOP: 173px"        runat="server" ErrorMessage="Value not Valid Phone Number format"        ControlToValidate="TextBox3"        ValidationExpression="((\(\d{3}\) ?)(\d{3}-))?\d{3}-\d{4}"> </asp:RegularExpressionValidator> <asp:RequiredFieldValidator id="RequiredFieldValidator1"        style="Z-INDEX: 117; LEFT: 391px; POSITION: absolute; TOP: 226px"        runat="server" ErrorMessage="Must Enter a Value"        ControlToValidate="TextBox4"> </asp:RequiredFieldValidator> <asp:ValidationSummary id="ValidationSummary1"        style="Z-INDEX: 118; LEFT: 240px; POSITION: absolute; TOP: 280px"        runat="server" Width="312px" Height="147px"> </asp:ValidationSummary> . . . 
end example
 

For this sample application, the only time I actually touched the HTML code was when I performed some minor "code formatting" to create an optimal copy-and-paste page display. However, nothing is stopping anyone from going the reverse order (i.e., typing the HTML in and then viewing the result in Design view). In fact, you can drag and drop HTML elements from the Toolbox (HTML tab) directly into the HTML code. That is, if you are interested in minimizing your typing effort.

Let's now run the sample application (press F5 with the project open in the VS .NET IDE). After you enter a few test values and click the Button to post the Form, all expected results are produced. You will notice (see Figure 14-9) that each validator control is showing the appropriate error message. Additionally, the SummaryValidator control is showing a compiled summary of all of the error messages. How nice!

click to expand
Figure 14-9: Executing the sample application ASP.NET application (MyWebUseValidationCobol) to demonstrate the use of validation controls

Using the .NET Framework and ASP.NET, it is extremely easy to add professionally styled validation to your user interface. With the right touch, this will be a welcomed change for your Web application. Just think how impressed your end users will be with the obvious effort toward adding true value to your user interface.

Note  

Obviously, in a real-life application you would add additional logic. Perhaps you would include business logic to capture and possibly store the data once it is validated. Given what you have learned about ADO.NET, adding a database connection to SQL Server should not present a big challenge for you. Other enhancements might include the addition of Web Form pages or other TextBox and Label controls. You could use the additional controls or pages to provide a "redisplay" of the validated data. Providing some type of confirmation to the user generally communicates that the data has been validated, received, and saved.

Isn't it amazing what you can do with ASP.NET? What you can now do in minutes with ASP.NET would have certainly taken much, much longer using mainframe tools to build a similar CICS application. Just think what your project managers will say when they find out that .NET fully supports a rapid application development (RAD) approach that enables you to create a complete data entry form with validation in less than an hour . Perhaps your future project timelines can be shortened a bit.

Note  

The sample application MyWebUseValidationCobol was created using the COBOL .NET ASP.NET Web Application project template. The ASP.NET Web Forms Designer basically built the HTML code (click, click, click). Given that, the resulting HTML would look virtually identical if I had chosen to use the VB .NET Web Application project template (instead of the COBOL .NET template). That being the case, I will leave it up to you to experiment with the VB .NET project template as you extend your training experience.

Throughout this section, I discussed adding value for your end user as he or she interacts with your application. I used user validation as an example scenario where interaction is common between your end user and your application. There are other scenarios. As you come across them, I am sure that the .NET Framework, ASP.NET, and VS .NET will serve your needs and then some.

In the next section you will take a high-level look at some possible opportunities for adding value made available through XML Web services. The ASP.NET XML Web service platform is no stranger to the need for value-added development. You will continue focusing on adding value, but with a different type of interface: the application interface.

[4] This depends slightly on your willingness and ability to use client-side scripting. It's wise to consider learning JavaScript. This will enhance your Web development choices.

[5] I suppose that Microsoft did this to make the HTML tab more similar to the Web Forms tab. They failed. With the HTML tab, the Label icon in the Toolbox is a <div> HTML tag. With the Web Forms tab, the Label icon in the Toolbox is an <asp:Label> HTML tag.

[6] If you dig deep enough you will find that the visual version of the literal control (the one located in the Toolbox) gets translated and stored along with other HTML/text into the ASP.NET-generated System.Web.UI.LiteralControl class during runtime.

[7] The System.Web.UI.WebControls.CompareValidator and System.Web.UI.WebControls.RangeValidator classes derive from the System.Web.UI.WebControls.BaseCompareValidator. The System.Web.UI.WebControls.BaseCompareValidator class is derived from the System.Web.UI.WebControls.BaseValidator class.




COBOL and Visual Basic on .NET
COBOL and Visual Basic on .NET: A Guide for the Reformed Mainframe Programmer
ISBN: 1590590481
EAN: 2147483647
Year: 2003
Pages: 204

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net