0% found this document useful (0 votes)
66 views80 pages

Module 7: Building Web Applications

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views80 pages

Module 7: Building Web Applications

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Module 7: Building Web

Applications

Contents

Overview 1
Introduction to ASP.NET 2
Creating Web Form Applications 16
Demonstration: Creating Web Forms 30
Lab 7.1: Creating the Customer
Logon Web Forms 31
Building Web Services 42
Demonstration: Creating a Web Service 50
Using Web Services 51
Demonstration: Using a Web Service 57
Multimedia: How Web Services Work 58
Lab 7.2: Creating and Using the
CustomerService Web Service 60
Review 71
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, place or event is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part
of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted
in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or
for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

© 2002 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BizTalk, FrontPage, IntelliSense, JScript,
Microsoft Press, Outlook, PowerPoint, Visio, Visual Basic, Visual C++, Visual C#, Visual
InterDev, Visual J#, Visual SourceSafe, Visual Studio, and Windows Media are either registered
trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module 7: Building Web Applications iii

Instructor Notes
Presentation: This module provides students with the knowledge needed to create Web-based
120 Minutes applications.
Labs: In the first lab, students will create several Web Forms for logging on or
105 Minutes registering as a customer of the Cargo system. In the second lab, students will
create a Web Service that provides information about customers and allows the
addition of new customers to the system. The labs use predefined classes that
replicate data storage and retrieval.
After completing this module, students will be able to:
 Explain and take advantage of the benefits of ASP.NET and its various
libraries in application development.
 Create Web Form applications.
 Use HTML server controls and Web server controls.
 Create Web Services.
 Use Web Services from a browser or from another client application.

Materials and Preparation


This lesson provides the materials and preparation tasks that you need to teach
this module.

Required Materials
To teach this module, you need the following materials:
 Microsoft® PowerPoint® file 2373B_07.ppt
 Module 7, “Building Web Applications”
 Lab 7.1, Creating the Customer LogOn Web Forms
 Lab 7.2, Creating and Using the CustomerService Web Service
 Multimedia presentation, How Web Services Work, file 2373_How Web
Services Work.htm on the Student Materials compact disc

Preparation Tasks
To prepare for this module, you should:
 Read all of the materials for this module.
 Read the instructor notes and the margin notes for the module.
 Practice the demonstrations.
 Complete the labs.
iv Module 7: Building Web Applications

Demonstrations
This section provides demonstration procedures that will not fit in the margin
notes or are not appropriate for the student notes.
These demonstrations show the creation of simple Web Forms and simple Web
Services. If students have previous experience with ASP.NET Beta 1, consider
using validation controls in the Web Forms demonstration, and analyze the
client-side proxy files generated in the Using a Web Service demonstration.

Creating Web Forms


 To create the application
1. Open Microsoft Visual Studio® .NET.
2. Create a new ASP.NET Web Application project called LogonDemo in the
following Web directory:
http://localhost/2373/DemoCode/Mod07/LogonDemo/Starter/LogonDemo
3. Examine the Web.config file, and locate the authentication and
sessionState sections, pointing out the default values.

 To create the logon page


1. Open the WebForm1.aspx file in the design window.
2. In the Properties window, change the Document.pageLayout property to
FlowLayout.
3. Click the top left corner of the Web Form to create a heading, and in the
Block Format list on the Formatting toolbar, click Heading 1.
4. Add the text Welcome to the Logon Page to the page.
5. Using the Web Forms toolbox, add the following controls to the page, and
then set their properties as shown in the table.
Control type Property Value

TextBox (ID) txtFullName


TextBox (ID) txtEmail
TextBox (ID) txtPassword
TextMode Password
TextBox (ID) txtConfirm
TextMode Password
Button (ID) btnSubmit
Text Submit

6. To describe the purpose of each TextBox, add Normal style text above each
box, as shown in the following table.
TextBox Describing text

txtFullName Please enter your full name:


txtEmail Please enter your e-mail address:
txtPassword Please enter a password:
txtConfirm Please confirm the password:
Module 7: Building Web Applications v

7. Reposition the controls on your page as shown in the following illustration:

8. Examine the WebForm1.aspx file in the HTML view of the HTML


Designer, and describe the @ Page directive at the top of the page and the
HTML syntax within the page, including the control declarations.
9. In the design window, double-click btnSubmit to display the Code Editor,
and then explain the code in this module.
10. Add the following code to the btnSubmit_Click event handler, and then
explain the uses of the session variable and Response object.
Session("FullName") = txtFullName.Text
Response.Redirect("Welcome.aspx")

 To create the welcome page


1. Add another Web Form named Welcome.aspx to the project, add a single
Label control to it, and then set the (ID) property of the control to
lblWelcome.
2. Locate the Page_Load event handler in the Welcome.aspx.vb code module,
and add the following code:
lblWelcome.Text = "Welcome " & Session("FullName")

 To test the application


1. Run the application.
2. Type values in the text boxes, and then click Submit, viewing the results.
3. Quit the application.
4. Quit Visual Studio .NET.
vi Module 7: Building Web Applications

Creating a Web Service


 To create the application
1. Open Visual Studio .NET.
2. Create a new ASP.NET Web Service project in the following directory:
http://localhost/2373/DemoCode/Mod07/Services/Starter/Services
3. Using the Solution Explorer, delete Service1.asmx from the project. Add a
new Web Service item named QueryUsers.asmx.

 To create the GetUserName method


1. Open the QueryUsers.asmx.vb code module and add the following method:
<WebMethod( )> Public Function GetUserName( _
ByVal Email As String) As String
Return Email & ": Corresponding name on database"
End Function

2. Build the project, but do not run it.

 To test the Web Service


1. Right-click QueryUsers.asmx in Solution Explorer, and then click View in
Browser.
2. Click the GetUserName hyperlink and examine the HTML description
page. Enter an e-mail address in the input field for the GetUserName
method and click Invoke and view the Extensible Markup Language (XML)
results. Close this window.
3. Return to the first HTML description page, and click the Service
Description link to view the Web Services Description Language (WSDL)
document. Describe the document, briefly pointing out the basic sections of
the document before closing the window.

 To add descriptions to the Web Service and methods


1. In the QueryUsers.asmx.vb code module, modify the class definition to read
as follows:
<WebService(Namespace := "http://tempuri.org/", _
Description:="This service deals with user
information.")> Public Class QueryUsers

2. Locate the GetUserName method and modify the WebMethod attribute to


read as follows:
<WebMethod(Description:="Looks up a name based on the
e-mail.")>

3. To display the new HTML description page, rebuild the project and view
QueryUsers.asmx in the browser as before, pointing out the new
descriptions.
4. Close Visual Studio .NET.
Module 7: Building Web Applications vii

Delivery Tip Using a Web Service


This demonstration uses the
Web Service from the
 To test a Web Service with Internet Explorer
previous demonstration. If 1. Open Microsoft Internet Explorer.
you have not created the
web service, you must open 2. Type the following Uniform Resource Locator (URL) into the Address bar
Services.sln in install of Internet Explorer to demonstrate how browsers can submit a call which
folder\DemoCode\Mod07\ includes parameters to the Web Service methods:
Services\Solution and build http://localhost/2373/DemoCode/Mod07/Services/
the project. Then you can
Starter/Services/QueryUsers.asmx/GetUserName?Email=Jeff
substitute
“Services/Solution” for 3. Close Internet Explorer.
“Services/Starter/Services”
in the folder paths in this
demonstration.  To use a Web Service from a rich client
1. Open the RichClient.sln solution in the install folder\DemoCode\
Mod07\RichClient\Starter folder.
2. View the form design for frmUserDetails.vb. The purpose of the form is to
retrieve user details based on an e-mail address by means of the Web
Service.
3. On the Project menu, click Add Web Reference, and then type in the
following URL:
http://localhost/2373/DemoCode/Mod07/Services/
Starter/Services/QueryUsers.asmx
4. Click the Go to button, and then click Add Reference.
5. Locate the localhost Web reference in Solution Explorer, and rename it
UserServices.
6. In Solution Explorer, click Show All Files and view the Reference.vb file
Delivery Tip that acts as the proxy class for the client application. Explain that this file
In step 6, do not go into too
much detail regarding the
allows client code to be written as if it were normal Visual Basic .NET
proxy class file. Students code, allowing the use of Microsoft IntelliSense® and early binding.
can explore this individually 7. Create the btnSubmit_Click event handler in frmUserDetails.vb, and add
if they want to. the following code, explaining the purpose of each line.
Dim qu As New UserServices.QueryUsers( )
MessageBox.Show(qu.GetUserName(txtEmail.Text), _
"Result from the Service")
qu = Nothing

 To test the client application


1. Run the project.
2. Click Submit to view the results of the call to the Web Service.
3. Exit the form and the Visual Studio .NET integrated development
environment (IDE).
viii Module 7: Building Web Applications

Multimedia Presentation
This section provides multimedia presentation procedures that do not fit in the
margin notes or are not appropriate for the student notes.

How Web Services Work


 To show the multimedia presentation
• To show this presentation, double-click the animation icon on the slide for
the Multimedia: How Web Services Work topic.

Module Strategy
Use the following strategy to present this module:
 Introduction to ASP.NET
This lesson introduces ASP.NET and shows some of the benefits over
Active Server Pages (ASP). Emphasize that this is primarily an overview
lesson; most of these topics are addressed in more detail throughout the
module.
For more in-depth information about ASP.NET, refer students to Course
2063A, Introduction to ASP.NET.
 Creating Web Form Applications
This lesson shows how to create Web Forms applications. Students examine
the structure of a Web Form, including some of the important directives that
are used within the page definition. Compare HTML controls to Web server
controls, and highlight some individual controls for discussion, such as the
validation controls and the AdRotator control. Finally, introduce students
to event handling for ASP.NET server controls.
 Building Web Services
This lesson describes the open standards and protocols that enable Web
Services, in addition to how to create Web Services and their methods by
using the WebMethod attribute. The student notes show how to include
method and Web Service descriptions within these attributes. Point these
lessons out to students. Use the instructor-led demonstration to show
students how to create a simple Web Service and its discovery document.
 Using Web Services
In this lesson, you examine how to use a Web Service from a client,
including the process of discovery and the exploration of service
descriptions. Explain to students how they can access this information from
a browser and from a rich client such as Visual Basic .NET. Use the
demonstration and animation at the end of the module to give students
examples of possible scenarios for Web Services, and elicit suggestions for
other Web Services from the students.
Module 7: Building Web Applications 1

Overview
Topic Objective
To provide an overview of
the module topics and
objectives.  Introduction to ASP.NET
Lead-in  Creating Web Form Applications
In this module, you will learn
about building Web  Building Web Services
applications with
Visual Basic .NET.  Using Web Services

*****************************ILLEGAL FOR NON-TRAINER USE******************************


Using Microsoft® Visual Basic® .NET and ASP.NET, you can create a new
generation of dynamic, powerful Web applications.
After completing this module, you will be able to:
Delivery Tip
Developers who are familiar  Explain and take advantage of the benefits of ASP.NET and its various
with the ASP model will find libraries in application development.
the transition to ASP.NET to
be fairly easy.  Create Web Form applications.
 Use HTML server controls and Web server controls.
 Create Web Services.
 Use Web Services from a browser or from another client application.
2 Module 7: Building Web Applications

 Introduction to ASP.NET
Topic Objective
To provide an overview of
the topics covered in this
lesson.  Overview of ASP.NET
Lead-in  Using Response and Request Objects
ASP.NET introduces many
improvements upon  Maintaining Client-Side State
traditional approaches to
Web development.  Maintaining Server-Side State
 Managing an ASP.NET Application
 Overview of ASP.NET Security
 Using Global Events with Global.asax

*****************************ILLEGAL FOR NON-TRAINER USE******************************


ASP.NET introduces many improvements upon traditional approaches to Web
Delivery Tip development. Its extensive framework of classes enables you to rapidly create
This lesson provides an
overview of ASP.NET and
powerful, scalable, manageable, and secure Internet applications.
its benefits without going After you complete this lesson, you will be able to:
into much detail about any
one topic. Most items are  Describe the advantages that ASP.NET provides over its predecessor,
covered in more depth later Active Server Pages (ASP).
in the module.
 Use two important ASP.NET objects: Request and Response.
 Use the various client-side and server-side state facilities that are available
in ASP.NET applications.
 Explain basic concepts in managing and securing ASP.NET applications.
 Use the Global.asax application file for global events.
Module 7: Building Web Applications 3

Overview of ASP.NET
Topic Objective  Code behind development
To discuss the key features
provided by ASP.NET.  Intuitive approach to development similar to Windows Forms
Lead-in  Code can be compiled using any .NET-compatible language
ASP.NET introduces many
 Significant performance improvement
significant enhancements to
ASP.  ASP.NET pages run side-by-side with ASP pages
 Files with the .aspx extension run side-by-side with current
ASP applications on IIS
 Automatic support for multiple browsers
 Rich DHTML, HTML 3.2, and small devices
 ASP.NET namespaces provide rich functionality
 Built-in support for Web Services

*****************************ILLEGAL FOR NON-TRAINER USE******************************


For several years, Web developers have used ASP to produce Internet
applications containing dynamic content. ASP.NET is the evolution of this
technology, and it provides many benefits to Web developers:
 Code-behind support
ASP.NET uses an event-driven programming model familiar to
Visual Basic and ASP developers. Web Forms use the drag-and-drop style
of page creation. You can modify code behind the controls on Web Forms
in the same way that you do on Visual Basic forms. This code resides in a
separate file to separate the content from the code.
 Code can be compiled from any Microsoft .NET-compatible language
You can create your ASP.NET applications by using any of the .NET
compatible languages, including Visual Basic .NET, C#, and Microsoft
JScript®. While ASP contains scripts that are interpreted when you execute
a page, ASP.NET code is compiled rather than interpreted. This allows early
binding, strong typing, and just-in-time (JIT) compilation to native code.
These factors greatly improve the performance of ASP.NET applications,
particularly when you have an increased number of clients.
 ASP.NET pages run side-by-side with ASP pages
ASP.NET uses the .aspx file extension to allow ASP.NET pages to run side-
by-side with existing ASP pages on Internet Information Services (IIS). The
ASP.NET runtime will only process files with .aspx extensions; .asp files
will be processed with the original ASP engine. You can easily migrate
existing .asp files to .aspx files without making many changes to the code.
4 Module 7: Building Web Applications

 Automatic support for multiple browsers


ASP.NET applications have the ability to render information differently to
suit the capabilities of different browsers. You can create your application in
the same way for both a simple browser that only supports HTML 3.2 and
for an enhanced browser that supports dynamic HTML (DHTML), such as
Microsoft Internet Explorer 4.0. You can even use Visual Basic .NET to
create Web applications that will run on small devices such as Handheld
PCs because of the ability of the ASP.NET Web server controls to render
themselves appropriately for each client browser.
 ASP.NET namespaces provide rich functionality
The ASP.NET framework provides several namespaces that allow you to
use powerful built-in features, such as the ability to communicate between
browser and server, to increase application performance by caching
information, and to fully secure a Web site. The framework provides Web
Service capabilities to allow access to your system services, and provides
many predefined controls for use on Web Forms.
 Built-in support for Web Services
ASP.NET includes built-in support for Web Services, enabling developers
to build loosely coupled applications that use Simple Object Access
Protocol (SOAP) for application-to-application communication.
Module 7: Building Web Applications 5

Using Response and Request Objects


Topic Objective
To explain how to use the
Response and Request  The System.Web namespace provides common Web
objects. functionality
Lead-in
The Response and  Requesting information from the client
Request objects provide the
ability to communicate
 Request object
between the server and the
browser. Dim
Dim strValue
strValue As
As String
String == Request.Form("txtInput")
Request.Form("txtInput")

 Sending information to the client


 Response object
Response.Write("<H2>The
Response.Write("<H2>The date
date is:
is: "" && Now.Date
Now.Date && "</H2>")
"</H2>")

*****************************ILLEGAL FOR NON-TRAINER USE******************************


You can use the System.Web namespace to access many of the classes that
provide the base functionality of ASP.NET applications. Many of these classes
are similar to those used by developers in ASP applications and have been
enhanced in ASP.NET.
You can use the Response and Request objects, provided by the System.Web
namespace, to communicate between the client browser and the server
computer. Both of these objects provide new properties and methods for their
equivalent objects in ASP.

Requesting Information from the Client Browser


You can request information such as query string, cookie, and form values from
a client browser by using the HttpRequest class. An instance of this class is
available by means of the Request property of the current Web Form.
The following example shows how to request the value currently stored in a
text box on a Web Form:
Dim strValue As String = Request.Form("txtInput")

Sending Information to the Client Browser


You can send information such as cookie values, HTML output, and browser
redirection to the client browser by using the HttpResponse class. An instance
of this class is available by means of the Response property of the current Web
Form.
The following example uses the Response object to display the current date:
Response.Write("<H2>The date is: " & Now.Date & "</H2>")
6 Module 7: Building Web Applications

Maintaining Client-Side State


Topic Objective
To explain how to use the
available client-side state  Maintaining control state across multiple requests
facilities in the ASP.NET
framework.  Set EnableViewState property of control
Lead-in  Use the StateBag class to store extra data
You can use several
approaches to maintain ViewState("TempData")
ViewState("TempData") == 25
25
client-side state in
ASP.NET applications.  Send data to client as hidden string
<input
<input type="hidden"
type="hidden" name="__VIEWSTATE"
name="__VIEWSTATE" value="dO…NnU="
value="dO…NnU=" />
/>

 Using cookies for enhanced client-side state


Response.Cookies("User_FullName").Value
Response.Cookies("User_FullName").Value == strFullName
strFullName
……
strFullName
strFullName == Request.Cookies("User_FullName").Value
Request.Cookies("User_FullName").Value

*****************************ILLEGAL FOR NON-TRAINER USE******************************


Web pages are generally regarded as stateless devices, meaning that they do not
remember any values between being displayed, destroyed, and displayed again.
However, in ASP.NET you can choose to maintain state for a Web page when
you need to. You can do this by using view state at the page and control level.

Maintaining Control State


Web pages are re-created each time a client browser makes a request. Normally
this means that all control state is reset with each request. However, you can
save the state of a page and its content by using the view state property or the
StateBag class. Both approaches use a hidden variable to store the information
as part of the page that is sent to the browser. This information is then retrieved
when the page is posted back to the server.

Using View State


The System.Web.UI.Control class implements a property named
EnableViewState. You can set this property to achieve the following
functionality:
 True
If you set this property to True (the default), any control that inherits from
this base class will maintain its view state and the view state of any
constituent control, through multiple requests by a single client browser.
 False
If a page does not post back to itself, you can set this property to False to
increase performance by reducing the size of the page.
Module 7: Building Web Applications 7

Using State Bags


You can use the StateBag class to maintain additional cross-request
information. An instance called ViewState is accessible from each Web Form
and allows you to store and retrieve extra information.
The following example shows how to create a stateful property (a value that is
maintained for multiple requests) called TempData and assign a value of 25.
You can then retrieve this data from the StateBag instance and display it to the
user by using the Response.Write method.
ViewState("TempData") = 25

Response.Write(ViewState("TempData"))

When the page is sent to the browser, a hidden variable is included, as shown in
the following example:
<input type="hidden" name="__VIEWSTATE" value="dO…NnU=" />

Using Cookies for Enhanced Client-Side State


A cookie is a simple mechanism for storing information in a text file on a client
computer. You can use the HttpCookie class to provide a type-safe way to
access cookies and manipulate cookie properties such as Expires, Value, and
Name. Read and write access to a cookie is provided by means of the Cookies
collection property for the Request and Response objects, respectively.
The following example stores a cookie with an expiration date on the client
computer before reading the data back from the client:
Response.Cookies("User_FullName").Value = strFullName
Response.Cookies("User_FullName").Expires = _
Now.AddMonths(1)
...
If Not (Request.Cookies("User_FullName") Is Nothing) Then
strFullName = Request.Cookies("User_FullName").Value
End If
8 Module 7: Building Web Applications

Maintaining Server-Side State


Topic Objective
To explain how to use the
server-side state facilities
available in the ASP.NET  Application object maintains application-level state
framework.
 Data for use by all users
Lead-in
You can use several Application("App_StartTime")
approaches to maintain Application("App_StartTime") == Now
Now
server-side state in
ASP.NET applications.  Session object maintains session-level state
 Data for use by a single client browser
 Data recoverable by means of Windows Service or SQL
Server database
Session("Session_StartTime")
Session("Session_StartTime") == Now
Now

*****************************ILLEGAL FOR NON-TRAINER USE******************************


Some parts of your Web application may need to maintain cross-request state.
For example, a shopping cart application may need to maintain information
about a customer order through multiple visits to a page before the items are
purchased. You can maintain state at either the application or session level.

Maintaining Application State


You can use the HttpApplicationState class to store application-level
Delivery Tip information. You can use the intrinsic Application object during a Web request
Ensure that students
understand the concepts of
to share global data across the application. The default Item property of this
a Web farm and Web object stores and retrieves a collection of objects, allowing anything from a
garden. string to a user-defined object to be maintained for the lifespan of the
application. Application state is not shared across a Web farm or a Web garden.

Note A Web farm is an application that is hosted across multiple computers. A


Web garden is an application that is hosted on a single computer with multiple
processors.

Example
The following example shows how to store the start time of the application and
then displays the information at a later stage:
Application("App_StartTime") = Now
...
Response.Write("Application Started: " & _
Application("App_StartTime"))
Module 7: Building Web Applications 9

About Application State


Note the following information when using application state:
 The Contents collection property of the HttpApplicationState class
provides backward compatibility with ASP.
 Multiple-user sessions within an ASP.NET application can potentially
modify data, resulting in values that differ from those expected by a single
user. The following example shows how you can use the Lock and Unlock
methods to avoid this problem:
Application.Lock
Application("aCounter") = Application("aCounter") + 1
Application.Unlock

Maintaining Session State


The server maintains session state information for each browser client as a
logical “session” until the session ends. The session ends when a time out
occurs or when the user moves away from the ASP.NET application.

Example
You can use the intrinsic Session object to access this state information. The
following example shows how to use session state to store a start time that can
be retrieved at a later stage during the user’s session:
Session("Session_StartTime") = Now
...
Response.Write("Session started: " & _
Session("Session_StartTime"))

About Session State


Note the following facts and guidelines when using session state in ASP.NET
applications:
 ASP.NET session state maintains backward compatibility with ASP session
state.
 You can store session state in three ways:
• As part of the application process
• As an external Microsoft Windows® Service, allowing for ASP.NET
application restarts and data sharing across multiple processors (Web
gardens)
• As data in a Microsoft SQL Server™ database, allowing the session data
to be available across multiple computers (Web farms)
 While ASP applications require a cookie to store a unique SessionID value
that links a user to a particular session, ASP.NET does not require cookies
in order to store session state. In the Web.config file, you can choose the
option to automatically encode the SessionID value in the Uniform
Resource Locator (URL). This means that all browsers can use session
information even if the user has disabled cookie support.

Note For more information about configuring session state, search for
“web.config” in the Microsoft Visual Studio® .NET documentation.
10 Module 7: Building Web Applications

Managing an ASP.NET Application


Topic Objective
To discuss the way  Configuring ASP.NET applications
ASP.NET applications are  XML configuration file – Web.config
managed.
 Human-readable and writeable
Lead-in
Managing ASP.NET  Stored with the application
applications is
 Deploying ASP.NET applications
straightforward.
 XCOPY the pages, components, and configuration
 No registration required
 Updating ASP.NET applications
 Copy new files over old files
 No update utility, restart, or reboot required
 Live update keeps applications running

*****************************ILLEGAL FOR NON-TRAINER USE******************************


ASP.NET applications are simple to configure, deploy, and maintain.

Delivery Tip Configuring ASP.NET Applications


Deployment is covered in
An ASP.NET application can contain web.config configuration files. These
more depth in Module 10,
“Deploying Applications,” in
files store information about the application, including application settings,
Course 2373B, custom browser capabilities, custom errors, security, and more. The document
Programming with Microsoft format is Extensible Markup Language (XML), so you can use any text or
Visual Basic .NET. XML editor to read or edit the file.
You deploy the configuration file to the same virtual directory as the
application it configures. The file also configures any applications in
subdirectories of that virtual directory, unless those applications have their own
configuration file.

Note For more information about configuring ASP.NET applications, search


for “ASP.NET configuration” in the Visual Studio .NET documentation.
Module 7: Building Web Applications 11

Deploying ASP.NET Applications


You deploy an ASP.NET application by copying the required files to a virtual
directory on an IIS computer. No component registration is required because
the components contain their own self-describing metadata. This also solves
registry problems previously associated with deploying components.

Note For more information about deployment of Visual Basic .NET-based


applications, see Module 10, “Deploying Applications,” in Course 2373B,
Programming with Microsoft Visual Basic .NET.

Updating ASP.NET Applications


You can update an ASP.NET application at any time without needing to restart
the application or IIS, because no components are locked at any stage. No
update utility is required because you can simply copy new files over the old
ones. The ASP.NET framework detects the update, and it upgrades the live
application.
12 Module 7: Building Web Applications

Overview of ASP.NET Security


Topic Objective
To provide an overview of
security in ASP.NET
applications.  Security settings stored in web.config file
Lead-in  Out-of-box authentication support
ASP.NET applications can
be secured in various ways.  Windows authentication – Basic, Digest, or Integrated
 Microsoft Passport authentication
 Forms (Cookie) authentication
 Role-based security architecture

*****************************ILLEGAL FOR NON-TRAINER USE******************************


Most companies need to secure their Web applications so that users can only
Delivery Tip perform actions they are authorized to perform. The required levels of security
Security is a complicated
topic and is only briefly
can include simple public access to Web pages, secure validation of credit card
covered in this lesson. information, and secure access for trading partners. The System.Web.Security
Direct students to additional namespace provides all aspects of ASP.NET security.
material as often as
possible. Security Settings Stored in web.config File
You can specify security settings in the web.config configuration file that is
then deployed with the application. This allows you to define which security
options your applications use and, optionally, which users can use the system.

Out-of-Box Authentication Support


ASP.NET works closely with IIS 5.0 to accept and validate user credentials by
using the following authentication methods.
 Windows authentication.
Windows authentication does not require any specific coding in your
ASP.NET application, but it does require extra administration when the
application is deployed. IIS provides three ways to perform Windows
authentication: Basic, Digest, and Integrated.
Authentication Definition

Basic Before information without encryption is posted to IIS, a


Windows dialog box appears in which users enter their user
name and password.
Digest Performs the same action as Basic authentication; however, the
information is encrypted when sent to the server.
Integrated Uses the user’s logged-on Windows domain account details.
This option is more suitable for an intranet application than for
an Internet application because it cannot be used through
firewalls or proxy servers.
Module 7: Building Web Applications 13

The following example shows how to specify Windows authentication in


the Web.config file:
<authentication mode="Windows" />

Note For more information about the different types of authentication, see
Designing Secure Web-Based Applications for Microsoft Windows 2000, by
Michael Howard, Microsoft Press®.

 Microsoft Passport authentication.


Passport authentication requires the user to have a Microsoft Passport that
can be created on the Internet. This approach benefits users because they use
the same sign-in name and password for any Web site that uses this type of
authentication.

Note For more information about passports, go to


http://www.passport.com/Business.

 Forms (Cookie) authentication.


Web sites that require users to logon to the system from an HTML form
usually store a cookie on the client computer. The cookie is used for
subsequent visits to the site and the information can then be used for
whatever purpose the site requires. This type of authentication is ideal for
querying user details against a database in an e-commerce situation.

Role-Based Security Architecture


ASP.NET allows you to selectively allow or deny requests from specific users
or groups of users known as roles. You can store the list of users and roles as
part of the Web.config file or as a separate XML document.
The following example shows code to use in the Web.config file to allow
access for two particular users and the Admins role but deny access to all others
using Windows authentication:
<authentication mode="Windows" />
<authorization>
<allow users="Doug,Denise" />
<deny users="*" />
<allow roles="Admins" />
<deny roles="*" />
</authorization>

Note For more information about role-based security, see ASP.NET


Authorization in the Visual Studio .NET documentation.
14 Module 7: Building Web Applications

Using Global Events with Global.asax


Topic Objective
To describe the uses of the
Global.asax file in an
ASP.NET application.  Useful for initializing data for application or session
Lead-in state
The Global.asax file Sub
Sub Application_Start(ByVal
Application_Start(ByVal Sender
Sender As
As Object,
Object, ByVal
ByVal ee As
As EventArgs)
EventArgs)
provides application-level Application("SessionCounter")
Application("SessionCounter") == 00
logic to your ASP.NET End
End Sub
Sub
application.
Sub
Sub Session_Start(ByVal
Session_Start(ByVal Sender
Sender As
As Object,
Object, ByVal
ByVal ee As
As EventArgs)
EventArgs)
Application("SessionCounter")
Application("SessionCounter") = Application("SessionCounter") ++ 11
= Application("SessionCounter")
Session("StartTime")
Session("StartTime") == Now
Now
End
End Sub
Sub
Sub
Sub Session_End(ByVal
Session_End(ByVal Sender
Sender As
As Object,
Object, ByVal
ByVal ee As
As EventArgs)
EventArgs)
Application("SessionCounter")
Application("SessionCounter") = Application("SessionCounter") -- 11
= Application("SessionCounter")
End
End Sub
Sub

*****************************ILLEGAL FOR NON-TRAINER USE******************************


You can initialize state for application-level or session-level data by using the
Global.asax application file. This application file enhances the Global.asa
application file used in ASP.
Avoid using local variables to store information, because ASP.NET may create
multiple instances of the global class. If you need to store information, use
application-state or session-state.

Application-Level Events
ASP.NET provides several events to initialize state at the application level,
including the following:
 Application_Start
This event is activated when the first user attempts to gain access to access
your Web application. Any subsequent requests will not activate this event
even if multiple instances of the Global class have been instantiated. This
event is particularly useful for initializing application-state information.
 Application_BeginRequest
This event is activated whenever a request for a URL is received from a
client application.
 Application_EndRequest
This event is activated whenever a request for a URL has been completed.
 Application_End
This event is activated when the last instance of the Global class is
destroyed so that any final resources can be cleaned up.
Module 7: Building Web Applications 15

Session-Level Events
ASP.NET also provides session-level events, including the following:
 Session_Start
This event is activated at the beginning of a new client session and is useful
for initializing session-state information.
 Session_End
This event is activated when a client session ends after a period of inactivity
or if the Session.Abandon method is explicitly called as part of your
application code.

Example
The following example shows how you could use these events in conjunction
with state management objects to initialize stateful data:
Sub Application_Start(ByVal sender As Object, _
ByVal e As EventArgs)
'Initialize the application-level counter
Application("SessionCounter") = 0
End Sub

Sub Session_Start(ByVal sender As Object, _


ByVal e As EventArgs)
'Increment the application-level counter
Application("SessionCounter") = _
Application("SessionCounter") + 1

'Assign new value to session-level data


Session("StartTime") = Now
End Sub

Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)


'Decrement the application-level counter
Application("SessionCounter") = _
Application("SessionCounter") - 1
End Sub
16 Module 7: Building Web Applications

 Creating Web Form Applications


Topic Objective
To provide an overview of
the topics covered in this
lesson.  Structure of Web Forms
Lead-in  Using HTML Controls
Web Forms create the
visual interaction between  Advantages of Web Server Controls
the server computer and the
user in the same way that  Using Web Server Controls
HTML and script did
previously, but in a compiled  Handling Events
and more maintainable
fashion.

*****************************ILLEGAL FOR NON-TRAINER USE******************************


Traditionally, you create Web applications by using a combination of static
HTML pages and dynamic content provided by client-side and server-side
script. ASP.NET provides Web Forms to improve and enhance Web
applications.
After you complete this lesson, you will be able to:
 Describe the files that constitute a Web Form.
 Use the different types of controls available on a Web Form, including
HTML and Web server controls.
 Write code in event handlers that will execute on the server.
Module 7: Building Web Applications 17

Structure of Web Forms


Topic Objective
To describe the structure of
ASP.NET Web Forms.
Lead-in  Web Forms separate declarative tags from logic
Because ASP pages often  The .aspx file contains HTML and other tags
contain script mixed with
HTML tags, they can be  The code-behind file contains logic and event handling
difficult to maintain.
ASP.NET solves this issue
by separating the HTML
tags from the page logic.

<tags> code

Logon.aspx Logon.aspx.vb

*****************************ILLEGAL FOR NON-TRAINER USE******************************


Because ASP pages often contain HTML tags mixed with user interface event-
Delivery Tip handling script, they can be difficult to maintain. When developing applications
Point out that, when the
application is built and
with the Visual Studio .NET Integrated Development Environment (IDE),
deployed, the .aspx files are ASP.NET Web Forms consist of two separate files: the .aspx file for HTML
copied, but the .aspx.vb files and other tags, and the code-behind file for the code that executes as a result of
are compiled into the user interaction. Because the tags and the code are separated in ASP.NET, you
appropriate DLL file. can more easily locate bugs and maintain code.

Alternatively, developers
can include both code and
The .aspx File
HTML tags within a single The .aspx file contains definitions for the visual elements of the Web Form,
.aspx file by using the such as the HTML tags, Web controls, client-side script, and static text. This
<script> tag. This approach file also includes any ASP.NET directives, such as links to the code-behind
provides less separation module that contains the logic and event-handling code of the Web Form.
between the code and tags,
but does not require a DLL You can use the Web Forms Designer in Design view to create a page by using
file to be built and deployed drag-and-drop techniques. You can use the HTML view to edit the HTML tags.
with the application. Microsoft IntelliSense® is provided in this view to increase the efficiency and
accuracy of creating HTML tag expressions.
18 Module 7: Building Web Applications

The Code-Behind File


The code-behind file is a file with an .aspx.vb extension in an ASP.NET project
using Visual Basic.NET. Your server-side and event-handling code is
automatically placed in the code-behind file of a Web Form. This file defines a
class that is referenced by the @ Page directive within the .aspx file of the Web
Form. You can use this class to:
 Create methods or event-handling code.
 Provide access to many of the commonly used ASP.NET objects.
This class inherits from the System.Web.UI.Page class to provide direct
access to many ASP.NET objects, such as Request and Response.
 Provide event handlers.
The class provides a series of useful event handlers, such as the page Load,
Init, Unload, and PreRender events.

The code generated in the code-behind file looks very similar to the code
generated in Windows Forms. Note the following when using the code-behind
file:
 It contains variable declarations.
The code contains variable declarations for the visible controls so they can
be accessed programmatically within your procedures.
 It contains variable events.
As the control variables are declared using the WithEvents modifier, you
can use the control events to execute user interface code to handle events
like submitting information to a database or linking to another page.
 It automatically compiles with your application.
The code in this file is automatically compiled into your dynamic-link
library (DLL) when you build the application.
Module 7: Building Web Applications 19

Using HTML Controls


Topic Objective
To explain how to use
HTML controls.
 Direct relationship to preexisting HTML tags
Lead-in
ASP.NET provides two main  Client side by default
types of controls for you to
use: HTML controls and  Server side with runat=server directive
Web controls.
 Properties correspond one-to-one with HTML, weakly
typed
 Defined with HTML tag
<input
<input type=text
type=text id="text1"
id="text1" value="some
value="some text"
text" runat="server">
runat="server">

 ASP.NET includes HTML controls for commonly used


HTML elements

*****************************ILLEGAL FOR NON-TRAINER USE******************************


HTML controls have a direct relationship to preexisting HTML tags. The
controls are defined by classes in the System.Web.UI.HtmlControls
namespace supplied by the .NET Framework. These controls correspond very
closely to the HTML elements that they render.

Specifying Client-Side or Server-Side HTML Controls


By default, HTML controls are run on the client. They are treated as opaque
text by the server and passed straight through to the browser for interpreting as
HTML elements. You can also write client-side script to process control events
on the client.
To run controls on the server, set the runat directive to the value of server to
convert the HTML elements to HTML server controls. You can do this
manually by editing the HTML tag of the control, or you can select the option
on the context menu of the control.

Manipulating HTML Controls


You define all HTML by using an HTML tag. For example, the following code
declares a text input field to run on the server:
<input type=text id="text1" value="some text" runat="server">

You can manipulate control properties programmatically from server-side code


when the control is marked to run on the server. These properties correspond
directly to their equivalent HTML tag predecessors. For example, the HTML
tag <INPUT> supports an attribute called Value, and the HTMLInputText
class supports an equivalent Value property.
20 Module 7: Building Web Applications

You can set other properties of the HTML control by using the Attributes
collection property of the control. This type of property setting is considered
weakly typed because the collection only stores and retrieves String values, as
shown in the following example:
HTMLTable1.Attributes("bgColor") = "Green" 'Weakly typed

To specify the programmatic accessor that identifies the control in the server
code, use the ID attribute. To set the initial display value of the text field, use
the VALUE attribute.

HTML Elements and HTML Server Controls


ASP.NET includes HTML controls for commonly used HTML elements such
as forms, input elements, tables, and so on. The following list matches the
client-side HTML elements with their corresponding HTML server controls.
HTML element HTML server control

<A> HTMLAnchor
<IMG> HTMLImage
<FORM> HTMLForm
<TABLE> HTMLTable
<TR> HTMLTableRow
<TD> HTMLTableCell
<SELECT> HTMLSelect
<TEXTAREA> HTMLTextArea
<BUTTON> HTMLButton
<INPUT TYPE=TEXT> HTMLInputText
< INPUT TYPE=FILE> HTMLInputFile
< INPUT TYPE=SUBMIT> HTMLInputButton
< INPUT TYPE=BUTTON> HTMLInputButton
< INPUT TYPE=RESET> HTMLInputButton
< INPUT TYPE=HIDDEN> HTMLInputHidden
Module 7: Building Web Applications 21

Advantages of Web Server Controls


Topic Objective
To provide an overview of
the features of Web server  Automatic browser detection
controls.
 Detect capabilities of client and render accordingly
Lead-in
The second type of control
 Strongly typed, consistent object model
that ASP.NET includes is  Enables compile-time type checking
the Web server control.
 Declared with XML tags
 Server side only using runat=server directive
<asp:textbox
<asp:textbox id="text2"
id="text2" text="some
text="some text"
text" runat="server">
runat="server">
</asp:textbox>
</asp:textbox>

 Rich functionality
 Example: Calendar or RadioButtonList control

*****************************ILLEGAL FOR NON-TRAINER USE******************************


In addition to HTML controls, ASP.NET Web Forms also provide Web server
controls. Web server controls run exclusively on the server, and provide the
following advantages:
 Automatic browser detection
Web server controls can render themselves differently to suit the capabilities
of different browsers. For example, a control may send dynamic HTML
(DHTML) to a rich browser (HTML 4.0 and later), and send HTML and
script to a more basic client browser. This is known as creating uplevel and
downlevel capability.
 Strongly typed, consistent object model
Web server controls are strongly typed, so compile-time checking of code
provides you with accurate error messages before the application is built.
With Web controls, you can use a consistent object model, which is similar
to Windows Forms controls. For example, you can set the BackColor
property of a Button control explicitly by using a strongly typed constant,
as shown in the following example.
Button.BackColor = Color.Green 'Strongly typed
22 Module 7: Building Web Applications

 Declared with XML tags


You declare Web server controls by using an XML tag. This tag references
the asp namespace and specifies information regarding the type of Web
control, a programmatic identifier through use of the ID attribute, and any
initial values.
The following example shows the syntax for creating a simple TextBox
Web control whose ID is “text2” and whose initial TEXT value is “some
text.”
<asp:TextBox id="text2" text="some text" runat="server">
</asp:TextBox>

 Rich functionality
Web server controls include enhanced versions of traditional HTML form
controls such as Button and TextBox, as well as complex controls such as
Calendar, DataGrid, and AdRotator (advertisement rotator). These
controls do not correspond directly to HTML elements or attributes.
Module 7: Building Web Applications 23

Using Web Server Controls


Topic Objective
To explain available Web
server controls.
 Intrinsic controls
Lead-in
There are several types of  List controls for repetition
Web server controls
 Validation controls validate
available in ASP.NET Web input
Forms.
 Rich controls simplify
common Web page
requirements

*****************************ILLEGAL FOR NON-TRAINER USE******************************


ASP.NET Web server controls can be separated into four main categories:
Delivery Tip intrinsic, list, validation, and rich controls. The table below explains each of
Pick one or two individual
controls for discussion,
these categories.
particularly a validation Category Definition Examples
control and rich control.
Intrinsic controls Provides the basic functionality Button, TextBox,
for user interaction with the CheckBox
browser.
Many of these controls are
similar to the corresponding
HTML controls, but their
enhanced properties and methods
allow a more powerful and
consistent programming style.
List controls Used for repetition when DropDownList, ListBox,
displaying any type of list. Repeater, DataGrid
Validation controls Provides simple control RequiredFieldValidator,
validation that displays a RangeValidator,
message to the user without RegularExpressionValida
making a return trip to the server. tor, CompareValidator
Rich controls Simplifies common Web page AdRotator, Calendar
requirements.
24 Module 7: Building Web Applications

Using Validation Controls


You can link a validation control to another control at design time or run time
to make a comparison against the linked control. This validation can include
testing for required fields using the RequiredFieldValidator control, testing
for a range of input values using the RangeValidator control, testing for values
that match a particular expression using the RegularExpressionValidator
control, and testing for comparisons between multiple controls using the
CompareValidator control.
The following example shows a RangeValidation control named rngTest and
a TextBox Web server control named txtInput. The validation control checks
whether the value in txtInput matches the range and displays a message if it
does not.
rngTest.ControlToValidate = "txtInput"
rngTest.MinimumValue = "10"
rngTest.MaximumValue = "20"
rngTest.ErrorMessage = "Please enter a value between 10 and
20."

This validation control is rendered in client-side script when the page is


displayed so that return trips to the server are not required simply for control
validation.

Using Rich Controls


Using the AdRotator control, you can display advertisement banners on a page
that automatically changes the displayed advertisement whenever the page is
refreshed or revisited. The information is stored in an XML file that includes
details about what image to use, where to redirect the browser when the
advertisement is clicked, and how frequently the advertisement should appear.
The following example shows how you can use the AdRotator control on a
page:
<body>
<form id="WebForm2" method="post" runat="server">
<asp:AdRotator id="AdRotator1" runat="server"
Width="401px" Height="45px"
AdvertisementFile="ads.xml">
</asp:AdRotator>
</form>
</body>
Module 7: Building Web Applications 25

The following example shows the information required in the XML file to
rotate the advertisements:
<Advertisements>
<Ad>
<ImageUrl>images/graphic1.gif</ImageUrl>
<NavigateUrl>http://www.example1.microsoft.com</NavigateUrl>
<AlternateText>
Click here for products page 1
</AlternateText>
<Keyword>Products 1</Keyword>
<Impressions>80</Impressions>
</Ad>
<Ad>
<ImageUrl>images/graphic2.gif</ImageUrl>
<NavigateUrl>http://www.example2.microsoft.com</NavigateUrl>
<AlternateText>
Click here for products page 2
</AlternateText>
<Keyword>Products 2</Keyword>
<Impressions>80</Impressions>
</Ad>
</Advertisements>

The HTML produced by these controls when rendered may be substantially


different from the object model that developers code against.
The following segment of a Web Form shows how the HTML syntax looks
when viewed in the HTML design window for a Web Form containing a
RadioButtonList.
<form id="WebForm1" method="post" runat="server">
<asp:RadioButtonList id="RadioButtonList1" runat="server">
<asp:ListItem Value="One">One</asp:ListItem>
<asp:ListItem Value="Two">Two</asp:ListItem>
</asp:RadioButtonList>
</form>
26 Module 7: Building Web Applications

The following HTML is generated when the Web Form is rendered in


Internet Explorer version 6.0. It shows that the RadioButtonList control
is rendered in a table with HTML input tags and labels.

Example
<form name="WebForm1" method="post" action="WebForm1.aspx"
id="WebForm1">
<table id="RadioButtonList1" border="0">
<tr><td>
<input type="radio" id="RadioButtonList1_0" value="One"
name="RadioButtonList1" />
<label for="RadioButtonList1_0">One</label>
</td></tr>
<tr><td>
<input type="radio" id="RadioButtonList1_1" value="Two"
name="RadioButtonList1" />
<label for="RadioButtonList1_1">Two</label>
</td></tr>
</table>
</form>

Note For information about creating Web Form controls, see Module 9,
“Developing Components in Visual Basic .NET,” in Course 2373B,
Programming with Microsoft Visual Basic .NET.
Module 7: Building Web Applications 27

Handling Events
Topic Objective
To explain how to handle  Event handlers contain code for user interactions
events in Web Forms.
 Page events: Init, Load, PreRender, UnLoad
Lead-in
Handling events in Web Private
Private Sub
Sub Page_Load(ByVal
Page_Load(ByVal Sender
Sender As
As System.Object,
System.Object, __
Forms is similar to ByVal
ByVal e As System.EventArgs) Handles MyBase.Load
e As System.EventArgs) Handles MyBase.Load
traditional Visual Basic If
If Not
Not IsPostBack
IsPostBack Then
Then 'IsPostBack
'IsPostBack is
is also
also available
available via
via 'Me'
'Me'
event handling. 'Perform action first time page is displayed
'Perform action first time page is displayed
End
End If
If
End Sub
End Sub

 Control events: Click, Changed, PreRender


Private
Private Sub
Sub btn_Click(ByVal
btn_Click(ByVal sender
sender As
As System.Object,
System.Object, __
ByVal
ByVal ee As
As System.EventArgs)
System.EventArgs) Handles
Handles btn.Click
btn.Click
btn.Text
btn.Text == "clicked"
"clicked"
End
End Sub
Sub

*****************************ILLEGAL FOR NON-TRAINER USE******************************


Interacting with users is one of the primary reasons for creating ASP.NET Web
Forms. You program various events to handle these interactions as you do in
traditional Visual Basic development. The Web page itself can execute code,
and so can the many events raised by different objects, including all of the
server controls.

Page Events
Every Web Form inherits from the Page class, which provides several useful
events indirectly from other inherited classes such as the Control and
TemplateControl classes. Several of these events are included in the following
list, in the order in which they occur when a user accesses a page:
 Init
This event occurs as the first step in the page lifecycle, when the page is
initialized. You use this event to initialize local variables. Do not use this
event to access view state information or controls on the page, because they
may not be created or accessible at this point.
 Load
This event occurs after the Init event and before the PreRender events are
raised. You can use this event to view state information or access controls.
 PreRender
This event occurs when the page is about to render its contents to the Web
browser. Use it to perform any pre-rendering steps before the view state is
saved.
 Unload
This event occurs when the page is unloaded, after rending has occurred.
Use it for removing any resources created throughout the request.
28 Module 7: Building Web Applications

Using the Load Event


The Load event is commonly used to test the IsPostBack property of the Web
Form to see whether the page is being loaded and displayed for the first time or
whether it is being displayed in response to a client postback.
The following example shows this common usage:
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
'IsPostBack is also available by means of 'Me'
If Not IsPostBack Then
'Perform action first time page is displayed
End If
End Sub

Control Events
Server controls are based on the WebControl class, which is based on the
System.Web.UI.Control class. The Page class is also based indirectly on the
System.Web.UI.Control class, through the TemplateControl class. Therefore,
server controls share the events described in the preceding Page Events section.
Individual controls also add their own events to the object model to allow easier
interaction with the user. Examples include the simple Click event for the
Button class, the TextChanged event for the TextBox class, and the
SelectedIndexChanged event for the ListControl class.
Some controls post their events to the server immediately, such as the Click
Delivery Tip event of the Button class. Other controls, such as the TextChanged event of
Discuss when events are
raised by explaining the
the TextBox class, may only register their events when other means are used to
AutoPostBack property, as post events to the server. These events are stored and then raised sequentially to
shown in the example in the the server code when the post event is triggered. You can alter this behavior by
notes. setting the AutoPostBack property of the control to True. In this way, you can
raise events immediately regardless of the default behavior. In the case of a
TextBox control, this means the event will be posted every time the text value
is modified and the control loses focus.
Module 7: Building Web Applications 29

Using Control Events


The following example shows how to add to events to individual controls,
TextBox and Button, to facilitate user interaction on a Web Form:
Private Sub btnPost_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnPost.Click
Response.Write("Button Pressed")
txtInput.AutoPostBack = True
End Sub

Public Sub txtInput_TextChanged(ByVal sender As Object, _


ByVal e As System.EventArgs) Handles txtInput.TextChanged
Response.Write("Text Changed")
End Sub

The preceding code is processed as follows:


1. When the user types a value into the txtInput control and tabs to the
btnPost control, the TextChanged event is held back until the button is
clicked.
2. This posts to the Web Form and executes first the txtInput_TextChanged
handler and then the btnPost_Click handler.
3. The page is then displayed again with the event order written as part of the
page, using the Response.Write method.
4. The post will now occur as soon as the user changes the value and tabs out
of the txtInput control because the txtInput.AutoPostBack property has
been set to True.

Important Using the AutoPostBack property for multiple controls on the same
form will slow down the performance of the application because of the need for
multiple trips to the server.
30 Module 7: Building Web Applications

Demonstration: Creating Web Forms


Topic Objective
To demonstrate how to
create a simple Web Form
application.
Lead-in
This demonstration shows
how to create a simple Web
Form application that posts
information to the Server by
using Web server controls.

*****************************ILLEGAL FOR NON-TRAINER USE******************************


In this demonstration, you will learn how to create a simple Web Form
Delivery Tip application that uses Web server controls for posting data to the server.
The step-by-step
instructions for this
demonstration are in the
instructor notes for this
module.
Module 7: Building Web Applications 31

Lab 7.1: Creating the Customer Logon Web Forms


Topic Objective
To introduce the lab.
Lead-in
In this lab, you will create a
simple Web Form
application that registers
and logs customers on to a
system.

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Explain the lab objectives.


Objectives
After completing this lab, you will be able to:
 Create a Web Forms application.
 Create Web Forms.
 Use Web controls, such as the validation controls.
 Use the Session state object.

Prerequisites
Before working on this lab, you must be familiar with creating Web Forms in
Visual Basic .NET.

Scenario
In this lab, you will create Web Forms that register and logon customers for the
Cargo system.
The WebCustomer class is provided for you to use as a basis for your Web
application. It provides some existing customer details to test your application
and allows you to add new customers. Any customer details added are only
valid for a single test session because they are not persisted to disk at this time.

Starter and Solution Files


There are starter and solution files associated with this lab. The starter files are
in the install folder\Labs\Lab071\Starter folder, and the solution files are in the
install folder\Labs\Lab071\Solution folder.

Estimated time to complete this lab: 60 minutes


32 Module 7: Building Web Applications

Exercise 1
Creating the DefaultPage Web Form
In this exercise, you will create a Web Application and its default menu page.

 To create the Web application project


1. Open Microsoft Visual Studio .NET.
2. On the File menu, point to New, and then click Project.
3. From the Visual Basic Projects folder, click ASP.NET Web Application.
4. Change the Location to the following Web directory:
http://localhost/2373/Labs/Lab071 and then click OK.

 To add the WebCustomer class


1. On the Project menu, click Add Existing Item.
2. Go to install folder\Labs\Lab071\Starter, click WebCustomer.vb, and then
click Open.

 To create the DefaultPage Web Form


1. In Solution Explorer, right-click WebForm1.aspx, and then click Delete,
confirming the deletion when prompted.
2. On the Project menu, click Add Web Form. Rename the item
DefaultPage, and then click Open.
3. Click in the design window for DefaultPage.aspx to display the Properties
window for the Web form. Change the pageLayout property for the
DOCUMENT object to FlowLayout.
4. In the design window for DefaultPage.aspx, type the following text on
separate lines.
Text Format

Welcome to the Cargo Online System Heading 1


Please select from the following options: Normal

5. From the Web Forms toolbox, insert the following controls, separated by
line breaks.
Control Property Value

Hyperlink (ID) lnkExisting


Text I am an existing customer
NavigateUrl LogOn.aspx
Hyperlink (ID) lnkNewCustomer
Text I am a new customer
NavigateUrl NewCustomer.aspx

6. Save your project.


Module 7: Building Web Applications 33

Exercise 2
Creating the NewCustomer Web Form
In this exercise, you will create a Web Form to allow new customers to register.

 To create the NewCustomer Web Form


1. On the Project menu, click Add Web Form. Rename the item
NewCustomer, and then click Open.
2. Click in the design window for NewCustomer.aspx to display the Properties
window for the Web form. Change the pageLayout property for the
DOCUMENT object to FlowLayout.
3. In the design window for NewCustomer.aspx, type the following text on
separate lines.
Text Format

Please enter your details Heading 1


Full name: Normal
E-mail: Normal
Password: Normal
Confirm password: Normal

4. From the Web Forms toolbox, insert the following controls, and set their
properties as shown in the following table.
Control Property Value

TextBox (ID) txtFullName


RequiredFieldValidator (ID) rfvName
ErrorMessage Please enter your
full name
ControlToValidate txtFullName
TextBox (ID) txtEmail
RegularExpressionValidator (ID) revEmail
ErrorMessage Your e-mail address
is invalid
ControlToValidate txtEmail
ValidationExpression Click the browse
button and select
Internet E-mail
Address
Display Dynamic
RequiredFieldValidator (ID) rfvEmail
ErrorMessage Please enter an
e-mail address
ControlToValidate txtEmail
Display Dynamic
TextBox (ID) txtPassword
34 Module 7: Building Web Applications

(continued)
Control Property Value

TextMode Password
RegularExpressionValidator (ID) revPassword
ErrorMessage Your password
must be at least 4
characters long
ControlToValidate txtPassword
ValidationExpression Click the browse
button and select
(Custom) from the
list, entering the
following value
\w{4,}
Display Dynamic
RequiredFieldValidator (ID) rfvPassword
ErrorMessage Please enter a
password
ControlToValidate txtPassword
Display Dynamic
TextBox (ID) txtConfirm
TextMode Password
CompareValidator (ID) cvConfirm
ErrorMessage Passwords do not
match
ControlToValidate txtConfirm
ControlToCompare txtPassword
Display Dynamic
RequiredFieldValidator (ID) rfvConfirm
ErrorMessage Please confirm the
password
ControlToValidate txtConfirm
Display Dynamic
Button (ID) btnSubmit
Text Submit
Module 7: Building Web Applications 35

5. Create your Web Form so that it looks like the following illustration.

6. Double-click btnSubmit, and add the following code to the


btnSubmit_Click event handler:
Dim newCust As New WebCustomer( )
newCust.AddCustomer(txtEmail.Text, txtPassword.Text, _
txtFullName.Text)
Session("User_FullName") = newCust.FullName

Response.Redirect("Welcome.aspx")

7. Save your project.


36 Module 7: Building Web Applications

Exercise 3
Creating the LogOn Web Form
In this exercise, you will create the LogOn Web Form for existing customers.

 To create the LogOn Web Form


1. On the Project menu, click Add Web Form. Rename the item LogOn, and
then click Open.
2. Click in the design window for LogOn.aspx to display the Properties
window for the Web form. Change the pageLayout property for the
DOCUMENT object to FlowLayout.
3. Open the design window for LogOn.aspx, and type the following text on
separate lines.
Text Format

Please enter your details Heading 1


E-mail: Normal
Password: Normal

4. From the Web Forms toolbox, insert the following controls, separated by
line breaks, arranging them with their related text values.
Control Property Value

TextBox (ID) txtEmail


RegularExpressionValidator (ID) revEmail
ErrorMessage Your e-mail address
is invalid
ControlToValidate txtEmail
ValidationExpression Click the browse
button and select
Internet E-mail
Address
Display Dynamic
RequiredFieldValidator (ID) rfvEmail
ErrorMessage Please enter an
e-mail address
ControlToValidate txtEmail
Display Dynamic
TextBox (ID) txtPassword
TextMode Password
RequiredFieldValidator (ID) rfvPassword
ErrorMessage Please enter a
password
ControlToValidate txtPassword
Display Dynamic
Module 7: Building Web Applications 37

(continued)
Control Property Value

Label (ID) lblNotFound


Text Not found message
ForeColor Red
Visible False
Button (ID) btnSubmit
Text Submit

5. Your Web Form should look like the following illustration.

6. Double-click the btnSubmit button, and add the following code to the
btnSubmit_Click event handler:
Dim existingCustomer As New WebCustomer( )
lblNotFound.Visible = False

Try
existingCustomer.LogOn(txtEmail.Text, txtPassword.Text)

Session("User_FullName") = existingCustomer.FullName
Response.Redirect("Welcome.aspx")
Catch ex As Exception
lblNotFound.Text = ex.Message
lblNotFound.Visible = True
Finally
existingCustomer = Nothing
End Try

7. Save your project.


38 Module 7: Building Web Applications

Exercise 4
Creating the Welcome Web Form
In this exercise, you will create the Welcome Web Form that customers see
after they are logged on to the system.

 To create the Welcome Web Form


1. From the Project menu, click Add Web Form. Rename the item Welcome,
and then click Open.
2. Click in the design window for Welcome.aspx to display the Properties
window for the Web form. Change the pageLayout property for the
DOCUMENT object to FlowLayout.
3. Open the Welcome.aspx file in the design window. In the Block Format
box on the Formatting toolbar, click Heading 1. Insert the following
control within the Heading 1 block, and set the property values as shown.
Control Property Value

Label (ID) lblWelcome


Text Welcome…

4. Open the Code Editor for Welcome.aspx.vb, and locate the Page_Load
event handler. Enter the following code:
lblWelcome.Text = "Welcome " & _
Session("User_FullName")

5. Save your project.


Module 7: Building Web Applications 39

 To test existing customers


1. In Solution Explorer, right-click DefaultPage.aspx, and click Set As Start
Page.
2. On the Debug menu, click Start.
3. Click the I am an existing customer hyperlink.
4. Click Submit to view the validation messages.
5. Enter the following values.
Text box Value

E-mail [email protected]
Password password

6. Click Submit to view the welcome message.


7. Use the Back button of the browser to return to the first page.

 To test new customers


1. Click the I am a new customer hyperlink.
2. Enter your full name, e-mail address and the password TRY. Use the TAB
key to exit the field. The error message will appear.
3. Type a valid password and confirm it.
4. Click Submit to view the welcome message.
5. Close the browser.
40 Module 7: Building Web Applications

If Time Permits
Using Cookies
In this optional exercise, you will use cookies to store and retrieve information
about a customer.

 To persist the cookie for a customer


1. Open the design window for LogOn.aspx.
2. Add a CheckBox control before the btnSubmit control, and set the
following properties.
Property Value

(ID) chkSave
Checked True
Text Save details

3. Open the Code Editor for LogOn.aspx.vb, and locate the btnSubmit_Click
event handler. Add the following code after the call to the
existingCustomer.LogOn method:
If chkSave.Checked = True Then
Response.Cookies("User_FullName").Value = _
existingCustomer.FullName
Response.Cookies("User_FullName").Expires = _
Now.AddMonths(1)
End If

 To retrieve the cookie for a customer


• Open the code window for DefaultPage.aspx.vb, and locate the Page_Load
event handler. Add the following code.
If Not (Request.Cookies("User_FullName") Is Nothing) Then
Session("User_FullName") = _
Request.Cookies("User_FullName").Value
Response.Redirect("Welcome.aspx")
End If
Module 7: Building Web Applications 41

 To test the application


1. On the Debug menu, click Start.
2. Click the I am an existing customer hyperlink.
3. Enter the following values.
Control Value

E-mail [email protected]
Password password
Save details Checked

4. Click Submit to view the welcome message.


5. Close the browser.
6. On the Debug menu, click Start.
7. Confirm that the Welcome page is the first page displayed and that it
displays the correct user details.
8. Close Internet Explorer and close Visual Studio .NET.
42 Module 7: Building Web Applications

 Building Web Services


Topic Objective
To provide an overview of
the topics covered in this
lesson.  What Are Web Services?
Lead-in  Creating a Web Service
Creating Web Services with
Visual Basic .NET enables  Enabling Web Service Discovery
you to quickly and easily
provide your customers with  Deploying and Publishing a Web Service
access to your business
services.

*****************************ILLEGAL FOR NON-TRAINER USE******************************


Internal client applications have been able to access shared components for
many years, but allowing external client applications access has been a difficult
challenge for both developers and administrators. Web Services allow you to
easily provide access to your application logic across the Internet without any
special configuration of firewalls or corporate networks by using the HTTP
protocol.
After you complete this lesson, you will be able to:
 Describe how the Internet and open standards such as XML and Hypertext
Transfer Protocol (HTTP) enable Web Services to be used by any client
application, regardless of its location or operating system.
 Create a Web Service by using Visual Basic .NET.
 Enable discovery of Web services.
 Deploy and publish your Web Services.
Module 7: Building Web Applications 43

What Are Web Services?


Topic Objective
To describe the purpose of
Web Services and the  Components accessible by means of the Internet rather than
supporting framework. distributed COM
Lead-in  Built using open Internet protocols XML, XSD, HTTP, SMTP
Web Services make your
components available to
the outside world.
 Consumers send and receive SOAP
XML messages
 Defined in terms of the message order Web Services
and format Description Language
 Site offers a description of the Web Discovery Document
Services it offers
 Search for a site that offers a Web UDDI
Service with a given capability

*****************************ILLEGAL FOR NON-TRAINER USE******************************


Components have traditionally been accessible only through local area
Delivery Tip networks by means of object-model specific protocols such as DCOM. This
This is an animated slide.
Click the slide to reveal the
limitation is partly due to the complexity involved in allowing external access
following sections: through ports to the internal network, as well as the dependence on both parties
1. Components accessible using a particular protocol.
by means of the Internet
rather than DCOM
Web Services remove this limitation by allowing access to components by
2. XML, XSD, HTTP, SMTP means of the Internet and HTTP while still maintaining security. The
3. SOAP supporting framework for Web Services provides the following:
4. WSDL
5. Discovery
 Open Internet protocols
6. UDDI Web Services use open Internet protocols such as XML, XML Schema
Definition (XSD), HTTP, and Simple Mail Transfer Protocol (SMTP) to
transmit messages. This allows any client application to use a Web Service
regardless of the operating system it is running on or the language it is
written in.
 XML messages and SOAP
SOAP is an industry standard for using XML to represent data and
Delivery Tip commands in an extensible way. Web Services do not have to use SOAP to
SOAP, XML, WSDL, and
discovery are discussed in
specify the message formats; HTTP GET and HTTP POST mechanisms can
more detail throughout this also be used. These mechanisms are not as powerful as SOAP, but they can
module. be used by all HTTP clients. SOAP supports extra functionality, including
passing classes, datasets, and by-reference parameters to a Web Service.
 Messages defined by Web Services Description Language (WSDL)
Web Services must provide a contract that client applications can rely upon
to accurately describe the service’s methods and their arguments. WSDL is
an XML-based way to describe the contract information that can be read by
all client applications that can work with XML.
44 Module 7: Building Web Applications

 Service descriptions available through discovery


The discovery specification describes a standard way for service providers
to publish Web Service contracts. It also describes how developers and
developer tools can discover these contract documents.
 Universal Discovery Description and Integration (UDDI)
The need to locate available services for an entire industry or individual
company has led to the UDDI project, which creates a framework for Web
Service integration by providing a distributed directory of Web Services.
This distributed directory enables registration and discovery of Web
Services through an assortment of predefined SOAP messages.
Module 7: Building Web Applications 45

Creating a Web Service


Topic Objective
To discuss how to create a
Web Service. 1. Add a Web Service module to the project
Lead-in  The .asmx file contains WebService directive
Creating a Web Service is
easy in Visual Basic .NET. <%@
<%@ WebService
WebService Language="vb"
Language="vb" Codebehind="User.asmx.vb"
Codebehind="User.asmx.vb"
Class="WebApp.User"%>
Class="WebApp.User"%>

2. Create a Web Service description


3. Add public subroutines or functions to .asmx.vb file
 Add WebMethod attribute to procedure definitions
<WebMethod()>
<WebMethod()> Public
Public Function
Function AddUser(…)
AddUser(…) As
As String
String
'Functionality
'Functionality to add a user and return new ID
to add a user and return new ID
Return
Return strNewId
strNewId
End Function
End Function

*****************************ILLEGAL FOR NON-TRAINER USE******************************


To create a Web Service in Visual Basic .NET, use the following process:
Delivery Tip
Ask students for examples 1. Add a Web Service module to your project.
of Web Services that they
could create for their current 2. Create a Web Service description.
server applications. 3. Add public subroutines and functions to the module, and add the
Suggestions include: WebMethod attribute to the procedure definitions.
1. E-commerce applications
with ordering and shipping. 4. Create the remaining code as usual.
2. Application integration
between existing
applications. What Is a Web Service Module?
3. Workflow solutions that A Web Service module uses the .asmx file extension and is made up of two
incorporate Microsoft files—the .asmx file and the .asmx.vb file—similar to the composition of a
BizTalk™ Server 2000 for Web Form.
document exchange.
 The .asmx file
The .asmx file simply contains the WebService directive that specifies the
language in which the developer wrote the code, the name of the code file,
and the name of the class that you use when referencing the service.
The following example declares a service named User written in
Visual Basic .NET, using the User.asmx.vb module for the code, in the
WebApp namespace.
<%@ WebService Language="vb" Codebehind="User.asmx.vb"
Class="WebApp.User" %>

 The .asmx.vb file


The .asmx.vb file contains the code that executes when you invoke a Web
Service method as if it were a regular class definition. The class inherits
from the System.Web.Services.WebService class and provides direct
access to common ASP.NET objects such as Application, Server, Session,
and User.
46 Module 7: Building Web Applications

Creating a Web Service Description


You can create a description for your Web Service by using the WebService
attribute in the class definition and specifying the Description parameter, as
shown in the following example. This information will be visible when the Web
Service URL is entered in a browser.
<WebService(Namespace:="http://tempuri.org/", _
Description:="Provides user details.")> _
Public Class User
Inherits System.Web.Services.WebService
...
End Class

Note Inheriting from System.Web.Services.WebService is not a requirement


for a Web Service to work.

Delivery Tip Adding Public Subroutines or Functions


Point out the ways to add
You can create procedures for the Web Service class by using standard method
descriptions for the service
and individual methods, as
syntax for either subroutines or functions. In order for these methods to be used
they are not mentioned in as Web Services, you must mark them as public and use the WebMethod class
the slide. attribute. The following example shows how to create a function that can be
accessed through a Web Service:
<WebMethod( )> Public Function AddUser(ByVal strName As _
String) As String
'Functionality to add a user and return new ID
...
Return strNewId
End Function

<WebMethod( )> Public Sub DeleteUser(ByVal strId As String)


'Functionality to delete a user based on ID
...
End Sub

You can add a description for each method by specifying the Description
argument of the WebMethod attribute, as shown in the following example:
<WebMethod(Description:="This method performs an action")> _
Public Sub PerformAction( )
...
End Function

Tip If you already have components that you want to convert to Web Services,
you can simply create a wrapper Web Service module that calls your
preexisting components and returns any results.
Module 7: Building Web Applications 47

Enabling Web Service Discovery


Topic Objective
To explain the process of  Discovery document
Web Service discovery.
 Enables location and interrogation of Web Service
Lead-in descriptions
A Web Service is useless if
no one knows it is available.  Contains links to resources that describe services
 Stores information in XML format
 Created manually or dynamically
<?xml
<?xml version="1.0"
version="1.0" ?>
?>
<discovery
<discovery xmlns="http://schemas.xmlsoap.org/disco/"
xmlns="http://schemas.xmlsoap.org/disco/" ...>
...>
<contractRef
<contractRef ref="http://www.nwtraders.msft/Shopping/User.asmx?wsdl"
ref="http://www.nwtraders.msft/Shopping/User.asmx?wsdl"
docRef="http://www.nwtraders.msft/Shopping/User.asmx"
docRef="http://www.nwtraders.msft/Shopping/User.asmx"
xmlns="http://schemas.xmlsoap.org/disco/wsdl/"
xmlns="http://schemas.xmlsoap.org/disco/wsdl/" />
/>
...
...
</discovery>
</discovery>
*****************************ILLEGAL FOR NON-TRAINER USE******************************
A Web Service is not very useful if other developers do not know that the
Delivery Tip service exists. Locating and interrogating Web Services is known as discovery.
The slide shows a dynamic
discovery document as
It is through the discovery process that client applications learn that a Web
explained in the student Service exists, what its capabilities are, and how to properly interact with it.
notes.
What Is a Discovery Document?
You can programmatically discover a Web Service if it publishes a discovery
document. This file contains links to other resources that describe each Web
Service, such as WSDL documents. The discovery document uses XML format,
so any client application can read this document.

Manually Creating a Discovery Document


You can create a discovery document by using any XML editor, as is shown in
the following example:
<?xml version="1.0" ?>
<disco:discovery
Delivery Tip xmlns:disco="http://schemas.xmlsoap.org/disco"
Point out that discovery is
xmlns:WSDL="http://schemas.xmlsoap.org/disco/WSDL">
not required for a Web
Service to work, and that <WSDL:contractRef
you may not want to use a ref="http://WebServerName/User.asmx?WSDL"/>
discovery document if you <disco:discoveryRef ref="SomeFolder/default.disco" />
want to keep your services </disco:discovery>
private.
Using this type of discovery document, you can explicitly expose only those
Web Services that you want to be publicly available. This type of discovery
document uses the .disco file extension.
48 Module 7: Building Web Applications

Creating a Dynamic Discovery Document


Alternatively, you can create a dynamic discovery document that will look up
the Web Services under a given virtual directory when queried by a client
application. This is the type of discovery document that Visual Studio .NET
creates automatically and that uses the .vsdisco file extension, as shown in the
following example:
<?xml version="1.0" encoding="utf-8" ?>
<dynamicDiscovery
xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17">
<exclude path="_vti_cnf" />
<exclude path="_vti_pvt" />
<exclude path="_vti_log" />
<exclude path="_vti_script" />
<exclude path="_vti_txt" />
<exclude path="Web References" />
</dynamicDiscovery>

You can use this type of discovery document to exclude particular folders from
the dynamic discovery process. The folders excluded in the previous example
are those used for Microsoft FrontPage® Extensions and any Web references
used by the project, but you can manually list as many folders as you want.
The preceding dynamic discovery document will produce the following results
when queried by a client application:
<?xml version="1.0" encoding="utf-8"?>
<discovery xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.xmlsoap.org/disco/">
<contractRef ref="http://www.nwtraders.msft
/Shopping/User.asmx?WSDL"
docRef="http://www.nwtraders.msft/Shopping/User.asmx"
xmlns="http://schemas.xmlsoap.org/disco/scl/" />
<soap address="http://www.nwtraders.msft/Shopping/User.asmx"
xmlns:q1="http://tempuri.org/ binding="q1:Service1Soap"
xmlns="http://schemas.xmlsoap.org/disco/soap/" />
</discovery>

Note A discovery document is not required for creating a Web Service.


Another site could be used to describe the service, or there may not be a
publicly available means of finding the service if it is only intended for private
use.
Module 7: Building Web Applications 49

Deploying and Publishing a Web Service


Topic Objective
To explain how to deploy
and publish a Web Service.
Lead-in  Deploying a Web Service
Deploying and publishing a  Copy .asmx, Web.config, and any components to an IIS
Web Service is a simple
process.
virtual directory
 Publishing a Web Service
 The discovery document is copied to IIS virtual directory
 Dynamic discovery document produced by ASP.NET
generates information for all services in all subfolders
 Manually created discovery document returns only
explicitly defined information

*****************************ILLEGAL FOR NON-TRAINER USE******************************


Once you create your Web Service, you can deploy it to a Web server and then
publish it.

Delivery Tip Deploying a Web Service


Ensure that students have a
You can deploy a Web Service by copying the various files to an IIS virtual
basic understanding of how
IIS and virtual directories
directory. These files should include:
work. Demonstrate these  Web Service files
processes if appropriate.
Copy only the .asmx files because the .asmx.vb files are included in your
compiled assembly.
 Configuration file
Copy the Web.config configuration file.
 Internal assemblies
Include all .dll files required to perform the services.
 External assemblies
Include any external assemblies not supplied by the .NET Framework.

Publishing a Web Service


If you want to publish your Web Service, you can copy the discovery document
to the root of the IIS virtual directory. If you are using the dynamic discovery
file produced by ASP.NET, this will return the details of all Web Services
contained in the root directory and any subdirectories. If you manually create
the discovery document, it will return only the information explicitly contained
in the file.
You can then choose how to direct your users to your discovery document. You
could do this by adding a link from your home page or by making the discovery
document the default page. However, you may not want to make your discovery
document publicly available, in which case you can implement alternate ways
of providing access to this file.
50 Module 7: Building Web Applications

Demonstration: Creating a Web Service


Topic Objective
To demonstrate how to
create a Web Service.
Lead-in
This demonstration shows
how to create a simple Web
Service and how to add
descriptions to the service
and its methods.

*****************************ILLEGAL FOR NON-TRAINER USE******************************


In this demonstration, you will learn how to create a simple Web Service and
Delivery Tip add descriptions to the service and its methods.
The step-by-step
instructions for this
demonstration are in the
instructor notes for this
module.
Module 7: Building Web Applications 51

 Using Web Services


Topic Objective
To provide an overview of
the topics covered in this
lesson.  Exploring Web Services
Lead-in  Invoking a Web Service from a Browser
Web Services are a key
component of the .NET  Invoking a Web Service from a Client
Framework. In this lesson,
you will learn how to
discover and use a Web
Service from a client
application.

*****************************ILLEGAL FOR NON-TRAINER USE******************************


Web Services are an important component of the .NET Framework.
Visual Basic .NET–based client applications enable you to easily discover and
use Web Services.
After you complete this lesson, you will be able to:
 Discover and interrogate a Web Service by using discovery and WSDL
documents.
 Call a Web Service from an Internet browser.
 Pass the service parameters to a Web Service.
 Reference a discovery document from Visual Basic .NET.
 Create client code that interacts with the Web Service.
52 Module 7: Building Web Applications

Exploring Web Services


Topic Objective
To explain how to access
information about a Web
Service.  HTML description page
Lead-in  Describes Web Service methods and arguments
You can access information
about Web Services in the  Provides simple test utility for methods
HTML description page.
 Displays additional descriptions from attributes
 Appears when you enter Web Service URL
http://webservername/virtualdirectory/webservice.asmx
http://webservername/virtualdirectory/webservice.asmx

 WSDL describes methods, arguments, and responses


 Generated by using Web Service URL with ?WSDL
switch

*****************************ILLEGAL FOR NON-TRAINER USE******************************


Exploring Web Services involves looking at two parts of the system: the HTML
description page and the WSDL document.

What Is the HTML Description Page?


The HTML description page is automatically generated when you call a Web
Service without specifying a particular method to execute. The HTML
description page provides the following:
 Web Service methods and arguments
The page contains links that describe the methods and arguments that make
up the Web Service.
 Simple test utility for methods
The links include test facilities for each method, in which you can input
each parameter through a text input field. When you enter values in the text
input fields and click the Invoke button, the Web Service executes and
displays any results in XML format. This facility is only provided for
methods that do not include any by-reference parameters because HTTPGet
and HTTPPost are the protocols used to process this page’s requests.
 Additional descriptions from attributes
Additional information about each method can be displayed if the developer
has specified the Description parameter for the WebMethod attribute of a
method, or for the WebService attribute of the class.
Module 7: Building Web Applications 53

You can view the description page by entering the Web Service URL in a
browser by using the following syntax:
http://webservername/virtualdirectory/webservice.asmx

You can also view the description page within Visual Studio .NET by right-
clicking the .asmx file in Solution Explorer, and then clicking View In
Browser.
Near the top of the HTML description page, there is also a “Service
Description” hyperlink to the WSDL document.

What Is a WSDL Document?


A WSDL document uses XML to define the syntax and parameters of the
available methods of a Web Service. This document is created automatically
when you add the ?WSDL switch to the Web Service URL, as shown in the
following example:
http://webservername/virtualdirectory/webservice.asmx?WSDL

It is possible to read and interpret the WSDL document, but it is not necessary
to understand the document to use a Web Service.
54 Module 7: Building Web Applications

Invoking a Web Service from a Browser


Topic Objective
To explain how to invoke a
Web Service from a
browser.  Enter the URL for the Web Service with parameters
Lead-in  Syntax:
Invoking a Web Service
from a browser is a http://webservername/vdir/webservicename.asmx/
straightforward process. MethodName?parameter=value
 Example:
http://www.nwtraders.msft/Shopping/User.asmx/AddUser?strName=Joe
http://www.nwtraders.msft/Shopping/User.asmx/AddUser?strName=Joe

*****************************ILLEGAL FOR NON-TRAINER USE******************************


You invoke a Web Service from a browser by entering the URL of the service,
specifying the method name to run, and specifying any parameter values.

Syntax
You use the following syntax to invoke a Web Service:
http://webservername/vdir/webservicename.asmx/
MethodName?parameter=value

Example
The following example shows how to invoke a Web Service. This code calls the
AddUser method of the User.asmx Web Service in the Shopping virtual
directory on the nwtraders.msft Web server. It also passes in a parameter value
of the user name Joe.
http://www.nwtraders.msft/Shopping/User.asmx/
AddUser?strName=Joe

The Web Service will return XML output containing the results of the
execution as shown in the following example. The results show a String value
of 43-124-21 being returned as the new identity of the added user.
<?xml version="1.0" ?>
<string xmlns="http://tempuri.org/">43-124-21</string>

This approach uses the HTTP-GET protocol and would most commonly be
used for testing purposes; real application-to-application communication would
use the more powerful SOAP protocol.
Module 7: Building Web Applications 55

Invoking a Web Service from a Client


Topic Objective
To explain how to invoke a  Visual Basic .NET creates a proxy class for early
Web Service from a rich binding
client application.
 Steps required:
Lead-in
Invoking a Web Service 1. Add a Web reference
from a client application
created in 2. Enter the URL for the .asmx file
Visual Studio .NET is
a simple process. 3. Create client code that uses appropriate namespaces
Sub
Sub btnSubmit_Click(…)
btnSubmit_Click(…) Handles
Handles btnSubmit.Click
btnSubmit.Click
Dim
Dim usr As New Services.User() 'Services
usr As New Services.User() 'Services is
is the
the given
given namespace
namespace
MessageBox.Show(usr.AddUser(txtName.Text))
MessageBox.Show(usr.AddUser(txtName.Text))
End
End Sub
Sub

*****************************ILLEGAL FOR NON-TRAINER USE******************************


You can invoke a Web Service from a client application in several ways,
Delivery Tip depending on the client. If the client is written in Visual Basic .NET, you can
Remind students that early
binding allows the most
use the following process for either a Windows Forms or a Web Forms
efficient type of calls to a application:
component.
1. Add a Web reference to the Web Service.
2. Enter the URL for the .asmx file.
3. Create your client code for accessing a component. Use the appropriate
namespaces.

When you add a Web reference to your client project, Visual Basic .NET
creates a proxy class that hides the complexity of calling a Web Service. This
proxy allows you to use early binding when connecting to the service, as if the
components were accessible within a local assembly.
56 Module 7: Building Web Applications

Example
In the following example, the required Web Service has taken a Web reference,
and the Web reference has been renamed as the Services namespace. A
command button named btnSubmit and a TextBox named txtName have been
placed on a Windows Forms form with the following code for the
btnSubmit_Click event handler:
Private Sub btnSubmit_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnSubmit.Click
'Services is the given namespace
Dim usr As New Services.User( )
MessageBox.Show(usr.AddUser(txtName.Text))
End Sub

When the preceding code is executed, a new user is created. The txtName text
box specifies the name of the new user, and the AddUser method creates a
message box that displays the new identity.
Module 7: Building Web Applications 57

Demonstration: Using a Web Service


Topic Objective
To demonstrate how to use
a Web Service.
Lead-in
This demonstration shows
how to use Web Services
from both simple and rich
clients, including
Visual Basic .NET-based
applications.

*****************************ILLEGAL FOR NON-TRAINER USE******************************


In this demonstration, you will learn how to access a Web Service from a
Delivery Tip simple browser client as well as from a rich Visual Basic .NET-based,
The step-by-step
instructions for this
Windows-based application.
demonstration are in the
instructor notes for this
module.
58 Module 7: Building Web Applications

Multimedia: How Web Services Work


Topic Objective
To introduce the How Web
Services Work animation.
Lead-in
This animation describes
how rich clients, such as
Visual Basic .NET-based
applications, can use Web
Services.

*****************************ILLEGAL FOR NON-TRAINER USE******************************


In this animation, you will see how you can use Web Services in your
Delivery Tip Microsoft Visual Basic .NET–based applications, how the Web Services
To start the animation, click
the animation icon in the
Description Language provides information about the Web Services, and how
slide. The step-by-step Visual Basic .NET uses SOAP to create proxies.
instructions for showing this
multimedia animation are in Script: How Web Services Work
the instructor notes for this
module.
A bride can plan every detail of her wedding, but if she is planning to change
her name, she might not be prepared for how complicated that can be.
At her job, how many phone calls do you think she will need to make to get her
name changed? How many internal and external Web sites do you think she
will need to update? How many hours of unproductive work do you think she
will spend, just to make the name change?
She needs to change her e-mail alias and contact payroll. She needs to change
her name with her health insurance company. She also needs to order new
business cards. All these different vendors use different platforms.
Imagine how astonished she will be to find out that she only needs to enter her
new information one time! How is that possible? It is possible because of Web
Services. Web Services are applications that are remotely activated over the
Web by a simple XML or SOAP-based message.
Here is how it works: An astute developer at her company built a portal based
on Web Services that aggregates all employee services. Web Services allow
client applications to access business logic by using Internet protocols, which
means that any business can interact with any other business without
encountering problems related to company-specific protocol.
When the Visual Basic .NET–based application running on this client needs to
use a Web Service, it uses a process called discovery to find out what services
are available from a specific company. To provide this flexible approach,
certain details must be provided by the Web Service in a discovery document.
Module 7: Building Web Applications 59

A discovery document contains information in XML format about one or


more Web sites that provide Web Services. The document contains URL
links to descriptive documents or contracts for a specific Web Service.
Visual Basic .NET automatically creates a discovery document when you create
a Web Service. The client application uses the discovery document to locate
individual services and contracts.
With this information, the client can explore the contract documents to find the
requirements of the Web Service methods. These contracts are also in XML
format, but they follow specific standards that have been established to describe
the methods, arguments, and return values of a Web Service.
ASP.NET uses the Web Services Description Language, or WSDL, to describe
the services available. WSDL documents describe the details of each method
for three different protocols: HTTP-Get, HTTP-Post, and the Simple Object
Access Protocol (SOAP).
From these requirements, the Visual Basic .NET client automatically constructs
a proxy class to ease communication between the developer’s client code and
the service. Visual Basic .NET applications use the SOAP method descriptions
when creating this proxy. SOAP supports some enhanced features such as by-
reference parameters and the ability to pass objects, structs, and ADO.NET
DataSets.
The Visual Basic .NET client application can then call the proxy class as if it
were talking directly to the real service. In fact, the proxy hides all of the
network communications.
The proxy then makes requests to the Web Service, passing any parameters
across the Internet as SOAP messages. The Web Service processes the
incoming request and performs the required action. If values need to be sent
back to the client, the Web Service creates these values and returns them as
SOAP messages.
The message is received by the proxy and converted into .NET base types that
the Visual Basic .NET client can work with. This layer of abstraction allows
developers to work with a Web Service as if it were a component running
locally to the client.
So, using Web Services, the Web server receives XML messages by means of
ASP.NET. The Web server activates Web Service functions using SOAP, and
the name change tasks are performed.The newlywed will be able to enter her
name in one location that:
 Uses the discovery process to find out what services are available.
 Uses the ASP.NET WSDL to define methods to call, the address of the
SOAP endpoint, schemas for SOAP messages and responses, and the data
types returned.
 Creates a proxy client class.

In this animation, you saw how you can use Web services in your
Visual Basic .NET applications, how the Web Service Description Language
provides information about the Web service, and how Visual Basic .NET uses
SOAP to create proxies.
60 Module 7: Building Web Applications

Lab 7.2: Creating and Using the CustomerService Web


Service
Topic Objective
To introduce the lab.
Lead-in
In this lab, you will create a
simple Web Service and
then access the service by
using a browser and a
Visual Basic .NET-based
application.

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Explain the lab objectives.


Objectives
After completing this lab, you will be able to:
 Create Web Services.
 Consume Web Services from a rich client.

Prerequisites
Before working on this lab, you must be familiar with creating Web Services in
Visual Basic .NET.

Scenario
In this lab, you will create a Web Service that allows retrieval and storage of
customer details. You will also create a Windows Forms application to test the
Web Service methods. Web Services are often used by other Web Services or
Web Form applications. A Windows Forms application will be used as the test
application in this lab to contrast using a class from a form with using a Web
Service from a form.
The Customer class from Lab 5.1, Creating the Customer Class, of Course
2373B, Programming with Microsoft Visual Basic .NET, is provided and will
be used as a basis for the Web Services application to replicate data retrieval
and storage. The test form from the same lab has been modified and supplied to
test these lab exercises.
Module 7: Building Web Applications 61

Starter and Solution Files


There are starter and solution files associated with this lab. The starter files are
in the install folder\Labs\Lab072\Ex0x\Starter folder, and the solution files are
in the install folder\Labs\Lab072\Ex0x\Solution folder (where x is the exercise
number).

Estimated time to complete this lab: 45 minutes


62 Module 7: Building Web Applications

Exercise 1
Creating the CustomerService Web Service
In this exercise, you will create the CustomerService Web Service and define its
methods.

 To open the starter project


1. Open Visual Studio .NET.
2. On the File menu, point to Open, and click Project.
3. Set the folder location to install folder\Labs\Lab072\Ex01\Starter, click
Ex01.sln, and then click Open.

 To create the CustomerService Web Service


1. On the Project menu, click Add Web Service. Rename the item
CustomerService.
2. Open the Code Editor for CustomerService.asmx, locate the Public Class
CustomerService definition, and then modify the WebService attribute to
include the following Description parameter value:
Stores and retrieves Customer information.

3. Verify that the class definition now looks as follows:


<WebService(Namespace:="http://tempuri.org/", _
Description:="Stores and retrieves Customer information." _
)> Public Class CustomerService

 To define the Web Service methods


1. On the File menu, point to Open, and then click File.
2. In the Files of type box, click Text Files.
3. Set the folder location to install folder\Labs\Lab072\Ex01\Starter, click
Code.txt, and then click Open.
4. Copy all of the code in Code.txt into the Web Service class definition in
CustomerService.asmx.
5. Examine each of the three methods to ensure that you understand the
purpose of the code.
6. Add the WebMethod attribute to each of the three method definitions. This
will change them from standard methods into Web Service methods.
7. Add the following descriptions to each WebMethod attribute, using the
same syntax as that used for the WebService attribute shown in step 3 of
the previous procedure.
Method Description

AddCustomer Adds a customer to the system.


GetDetails Retrieves customer details based on the Customer ID.
LogOn Retrieves customer details based on logon details.
Module 7: Building Web Applications 63

 To test the Web Service


1. Build the project.
2. In Solution Explorer, right-click CustomerService.asmx, and then click
View in Browser to display the HTML description page.
3. Click the Service Description hyperlink and examine the WSDL document.
4. Click the Back button on the Web toolbar to move back to the HTML
description page.
5. Click the hyperlink for each method of the Web Service to view the method
details. Note that you can only test the AddCustomer method from this
page because it is the only method that does not use by-reference
parameters.
6. Test the AddCustomer method by entering any information for the input
fields and then clicking Invoke. View the XML results to confirm that the
value 1200 was generated and returned.
64 Module 7: Building Web Applications

Exercise 2
Creating the LogOn Test Code
In this exercise, you will test the LogOn method of the Web Service from a
simple form.

 To open the starter project


1. On the File menu, point to Open, and then click Project.
2. Set the folder location to install folder\Labs\Lab072\Ex02\Starter, click
Ex02.sln, and then click Open.

 To create the Web reference


1. On the Project menu, click Add Web Reference.
2. Type
http://localhost/2373/Labs/Lab072/Ex01/Starter/CustomerService.asmx
in the Address box, and then click Go.
3. When the discovery document information is displayed, click Add
Reference.
4. In Solution Explorer, rename localhost as Services to provide an appropriate
namespace.

 To add the test code for the Logon method


1. In frmLogon.vb, locate the btnLogon_Click event handler.
2. Declare and instantiate a Services.CustomerService variable named
cusCustomer.
3. Call the LogOn method of the cusCustomer object, using the following
parameters.
Parameter Value

strEmail txtEmail.Text
strPassword txtPassword.Text
intID intId
strFName strFName
strLName strLName
strAddress strAddress
strCompany strCompany
Module 7: Building Web Applications 65

4. Assign the following values to the text boxes following the call to the
LogOn method.
Text box Value

txtID CStr(intId)
txtFName strFName
txtLName strLName
txtAddress strAddress
txtCompany strCompany

5. Destroy the cusCustomer reference by using the Nothing keyword.


6. Save the project.

 To test the LogOn code


1. On the Debug menu, click Start.
2. Click the Test ‘Logon’ button to display the test form.
3. Enter the following values in the appropriate text boxes.
Text box Value

E-mail [email protected]
Password password

4. Click the Logon button and confirm that the customer information is
displayed correctly in the text boxes.
5. Close the application.
66 Module 7: Building Web Applications

Exercise 3
Testing the GetDetails Procedure
In this exercise, you will test the GetDetails Web Service method from the test
form. Continue working with the project from the previous exercise. If you did
not complete the previous exercise, you can use the Ex03.sln project located in
the install folder\Labs\Lab072\Ex03\Starter folder.

 To add the test code for the GetDetails method


1. In frmRetrieve.vb, locate the btnRetrieve_Click event handler.
2. Declare and instantiate a Services.CustomerService variable named
cusCustomer.
3. Call the GetDetails method of the cusCustomer object, using the following
parameters. Note that all parameters except for intID are by reference, so
values are returned from the method.
Parameter Value

intID CInt(txtID.Text)
strEmail strEmail
strPassword strPassword
strFName strFName
strLName strLName
strAddress strAddress
strCompany strCompany

4. Assign the following values to the text boxes following the call to the
GetDetails method.
Text box Value

txtEmail strEmail
txtPassword strPassword
txtFName strFName
txtLName strLName
txtAddress strAddress
txtCompany strCompany

5. Destroy the cusCustomer reference by using the Nothing keyword.


6. Save the project.
Module 7: Building Web Applications 67

 To test the Retrieve code


1. On the Debug menu, click Start.
2. Click the Test ‘Get Details’ button to display the test form.
3. Enter the value 1119 in the CustomerID text box, and then click the
Retrieve button.
4. Confirm that your code retrieves the customer information and displays it
correctly in the text boxes.
5. Close the application.
68 Module 7: Building Web Applications

Exercise 4
Testing the AddCustomer Procedure
In this exercise, you will test the AddCustomer Web Service method from the
test form. Continue working with the project from the previous exercise. If you
did not complete the previous exercise, you can use the Ex04.sln project located
in the install folder\Labs\Lab072\Ex04\Starter folder.

 To add the test code for the AddCustomer method


1. In frmNew.vb, locate the btnNew_Click event handler.
2. Declare and instantiate a Services.CustomerService variable named
cusCustomer.
3. Call the AddCustomer method of the cusCustomer object and display the
return value in a message box. Use the following values for the parameters
of the AddCustomer method.
Parameter Value

strEmail txtEmail.Text
strPassword txtPassword.Text
strFName txtFName.Text
strLName txtLName.Text
strAddress txtAddress.Text
strCompany txtCompany.Text

4. Destroy the cusCustomer reference by using the Nothing keyword.


5. Save the project.

 To test the AddCustomer code


1. On the Debug menu, click Start.
2. Click the Test ‘New Customer’ button to display the test form.
3. Enter values in all the text boxes.
4. Click the New Customer button, and confirm that an ID is displayed in the
message box. Note that adding customers does not actually add a customer
to the system, because this part of the application is hard-coded.
5. Close the application.
Module 7: Building Web Applications 69

If Time Permits
Using a Web Service from a Web Application
In this optional exercise, you will use the Web Service from a Web application.

 To open the starter project


1. Open Visual Studio .NET.
2. On the File menu, point to Open, and then click Project.
3. Set the folder location to install folder\Labs\Lab072\Ex05\Starter, click
Ex05.sln, and then click Open.
4. In the Solution Explorer, right-click Logon.aspx and click Set As Start
Page.
5. View Logon.aspx in the design window and then Logon.aspx.vb in the Code
Editor to understand what functionality the Web Form provides.

 To create the Web reference


1. On the Project menu, click Add Web Reference.
2. Enter
http://localhost/2373/Labs/Lab072/Ex01/Starter/CustomerService.asmx
in the Address box, and then click Go.
3. When the discovery document information is displayed, click Add
Reference.
4. In Solution Explorer, rename localhost as Services to provide an appropriate
namespace.

 To add the test code for the LogOn method


1. Locate the btnSubmit_Click event handler.
2. In the line before the Try...Catch...Finally code block, declare and
instantiate a Services.CustomerService variable named cusCustomer.
3. Inside the Try block, call the LogOn method of the cusCustomer object,
using the following parameters.
Parameter Value

strEmail txtEmail.Text
strPassword txtPassword.Text
intID intID
strFName strFName
strLName strLName
strAddress strAddress
strCompany strCompany

4. Assign the user name to the Session object, as follows:


Session("User_FullName") = strFName & " " & strLName
70 Module 7: Building Web Applications

5. Redirect the user to the Welcome.aspx Web Form, as follows:


Response.Redirect("Welcome.aspx")

6. Save the project.

 To test the LogOn code


1. On the Debug menu, click Start.
2. Enter the following values in the appropriate text boxes.
Textbox Value

E-mail [email protected]
Password karen

3. Click the Submit button to confirm that the error message is displayed.
4. Enter the following values in the appropriate text boxes.
Textbox Value

E-mail [email protected]
Password password

5. Click the Submit button, and confirm that the correct name is displayed on
the Welcome page.
6. Close the browser and Visual Studio .NET.
Module 7: Building Web Applications 71

Review
Topic Objective
To reinforce module
objectives by reviewing key
points.  Introduction to ASP.NET
Lead-in  Creating Web Form Applications
The review questions cover
some of the key concepts  Building Web Services
taught in the module.
 Using Web Services

*****************************ILLEGAL FOR NON-TRAINER USE******************************


1. Describe some of the features of ASP.NET.
Compiled code, multiple browser clients, session state that supports
Web farms, and easy deployment.

2. Explain why updates to an ASP.NET application do not require you to


restart IIS.
No items are locked by IIS, so updating does not require you to restart
IIS.

3. Create a line of code that uses the Response object to retrieve a userCounter
session variable and display it to the user.
Response.Write("Value: " & Session("userCounter").ToString)

4. Convert the following HTML control tag into a server-side control.


<input type=text id=mytext value="hello">

<input type=text id=mytext value="hello" runat=server>


72 Module 7: Building Web Applications

5. What attribute do you add to class methods when creating a Web Service?
WebMethod.

6. Visual Basic .NET allows early binding to a Web Service. True or false?
True. Setting a Web reference to a discovery document allows
Visual Basic .NET to create a proxy class that allows early binding in
the client application.

You might also like