ASP.NET Workbook

potpiedicedInternet and Web Development

Jul 5, 2012 (5 years and 1 month ago)

1,825 views



ASP.NET Workbook
Hands-On Exercises for the Beginner








Heng Ngee Mok












1st Edition
(with minor corrections made)
Version 1.1 (Feb 2004)

The 1
st
edition of this book has been published by Prentice Hall
Publishing (Pearson Education) (Singapore) in December 2003



You can download the latest edition of this book at
http://www.mokhengngee.per.sg/book

www.mokhengngee.per.sg/book

ii
Acknowledgements


I would like to acknowledge my colleagues whose keen spirit of sharing has
helped me in my foray into ASP.NET. They are, in no particular order of merit,
Law Chee Yong and Ouyang Yin Ming, the real ASP.NET experts here at the
School of IT. Special thanks must be given to Daniel Wee, who has been a truly
nice boss. I must also mention Serena Goh, Sarah Chong and Adrian Png,
without whom, my lunch hours would have been plain and uneducational
experiences.


Errata


Readers can view the latest erratum list at www.mokhengngee.per.sg/book.
Additional exercises which could not make it in time for this edition shall also
be posted there.



ASP.NET Workbook
iii
Preface

In the spirit of communal sharing, I have decided to make the text of this
workbook available to all developers in Singapore and around the world.
Readers are free to download the PDF format of this text, and use for non-profit
educational purposes. Readers are obliged to acknowledge the source (i.e. this
book/author) where appropriate. Please do not modify the contents of this
document, or re-distribute it in any form. Instead, please direct your friends to
the ‘official’ download Web site. The latest corrected version of this book can
always be found at http://www.mokhengngee.per.sg/book. ‘Book bug’ reports
are also always appreciated at mok@ieee.org.

I wish you a pleasant adventure with ASP.NET :)

H.N. Mok
February 2004
Singapore



Preface to the Original Edition


This book has been prepared to support the curriculum of the IT1202 (Web
Application Development) module, which year 1 Diploma in IT students are
required to complete at Nanyang Polytechnic. This guide for practical exercises
is not meant to be a stand-alone manual, but to be complimented with
lecture/tutorial materials and reference books on ASP.NET.

This being a workbook for my students at the School of IT, I would like to
dedicate this book, and (hopefully) all the knowledge that they could gain from
it, to all my wonderful students. May they have a memorable experience at
NYP, and may the spirit of learning be forever with them!

Please do send any comments or (constructive) criticisms on the lab exercises
presented here to mok@ieee.org.

H.N. Mok
December 2003
Singapore

www.mokhengngee.per.sg/book

iv
Prerequisites


This book assumes that the following software requirements have been met by
your PC:

Operating system: Windows XP Professional, Windows 2000 Professional
(SP3 or later required), Windows 2000 Server (SP3 or later required) or
Windows Server 2003.

Windows Me and XP Home won’t do: You can install VS.NET on
Windows XP Home edition, but you cannot create ASP.NET or Web
service applications. And if you are still running on Windows 9x, it’s
high time to upgrade!

Visual Studio .NET 2003
You can also follow the exercises using Visual Studio .NET 2002.
However there might be minor differences in the user interface and steps
to be taken.

Backward compatibility: Note that VS.NET 2003 is not ‘backward
compatible’ with VS.NET 2002; a project or solution created using
VS.NET 2002 can be opened in VS.NET 2003, but thereafter cannot be
opened using VS.NET 2002 again.

The reason is because VS.NET 2003 uses the newer .NET Framework
version 1.1 compared to VS.NET 2002, which uses .NET Framework 1.0.
When a VS.NET 2002 project is opened in VS.NET 2003, the project
will be automatically converted to consume classes from the newer .NET
Framework. A VS.NET 2003 project or solution thus cannot be opened in
VS.NET 2002. Be wary of this limitation if you have different versions of
VS.NET installed at home or in your lab.


Microsoft Access XP (2002) or 2003
For the ADO.NET exercises, you will need to create an Access database.

Windows Administrator rights
o If VS.NET is not yet installed on your PC, you will need administrator
rights to do so.

ASP.NET Workbook
v
o You will also need enough rights to execute the IIS Manager (see
figure 0-1). You should be able to see the IIS Manager icon by
selecting the ‘Administrative Tools’ icon in the Control Panel.


Figure 0-1: You should be able to execute IIS Manager in order to try out
the exercises.



www.mokhengngee.per.sg/book

vi
Contents

1: Hosting Web Pages on IIS................................................................................1

Ex 1.1: Writing a Simple Web Page & Hosting it on IIS.................................1

Ex 1.2: Creating a Virtual Directory with IIS..................................................5

Ex 1.3: Hosting a Simple ASP.NET Web Page on IIS.....................................9

Ex 1.4: IIS Access Right Settings (optional)..................................................15

2: ASP.NET Web Forms....................................................................................21

Ex 2.1: Introducing the VS.NET IDE.............................................................21

Ex 2.2: Writing a Simple Web Page and Understanding Event Handlers.....35

Ex 2.3: Understanding Code-Behind Pages....................................................46

Ex 2.4: Creating a More Complex Web Form with Other Server Controls...49

3: Validator Controls..........................................................................................55

Ex 3.1: Simple Validator Controls..................................................................55

Ex 3.2: Other Validator Controls....................................................................62

4: State Management..........................................................................................69

Ex 4.1: State Management Using the Session and Application Objects........70

Ex 4.2: Using Cookies....................................................................................81

Ex 4.3: Using Global.asax.......................................................................87

Ex 4.4: Extracting Parameters from Web.config Programmatically.........91

Ex 4.5: Tracing your Web Application ..........................................................93

5: ADO.NET.......................................................................................................96

Ex 5.1: Using the DataTable Class............................................................96

Ex 5.2: Reading from the Database and Using the DataReader Class....100

Ex 5.3: Performing Simple CRUD Operations............................................112

6: Web Services................................................................................................122

Ex 6.1: Creating a Web Service Provider.....................................................122

Ex 6.2: Creating a Web Service Consumer..................................................129

Ex 6.3: Consuming Web Services from Google (optional)..........................138

Ex 6.4: Consuming Web Services from Amazon (optional)........................139

7: Site Security..................................................................................................141

Ex 7.1: Web Form Authentication using Web.config.............................141



1: Hosting Web Pages on IIS

In this chapter, you will be hosting simple static HTML and dynamic ASP.NET Web
pages on IIS without using Visual Studio.NET.

There are 4 exercises in this chapter:
• Exercise 1.1: Writing a Simple Web Page & Hosting it on IIS
• Exercise 1.2: Creating a Virtual Directory with IIS
• Exercise 1.3: Hosting a Simple ASP.NET Web Page on IIS
• Exercise 1.4: IIS Access Right Settings (optional)


Introducing IIS

Microsoft has 2 primary Web servers for hosting Web applications: Personal Web Server
(PWS) and Internet Information Server (IIS). PWS is a lightweight Web server for non-
industrial usage, and comes with the old Windows NT Workstation 4.0. IIS 6.0 is the
latest industrial-strength Web server.

Windows XP Professional comes with IIS 5.1, while XP Home doesn’t come with any
Web server. If you are running on Windows Server 2003, IIS 6.0 shall be installed.

IIS 6 boasts of an improved architecture, and is a great improvement over previous
versions, though most of the changes are not really visible to the user. For this course, we
shall be using either IIS 5.1 or 6.0.


Exercise 1.1
Writing a Simple Web Page & Hosting it on IIS

Welcome to the world of ASP.NET! In this very first exercise, you will write a simple
static HTML file, and host it on the IIS Web server. There’s nothing dynamic or
mysterious – but this exercise shall serve as a good hand-warmer.

Objective:
• To host a simple Web page on IIS (and appreciate how easy it is to do so!)

Instructions:

1. Ensure that IIS has been properly installed and working.


www.mokhengngee.per.sg/book

2
Open up Internet Explorer and type the following URL in the Address field:
http://localhost
You should be able to see IIS’s default Web page (figure 1-2):


Figure 1-2: Default page of IIS 5.1 running on Windows XP Professional

If you see a 404 error instead (figure 1-3), it is likely that IIS hasn’t been properly
installed or the IIS process isn’t running, or that it is listening on another port instead
of port 80. You may want to seek assistance.


Figure 1-3: 404 error probably indicating that IIS isn’t installed or running, or
listening at another port instead of port 80.

2. Create the HTML file.

Create a new text file (using Notepad or any other text editor) called
MyFirstPage.html. Type in the following lines and save it in
c:\inetpub\wwwroot.

<HTML>
<BODY>

ASP.NET Workbook
3
Hello ASP.NET!
</BODY>
</HTML>


That’s it! We have hosted a static Web page called MyFirstPage.html on your
machine.


3. Try to access the hosted Web page from your local machine.

Typing the following URL in the Address field of IE:
http://localhost/MyFirstPage.html
You should be able to see the following page (figure 1-4).


Figure 1-4: Viola! Your first static Web page hosted on IIS.

What is localhost? localhost is the ‘common name’ for the ‘loopback
address’, or the reserved IP address 127.0.0.1. Basically it represents your own PC.
You are trying to access a Web page called MyFirstPage.html hosted on your
local PC. Instead of http://localhost/MyFirstPage.html, you could’ve
typed http://127.0.0.1/MyFirstPage.html; they would have meant the
same thing.

URL case sensitivity: Instead of http://localhost/MyFirstPage.html,
try http://localhost/myfirstpage.html. You will realise that IIS does
not generally bother about casing as far as URLs are concerned, unlike many Java
Web servers which are very particular about the correct casing in URLs.

wwwroot: c:\inetpub\wwwroot is the folder where IIS finds Web pages to
serve out to clients.




www.mokhengngee.per.sg/book

4
4. Test out your Web page from a remote client machine.

In an actual scenario, a user will be trying to access your Web page from a remote
client using a web browser. Get your PC’s IP address by typing ipconfig at the
DOS command prompt (figure 1-5).


Figure 1-5: You can use command line tool ipconfig.exe to check your IP
address.

Figure 1-5 shows that the current PC’s IP address is 172.20.46.45 (it will be a unique
number for each PC on the network).

Go to your friend’s PC and type the following URL in IE:
http://<yourIPaddress>/MyFirstPage.html
(Replace <yourIPaddress> with your own Web server’s IP address). You should
be able to see the same Web page on your friend’s PC.


ASP.NET Workbook
5


5. Create a new physical folder in wwwroot

Create a folder called colors in c:\inetpub\wwwroot. In colors, create a
few static HTML files which prints out some statement (suggestion: you can have
yellow.html, blue.html etc)

6. Access these static pages using a browser

Access these static Web pages from IE using the correct URL such as:
http://localhost/colors/yellow.html or
http://localhost/colors/blue.html

You will realise that you need to specify the folder structure all the way to the
HTML file’s name. If you want to view deep.html which is in
c:\inetpub\wwwroot\colors\water\masterpiece\myworks\, then
the URL shall be
http://localhost/colors/water/materpiece/myworks/deep.htm
l.



Exercise 1.2
Creating a Virtual Directory with IIS

The previous exercise shows how you can host your Web pages by placing them in a
folder in c:\inetpub\wwwroot. It is not always necessary to have to place all the
Web pages you want to host in this special folder, and in this exercise, you will learn
how to host Web pages placed in any other physical folder by using a virtual directory
mapping.

Objective:
• To understand what is a virtual directory and how it works

Instructions:

www.mokhengngee.per.sg/book

6

1. Create a physical folder

Create a folder called temp in c:\. In temp, create a few static HTML files which
prints out some statement (suggestion: you can have page1.html, page2.html
etc)


2. Create a virtual directory to map to the c:\temp folder.

Start IIS Manager (Start button  administrative tools  Internet Information
Server). Open up the (local computer) icon by double-clicking on it. Open up ‘Web
sites’, and you should be able to see the ‘Default Web site’ icon.

Right click on the ‘Default Web site’ icon and select ‘New’, followed by ‘Virtual
Directory’ (figure 1-6).


Figure 1-6: Create a virtual directory from IIS Manager

3. Run the Virtual Directory Creation Wizard

The Virtual Directory Creation Wizard will run. Click on ‘Next’ as instructed. When
you are asked to enter your virtual directory alias, key in a name and click ‘Next’. For
this example, ‘somepage’ is used as the virtual directory alias (figure 1-7).

Spaces in aliases: It is possible to select a name containing spaces for your alias,
although this is seldom done. This will mean that the URL specified to access your
Web page will also contain spaces.

ASP.NET Workbook
7


Figure 1-7: Select a name for your virtual directory.

4. Enter the physical path to the location of your Web pages.

The wizard will ask for the physical path to the folder which contains your Web
pages. Enter c:\temp or click on ‘Browse’ and select the temp folder. Click on
‘Next’ (figure 1-8).


Figure 1-8: Enter the path to the folder which contains your Web pages.


5. Keep the default access permission settings for your virtual directory

The wizard will ask you to set the access permissions for this virtual directory. For
now, just accept the default settings (i.e. with only ‘Read’ and ‘Run scripts’ checked)
and click ‘Next’. More about access permissions will be covered soon (figure 1-9).

www.mokhengngee.per.sg/book

8


Figure 1-9: Accept the default access permissions.

The wizard then shows a message to inform that you have successfully completed the
Virtual Directory Creation Wizard. Click on ‘Finish’.

What is a virtual directory? To understand what we have done so far, we need to
understand what is a virtual directory. A virtual directory is basically a ‘mapping’
between a physical folder and an alias. Instead of copying over the temp folder into
c:\inetpub\wwwroot (we could have done that too), we can create a ‘mapping’
of an alias (‘somepages’ in this example) to a physical folder (c:\temp). Hence
there is no need for all your Web page files to be placed in
c:\inetpub\wwwroot. All you need to do is to create a virtual directory
mapping and remember the alias you have selected.

In the next step, we shall see how to access the Web pages stored physically in
c:\temp using a browser using this alias.

Why virtual directories? Let’s consider the advantages of using virtual directories
rather than to store your Web pages in c:\inetpub\wwwroot. By using virtual
directories,
• The user viewing your page cannot determine the actual physical structure of your
folder and its sub-folders by looking at the URL. There are security implications
here; the lesser an external party knows about the folders and its structure, the
better.
• For Web pages which are buried into a deep folder hierarchy, virtual directories
provide a short and more direct URL to access these pages.


ASP.NET Workbook
9
The Virtual Directory Creation Wizard will not allow you to map a virtual
directory to a remote folder (i.e. a path that points to somewhere besides your
local hard disk such as a remote shared storage area on another machine), nor a
removable disk (such as a zip drive or CDROM drive).


7. Access your Web pages using your virtual directory alias

Open up IE and type in the following URL:
http://localhost/somepages/page1.html
Your Web page should appear.



Exercise 1.3
Hosting a Simple ASP.NET Web Page on IIS

So far, the Web pages you have hosted on IIS are (boring) static HTML pages. In this
exercise, you will write you very first dynamic ASP.NET page and host it.

Objective:
• To write (and understand) your first ASP.NET page, and host it on IIS

Instructions

1. Create a script file using Notepad

Create a new text file called luckyno.aspx using Notepad with the following
contents, and save it in c:\inetpub\wwwroot. Note that the label’s ID is lb1 –
not lbl – and it stands for Label Number 1 (for lack of a better name) in this short
demo.

<!-- luckyno.aspx -->
<SCRIPT runat="server" language="VB">
Sub Page_Load
Dim r As Random
r = new Random()
lb1.Text = "Your lucky number today is " + _
Convert.ToString(r.Next(100))
End Sub
</SCRIPT>

<HTML>
<BODY>

www.mokhengngee.per.sg/book

10
<FORM runat="server">
<asp:label id="lb1" runat="server" />
</FORM>
</BODY>
</HTML>

Applying virtual directories: Instead of placing luckyno.aspx in
c:\inetpub\wwwroot, you may want to save it anywhere on your hard disk, and
create a virtual directory to point to that location.

aspx? All ASP.NET Web pages end with a .aspx extension. This will tell the IIS
Web server engine that this is a file containing ASP.NET codes, and to process it
accordingly. In contrast, ASP 3.0 (“classic ASP”) Web page files end with a .asp
extension (without the x).


2. Test your Web page

Check out the aspx Web page which you have just hosted by opening IE and typing
the following URL:
http://localhost/luckyno.aspx
or if you are using a virtual directory,
http://localhost/<virtual_directory_alias>/luckyno.aspx

You should be able to see something like figure 1-10. (Of course the random number
may be different.)


Figure 1-10: The Web page shows your lucky number between 0 and 99 (inclusive)

Try refreshing the page by pressing F5 a few times, or clicking the ‘Go’ button beside
the Address field of IE. (What you are trying to do is to visit the same aspx Web page
again and again.) You should see a new random number each time you hit the page.


ASP.NET Workbook
11
First time longer: If you are observant, you might have noticed that the first time
you tried to access luckyno.aspx, it took a significantly longer time before the
Web page appeared in your browser. Subsequent visits to the same aspx file (when
you refreshed the page) were relatively fast. The reason for this is that the first time a
visitor (client browser) hits a particular aspx page, IIS kicks in its engine to process
the aspx file, convert into a class, create an instance of this class to form an object
which then responds to your browser request. On the second and subsequent times the
same aspx file is ‘hit’, this cached object is used to respond to your browser request
instead. This explains why the first hit to an aspx page always takes more time.


3. Examine the code

Now that we have successfully written and hosted our first ASP.NET page, let’s take
some time to understand what the code actually does.

We can break up luckyno.aspx into 2 parts, the <SCRIPT> part (lines 1-9) & the
<HTML> part (lines 10-16).

01 <!-- luckyno.aspx -->

Line 1 is simply an HTML comment. HTML comments are enclosed within <!--
and -->, and are ignored by the .NET engine processing the ASP.NET file. You can
insert comments in your code where appropriate.

HTML comments vs. ASP.NET comments: HTML comments are sent to the
client browser and are visible at the client side (by selecting ViewSource on the IE
menu). Be aware of this, because you won’t want irrelevant or even confidential
comments (which give clues as to how your ASP.NET page works) to be viewable by
the client! For these, you might want to use ASP.NET comments instead of HTML
comments. ASP.NET comments are enclosed within <%-- and --%>. So, line 01
could’ve been replaced by
01 <%-- luckyno.aspx --%>
The difference will be that this comment will not be sent back to the client browser,
and is thus not visible to the client user.

02 <SCRIPT runat="server" language="VB">
...
09 </SCRIPT>

The <SCRIPT> element is found from lines 2-9. The runat="server"
attribute/value pair tells IIS that the contents of this <SCRIPT> element (i.e. lines 3-
8) are to be processed at the server-side, and not sent back to the client browser
whole-sale. It is important to understand the difference between server-side script

www.mokhengngee.per.sg/book

12
(such as this one) and client-side script (such as JavaScript, or client-side VBScript)
which is supposed to be understood by and processed at the client browser.

1 possible value for the runat attribute: If you omit the runat="server"
attribute/value pair in the <SCRIPT> element start tag, this element will be treated as
a client-side script, and will be sent back to the client without further processing. The
only possible value for the runat attribute is "server", you cannot specify
runat="client".

Another attribute of the <SCRIPT> element is language. In my example, I have
specified the programming language used in the contents of <SCRIPT> to be Visual
Basic.NET (VB). You can use any other supported .NET language in your
<SCRIPT> element such as J# (language="JS") or C# (language="C#", or
language="CS").


VB.NET is the default scripting language: By default, if no language
attribute/value pair is specified in the <SCRIPT> element, VB.NET will be used as
the default language. Hence, in the example in this exercise, it is all right to omit
language="VB" on line 2; it will still work. However, this default language setting
can be changed via IIS Manager.

As an example, you can replace lines 2-9 with the following lines:

<SCRIPT runat="server" language="C#">
public void Page_Load(){
Random r = new Random();
lb1.Text = "Your lucky number today is " +
Convert.ToString(r.Next(100));
}
</SCRIPT>

In this case, the language used in the <SCRIPT> element is C# instead of VB.NET.
Both codes accomplish the same task.

Let’s look at the code contents of this server-side <SCRIPT> element:

02 <SCRIPT runat="server" language="VB">
03 Sub Page_Load
04 Dim r As Random
05 r = new Random()
06 lb1.Text = "Your lucky number today is " + _
07 Convert.ToString(r.Next(100))
08 End Sub
09 </SCRIPT>

ASP.NET Workbook
13

The <SCRIPT> element encloses the Page_Load method (or subroutine, as
traditionally indicated by the Sub keyword in VB).

Page_Load is a special predefined method that will automatically be executed by
the IIS engine every time this Web page is loaded up (i.e. when a client browser hits
it). This is the place to place any initialization code.

Line 4 declares a new variable called r of type Random, and line 5 actually creates
an instance of that class.

The Random class is one of the frequently used classes in the .NET core library. This
method contains the Next method which takes in an integer, and returns a pseudo-
random integer between 0 and that input parameter (including 0, but excluding the
input parameter). So the expression r.Next(100)on line 7 returns a pseudo-
random integer between 0 and 99 inclusive.

The Convert.ToString() method takes in an integer as input parameter, and
returns the string form of that integer (i.e. if the integer 91 is passed in, the whole
expression will return "91" as a string). Hence the whole expression on line 7
(Convert.ToString(r.Next(100))) returns a pseudo-random number
(between 0 and 99 inclusive) as a string.

This string value is then concatenated with "Your lucky number today is
" to get something like "Your lucky number today is 91", and assigned
to lb1.Text on line 6.

Concatenation operator in VB.NET: In VB.NET, we can use either + or & as the
string concatenation operator. & is peculiar to the VB language; other common
programming languages such as Java, C# or C++ uses the + for string concatenation.

lb1 is the variable that represents a server-side ASP.NET Label control which is
declared on line 13 which we shall be discussing soon.

Let’s consider the <HTML> portion:

10 <HTML>
11 <BODY>
12 <FORM runat="server">
13 <asp:label id="lb1" runat="server" />
14 </FORM>
15 </BODY>
16 </HTML>



www.mokhengngee.per.sg/book

14
Lines 10 and 11, 15 and 16 are the HTML and BODY tags, and will be ignored by
the IIS engine, and sent over to the client browser unchanged.

Lines 12-14 represent a server-side HTML form. Note the runat="server"
attribute/value pair of the <FORM> element (that’s why it’s a ‘server-side’ form).
This tells the IIS engine to process lines 12-14, and replace them with some relevant
client-side HTML codes before sending them over to the client browser.

Line 13 declares an ASP.NET server-side web control called a Label. Each ASP.NET
control can have an ID, much like a variable name, so that it can be identified. In my
example, this Label object has an ID lb1.

When luckyno.aspx loads, the IIS engine will execute the Page_Load method
in the <SCRIPT> section first, and set our Label control lb1’s Text attribute to a
string that may read "Your lucky number today is 91". Lines 12-14 will
be processed by the IIS engine at the server and replaced by a line "Your lucky
number today is 91", which is then sent back to the client browser within the
<HTML> and <BODY> elements.


4. Understand what gets sent back to the client

Open up IE and view luckyno.aspx again. Select ViewSource from IE’s menu
to take a look at the HTML codes that were actually returned from IIS. You should
see something like this:

<!-- luckyno.aspx -->

<HTML>
<BODY>
<form name="_ctl0" method="post"
action="luckyno.aspx" id="_ctl0">

<input type="hidden" name="__VIEWSTATE"
value="dDw4MDE0NzI0MDA7dDw7bDxpPDI+Oz47bDx0PDtsPGk8MT47PjtsPHQ
8cDxwPGw8VGV4dDs+O2w8WW91ciBsdWNreSBudW1iZXIgdG9kYXkgaXMgNDg7P
j47Pjs7Pjs+Pjs+Pjs+sFphy5fXRFGvzAcMZe8pIUwBq1w=" />

<span id="lb1">Your lucky number today is 48</span>
</form>
</BODY>
</HTML>

Ignore the <INPUT> element first (this will be discussed when we deal with states), and you
can see that what actually got sent back from the server was simply a plain HTML file which
looks like this:

ASP.NET Workbook
15

<!-- luckyno.aspx -->

<HTML>
<BODY>
<form name="_ctl0" method="post"
action="luckyno.aspx" id="_ctl0">
<span id="lb1">Your lucky number today is 48</span>
</form>
</BODY>
</HTML>

You should realise that all server-side codes (the <SCRIPT>, <FORM> and
<asp:label>) in the original aspx file had been processed by the IIS server
engine, and replaced with relevant HTML codes that the client browser can
understand.



Exercise 1.4 (optional)
IIS Access Right Settings

In this exercise, you will be introduced to how you can control the accessibility of your
Web pages hosted on IIS. It is important to understand to understand this exercise
because given users more access than is required may lead to security problems.

Objective:
• Understanding basic IIS access rights settings to control the accessibility of your Web
pages.

Instructions:

1. Prepare for the exercise

You need to have understood how to create a virtual directory (see exercise 1.2)
before proceeding.

Run the Virtual Directory Creation Wizard to create a virtual directory mapping to a
folder on your hard drive (such as c:\temp). For this example, somepages has
been selected as the virtual directory alias.

In your physical drive which is mapped to the alias (such as c:\temp), create a
static HTML file which displays a simple message (such as myfirstpage.html)
and an ASP.NET Web page (such as luckyno.aspx) which contains some
ASP.NET scripts.

www.mokhengngee.per.sg/book

16


2. View properties of the virtual directory

Recall that in step 5 of exercise 1.2 (Creating a Virtual Directory with IIS), the
Virtual Directory Creation Wizard provided you with options to set the accessibility
of your Web pages (see figure 1-9), but all you did was to accept the default options
(i.e. only ‘read’ and ‘run scripts’ enabled). You will learn the implications of
selecting each option in this exercise.

You can still modify the accessibility options of a particular directory after it has been
created. Fire up IIS Manager (Start Administrative Tools Internet Information
Server). On the left panel, double click on the ‘local computer’ icon, ‘Web sites’ icon
and the ‘default Web site’ icon. You should be able to see an icon representing your
virtual directory. (See figure 1-11: in this example, the virtual directory alias had
been set as ‘somepages’.) Right click on ‘somepages’ or your alias icon and
select ‘Properties’.


Figure 1-11: Viewing the properties of a virtual directory

You should see the Properties pop-up window (figure 1-12). Here is where you can
adjust the accessibility settings of your virtual directory. The access permissions you
set here controls the type of access for the given directory and permissions allowed
on files in that directory.


ASP.NET Workbook
17

Figure 1-12: Properties of a directory where you can change access permissions

3. Understand the various access options

Figure 1-13 summarizes the possible script access options: ‘Script source access’,
‘Read’, ‘Write’ and ‘Directory browsing’.


Figure 1-13: The various script access options.

Script source access: If this is
checked, client users can access the
source code of an .aspx file. This
option is available only if ‘read’ or
‘write’ is checked.
Read: If this is checked, client users can
read/download files in the directory. If
unchecked, HTML files cannot be read, but
.aspx
files can still be processed and read.
Write: If this is checked, client
users can create/modify files in
the director
y
.
Directory browsing: If this is
checked, client users can view
the contents of the director
y
.


www.mokhengngee.per.sg/book

18

Figure 1-14: Execute Permissions

Figure 1-14 summarizes the possible options for the ‘Execute Permissions’ field.

4. Experiment with Access Permissions

Set access permissions to ‘Read’ and ‘Directory browsing’, and Execute Permissions
to ‘None’, and click on ‘OK’. By studying the descriptions of the various access
permissions, do you think a client user can view the HTML file, and/or the ASP.NET
file?

To check if you are correct, open up IE and try to view the HTML file:
http://localhost/somepages/myfirstpage.html
You should be able to see the HTML file.

Next, try to view the ASP.NET file:
http://localhost/somepages/luckyno.aspx
A 403 error appears with the problem description. (See figure 1-15 :the ‘Background’
section describes exactly how we have configured in the properties pop-up box.)

None: Client users can only access
static files only (html, jpegs etc), but
not ASP.NET pages.
Scripts only: Client users can access
script-based pages (i.e. ASP.NET
pages)
Scripts & Executables: Client users
can execute any type of file in the
directory including
.exe
s

ASP.NET Workbook
19

Figure 1-15: HTTP 403.1 error due to denied access permissions.

Now, try specifying only the alias name:
http://localhost/somepages/
You should be able to see the contents of the physical folder. This is because
‘Directory browsing’ has been enabled. (See figure 1-16)

Switch off directory browsing unless necessary: Setting ‘Directory browsing’
rights might be useful if you intend to set up a site for users to download files (similar
to an FTP site). Otherwise it is generally bad practice to allow users to view the
contents of your folder (with security implications).



www.mokhengngee.per.sg/book

20

Figure 1-16: viewing the directory contents of your physical folder


As Web server administrator, you should always give as little access permissions
as possible to your users. Unless there is a special requirement, you should use the
default configurations (i.e. only enable ‘Read’ and set Execute Permissions to ‘Script
only’).



2: ASP.NET Web Forms

In this chapter, you will get familiar with Visual Studio.NET’s development
environment, and create ASP.NET Web applications using VS.NET.

There are 4 exercises in this chapter:
• Exercise 2.1: Getting familiar with the VS.NET IDE
• Exercise 2.2: Writing a Simple Web page and Understanding Event Handlers
• Exercise 2.3: Understanding Code-Behind Pages
• Exercise 2.4: Creating a More Complex Web Form with other Server Controls


Exercise 2.1
Introducing the VS.NET IDE

Objective:
• To be familiar with VS.NET’s Integrated Development Environment.

Instructions:

1. Start up VS.NET and create a new project

Click on Start All Programs Microsoft Visual Studio.NET 2003 VS.NET. The
IDE will appear after the splash screen disappears.

What components have been installed? The VS.NET splash screen will show the
installed languages and modules with VS.NET on your machine. In this example,
figure 2-1 shows 3 .NET languages (VB.NET, C# and J#, but not C++.NET) have
been installed on this particular machine. If you intend to use a particular.NET
language which is not available on your PC, you will need to install it first
(administrator rights to your local PC required).


www.mokhengngee.per.sg/book

22
Figure 2-1: Splash screen showing the installed products.

The ‘start page’ which contains shortcut ‘links’ to the last few opened projects (if
any) appears. Notice the Toolbox pane on the left, Solution Explorer pane on the right
and the Task List pane at the bottom. For now, they are quite empty because you are
not yet working on any project.


Figure 2-2: VS.NET IDE

Hiding panes: You can hide or show the Toolbox or Solution Explorer pane (and
any other panes) by selecting ViewToolbox, or ViewSolution Explorer on
VS.NET’s menu. Conversely, if you do not see the Toolbox and Solution Explorer
upon startup, that probably implies that the computer user before you might have
hidden them.

Open a new project by selecting FileNewProject… from the menu. The New
Project dialog appears (figure 2-3). For this exercise, we are going to create a new
Web Application project.


ASP.NET Workbook
23

Figure 2-3: Creating a new VS.NET project

Select ‘Visual Basic Projects’ for ‘Project Types’ and ‘ASP.NET Web Application’
for ‘Templates’. In the ‘Location’ field, type in:
http://localhost/TestWebApp

When you click on ‘OK’, VS.NET will communicate with IIS to create a folder in
c:\inetpub\wwwroot (see figure 2-4). For this example, since TestWebApp
has been entered in the ‘Location’ field (figure 2-3), VS.NET will create the folder
TestWebApp in c:\inetpub\wwwroot and place within it several other files
created automatically as part of the project.


Figure 2-4: A new folder is created in wwwroot when you create a new Web
application project.


www.mokhengngee.per.sg/book

24
Using Windows Explorer, take a look at that folder to determine what files have been
created for you for the new project. You will also be able to see these files in the
Solution Explorer pane in the VS.NET IDE.

If you see the error ‘Web Access Failed’ in figure 2-5 when you try to create a
new project, you may not have the proper permissions to create this project. Check
with your system administrator that your account is a member of the ‘VS Developer’
group on your local machine (This group is created when VS.NET was installed.)

Figure 2-5: Web access failure may be due to insufficient privileges.


Anatomy of a VS.NET Solution: In VS.NET, one or more ‘projects’ make up a
‘solution’. A solution is a group of projects that are loaded into VS.NET at the same
time for the purpose of development, debugging and building. If you take a look at
the c:\inetpub\wwwroot\<project_name> folder, you will see your project
files (something.vbproj for VB.NET projects, something.vjsproj for J#
projects, and something.csproj for C# projects). ASP.NET Web application
project files are usually placed there. On the other hand, if you are writing a .NET
Windows application, you can place your project files in any location.

The solution file (something.sln) may or may not be placed together with your
project files; to find out where your .sln file is stored, select the solution file in
Solution Explorer (it’s the top-most one in Solution Explorer) and look at the
Properties pane. The value of its ‘Path’ property indicates the location to the .sln
file. The .sln file is simply a text file (that you can open using Notepad) which
contains information about the various projects in this solution.


Every time when you select NewProject from the VS.NET menu, you will have an
option to include this new project as part of an existing solution, or to create a new
solution to contain only this project.

Transferring your Web application to another machine: A simple way to copy
out a VS.NET solution from one development machine (from home) to another (say,

ASP.NET Workbook
25
in school) is to copy the .sln file and the whole project folder from
c:\inetpub\wwwroot.
• Place the project folder in the wwwroot folder of the target machine
• Open IIS Manager and expand the directory tree on the left until the ‘Default Web
site’ icon is shown.
• You should be able to see your new folder represented as a normal folder icon
(instead of a Web application icon).
• Right-click on this icon and select ‘Properties’.
• In the ‘directory’ tab of the ‘Properties’ window, click on the Create button to
make this a Web application. This is an important step – otherwise, you may be
able to open your .sln or project files in VS.NET, but won’t be able to view the
Web pages in a browser.
• You can then double-click on the .sln or project file to open it up in VS.NET.


2. Explore the Toolbar

After these files are created in c:\inetpub\wwwroot, your IDE will display
WebForm1.aspx right in the middle, and you are ready to start working on your
WebForm1.aspx file (figure 2-6). You should also have noticed that the Toolbox
and Solution Explorer panes are filled with useful ‘goodies’ relevant to your Web
application.


Figure 2-6: Checking out the various parts of the IDE

The Toolbox pane is where you will drag server-side controls to your aspx file from.
Figure 2-7 shows the Toolbox. Notice that there is a thumb pin icon (circled in figure
2-7). Click on it to ‘auto-hide’ your Toolbox pane. You can also do this for all other

www.mokhengngee.per.sg/book

26
panes (Solution Explorer etc). It is advisable to auto-hide some panes so that you
have more space for your main document.

You can also dock the Toolbar (or any other panes) at other locations by dragging the
title bar of the pane (circled in figure 2-7) to any location in the IDE.


Figure 2-7: The Toolbox pane: your chest of ‘goodies’ controls.

The Toolbox contains the following sub-sections: Data, Web Forms, Components,
HTML, Clipboard Ring, and General. You will be dragging quite a few controls from
the ‘Web Forms’, ‘HTML’ and ‘Data’ sections of the Toolbox for your subsequent
exercises.

The Toolbox’s ‘Web Forms’ section contains useful controls such as Textboxes,
Labels, Buttons etc. Click on the up/down arrows (circled in figure 2-7) if necessary
to view the complete list of controls available in that section.

Click on the ‘HTML’ section to reveal the available controls there. The Toolbox’s
‘HTML’ section contains somewhat similar controls such as Labels, Buttons and
TextFields too. You will learn the difference between controls ‘pulled out’ from the
‘Web Forms’ and the ‘HTML’ sections soon.


3. Explore the Solution Explorer pane

Take a look at the Solution Explorer pane on the right. The Solution Explorer is
where you can view all the files and references used in your project. You will realise
that several other files such as Global.asax and Web.config have been

ASP.NET Workbook
27
generated and included in the project for you. You can double click on the file names
to open them. (More will be covered about Global.asax and Web.config
later.)

Not all files in your project are visible though. Click on the ‘Show All Files’ icon
(figure 2-8) to view all the files associated with your project. Then expand on
WebForm1.aspx by clicking on the plus sign beside WebFrom1.aspx. You
should be able to see that there are 2 other files associated with WebFrom1.aspx
called WebForm1.aspx.vb and WebForm1.aspx.resx.

WebForm1.aspx is the default aspx file which is generated when you selected to
create a Web application project. You can rename it by right clicking on
WebForm1.aspx in Solution Explorer, and selecting the ‘rename’ option. If you do
so, you will notice that the corresponding WebForm1.aspx.vb and
WebForm1.aspx.resx files will also be renamed accordingly.

For this exercise, the original name (i.e. WebForm1.aspx) will be retained, but you
may wish to give it a more appropriate name.

resx file? We don’t have to bother too much about the .resx file. It’s just a
resource file associated with our Web page.

Code-behind files: WebForm1.aspx.vb is a VB.NET file. If you had selected
to create a C# Web application project instead of a VB.NET Web application project,
the file will be WebForm1.aspx.cs instead of WebForm1.aspx.vb. This .vb
or .cs file is also known as the ‘code-behind’ file of WebForm1.aspx. The
purpose of a ‘code-behind’ file will be explained later, but for now, it is enough to
know that WebForm1.aspx.vb will contain VB.NET source codes which
‘support’ the WebForm1.aspx Web page. Every Web form you create in VS.NET
will come with its own ‘code-behind’ file.




www.mokhengngee.per.sg/book

28
Figure 2-8: Show all files in Solution Explorer


4. Explore the main document area

You can open any file by clicking on the file name in Solution Explorer (or selecting
FileOpenFile… from the menu). Figure 2-9 shows the editing area with 4 files
currently open. Also notice from figure 2-9 that WebForm1.aspx has an * beside
its name indicating that changes have made to this file, and it hasn’t been saved yet.
You can use Ctrl-S or select FileSave to save the current file.

If you hover your mouse pointer over the file name, the actual physical location
where the file is stored pops up too (figure 2-9).


Figure 2-9: Edit your documents here


Try dragging a Button control from the Toolbox’s ‘Web Forms’ section to the editing
area of WebForm1.aspx. Also drag a Button control from the Toolbox’s ‘HTML’
section to the same area (below the first button).

You should see something like figure 2-9. What you have just done is create a Web
form containing 2 Button controls.

Runat Server Controls: Notice that one of the 2 Button controls has a tiny green
arrow (the button which was dragged from the Toolbox’s ‘Web Forms’ section) when
viewed in the Design View. The other button (the one which was dragged from the
Toolbox’s ‘HTML’ section) doesn’t (figure 2-9). This green arrow ‘attached’ to a
control indicates that it is a server-side control, or, in other words, this control has a
runat="server" attribute/value pair, and will be processed at the IIS server
rather than just returned to the client browser.

Right click on the button which runs at the client (the one without the green arrow)
and select ‘Run as Server Control’. You will notice that the green arrow now appears.

ASP.NET Workbook
29
If you check out the HTML codes, the runat="server" attribute/value pair
would have been inserted into the <INPUT> (HTML button) element. Set it back to
run as a client control by right clicking on that button and selecting ‘Run as Server
Control’ again.


Each aspx Web form can be represented in 2 ways: the Design View and the HTML
View.

You are currently viewing the Design View of WebForm1.aspx. The Design View
represents a visual way for manipulating the Web form. While you are dragging and
dropping controls from the Toolbox pane to your WebForm1.aspx in Design
View, VS.NET is busily creating HTML codes in the background for you.

Click on the ‘HTML’ tab (circled in figure 2-9) to switch over to the HTML View of
WebForm1.aspx. You will see what VS.NET has generated for you when you
dragged the Button controls over:

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb"
Inherits="TestWebApp.WebForm1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>
<HEAD>
<title>WebForm1</title>
<meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.1">
<meta name="CODE_LANGUAGE" content="Visual Basic.NET 7.1">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="...">
</HEAD>

<body MS_POSITIONING="GridLayout" bgColor="#ffffff">
<form id="Form1" method="post" runat="server">

<asp:Button id="Button1" style="Z-INDEX: 101; LEFT: 128px;
POSITION: absolute; TOP: 88px" runat="server"
Text="Button"></asp:Button>

<INPUT style="Z-INDEX: 102; LEFT: 128px; POSITION: absolute;
TOP: 136px" type="button" value="Button"
id="Button2" name="Button2">
</form>
</body>
</HTML>

The code statements in bold above were inserted by VS.NET when you dragged the
button controls over in Design View.







www.mokhengngee.per.sg/book

30
5. Understand button codes

Let’s examine the 2 code fragments in greater detail.

The following fragment represents a ‘normal’ HTML INPUT button which was the
Button control that was dragged from the HTML section of your Toolbox pane:
<INPUT style="Z-INDEX: 102; LEFT: 128px; POSITION: absolute;
TOP: 136px" type="button" value="Button"
id="Button2" name="Button2">


The following fragment represents an ASP.NET server-side Button control which
was the Button control that was dragged from the Web Forms section of your
Toolbox pane:
<asp:Button id="Button1" style="Z-INDEX: 101; LEFT: 128px;
POSITION: absolute; TOP: 88px" runat="server"
Text="Button"></asp:Button>

Aren’t they different! (Though you can’t tell the difference when looking at their
graphical representation in Design View). One notable difference is that the Button
control dragged from the Toolbox’s HTML section is an <INPUT> element, while
the other is an <asp:Button> element.

Another difference is that your <asp:Button> element has the
runat="server" attribute/value pair, which means that this <asp:Button>
control is a server-side control, and will be processed at the server.


6. Explore the Properties pane

Besides the Solution Explorer and the Toolbox pane, there is another useful pane
which you will use very frequently: the Properties pane. Each object in your Web
form has certain properties which you can set using the Properties pane.

F4 (but not the boy band): A useful shortcut to make the Properties pane appear is
the F4 function key. Close the Properties pane. Select any control on your Web form,
and hit F4.

If you click on the drop-down field right on top of your Properties pane, you will see
the list of available objects in your aspx page (figure 2-10). For now, you should be
able to see:
• 2 button objects (Button1, which is a <asp:Button> control, and
Button2, which is an HTML <INPUT> control),
• WebForm1 (which represents the <FORM>…</FORM> element of your page)
and
• DOCUMENT (which represents the whole Web page itself).

ASP.NET Workbook
31


Figure 2-10: The list of available objects in your Web page so far


Can’t see properties: If you only see DOCUMENT in the Properties pane’s drop-
down list, it may be because your aspx file is in HTML View. Click on the ‘Design’
tab to switch to Design View, and you should be able to see the full list of objects on
your aspx page.

Each object will have property settings specific to its type. So, you will see different
properties for each object. Let’s check out the <asp:Button> button: select
Button1 (not Button2, which is your HTML <INPUT> button) from the drop-
down list to view its properties (figure 2-11 left).


Figure 2-11: Set the properties of your ASP server-side Button control

Click on the BackColor property of your Button1 object and select a new color
(figure 2-11 middle). One property value which you will want to change is the Text
property.


www.mokhengngee.per.sg/book

32
Change Button1’s Text value to ‘Click me’ or some text (figure 2-11 right).
The changes (in BackColor and Text) are immediately reflected in the Design
View of the Web page.

You might also want to change the values of other properties. A brief description of
the property you are trying to change will appear at the bottom of the Properties pane
(see circled area in figure 2-11 middle).

Property changes: What actually happens when you change an object’s property
value in the Properties panel? These changes are reflected in the HTML
representation of your Web page. To see the ‘effects’ of the changes that have just
been made, switch over to HTML View.

Notice that the <asp:Button> element has been altered with the new Text and
BackColor values:

<asp:Button id="Button1" style="Z-INDEX: 101;
LEFT: 128px; POSITION: absolute; TOP: 88px"
runat="server" Text="Click me" BackColor="Yellow">
</asp:Button>

Instead of using the Properties pane, you can also edit the HTML codes in HTML
View directly (the changes will be reflected in the Properties pane), but it will be
much easier to use the Properties pane.


7. View the end product in a client browser

So far, we have created a Web page called WebForm1.aspx. Let’s view this page
using a client browser. You can do that easily from within VS.NET: right-click on
WebForm1.aspx in Solution Explorer, and select ‘View in Browser’. After a while
(remember that it takes a little longer the first time you view a Web page), you will
see the 2 buttons as they will appear in IE.

Alternatively, you can open up IE and type in the correct URL (this URL is the same
URL as that shown circled in figure 2-12).

Remote access: If you are trying to view WebForm1.aspx from another
machine, remember to replace localhost with your machine’s IP address in the
URL.


ASP.NET Workbook
33

Figure 2-12: Browsing a Web page from within VS.NET itself.

If you are using IE to view WebForm1.aspx, you can view the HTML source
codes being displayed by selecting ViewSource from IE’s menu. You can also
right-click on any blank space on the page and select View Source. If you are viewing
the page within VS.NET, you can right-click on any blank space around the 2 buttons
and select ‘View Source’ (figure 2-12).

8. Understand ‘server-side’ controls

It is important to understand what is meant by ‘server-side’ controls – as opposed to
‘client-side’ controls. What does it mean when someone says that ‘server-side’
controls are processed at the IIS server first before they are sent back to the client?

Compare the source codes of WebForm1.aspx in HTML View and the final
HTML codes that are sent back to the client browser (follow the instructions in the
previous step to view the HTML codes being displayed at the client). The following
code shows the HTML codes which have been sent over to the client browser:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>WebForm1</title>
<meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.1">
<meta name="CODE_LANGUAGE" content="Visual Basic.NET 7.1">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="...">
</HEAD>

<body MS_POSITIONING="GridLayout" bgColor="#ffffff">
<form name="Form1" method="post" action="WebForm1.aspx" id="Form1">

<input type="hidden" name="__VIEWSTATE"
value="dDwtNTMwNzcxMzI0Ozs+aiTbi12xQ6EFGoEcr5DNWOhDMKo=" />

<input type="submit" name="Button1" value="Click me"
id="Button1" style="background-color:Yellow;Z-INDEX: 101;
LEFT: 128px; POSITION: absolute; TOP: 88px" />

www.mokhengngee.per.sg/book

34

<INPUT style="Z-INDEX: 102; LEFT: 128px; POSITION: absolute;
TOP: 136px" type="button" value="Button" id="Button2"
name="Button2">

</form>
</body>
</HTML>

Notice that there are significant differences between the HTML codes the client
receives and the original codes in WebForm1.aspx.

The following shows the differences between the original and the final in the
<FORM> element. (For now, ignore the first <INPUT type="hidden"> element
which contains the strange series of random characters; the usage of this additional
<INPUT> element will be covered subsequently.)



Notice that the <asp:Button> element (Button1) which is a server-side control
(it has the runat="server" attribute/value pair) has been processed by IIS and
replaced with a normal HTML <INPUT type="submit"> (button) element
before being sent over to the client.

On the other hand, the <INPUT> element (Button2) which is a client-side control
(pulled out from Toolbox’s HTML section) has remained intact. The element is
<form id="Form1" method="post" runat="server">

<asp:Button id="Button1" style="Z-INDEX: 101; LEFT: 128px;
POSITION: absolute; TOP: 88px" runat="server"
Text="Click me" BackColor="Yellow"></asp:Button>

<INPUT style="Z-INDEX: 102; LEFT: 128px; POSITION: absolute;
TOP: 136px" type="button" value="Button" id="Button2"
name="Button2">

</form>


<form name="Form1" method="post" action="WebForm1.aspx"
id="Form1">

<input type="hidden" name="__VIEWSTATE"
value="dDwtNTMwNzcxMzI0Ozs+aiTbi12xQ6EFGoEcr5DNWOhDMKo=" />

<input type="submit" name="Button1" value="Click me"
id="Button1" style="background-color:Yellow;Z-INDEX: 101;
LEFT: 128px; POSITION: absolute; TOP: 88px" />

<INPUT style="Z-INDEX: 102; LEFT: 128px; POSITION: absolute;
TOP: 136px" type="button" value="Button" id="Button2"
name="Button2">

</form>
Sentbacktoclient
Original codes

ASP.NET Workbook
35
meant to be sent over to the client browser unchanged, and will be processed by the
client. IIS will not modify it since it is meant for the client.

Runat-Server Form: Notice also that the <FORM> element has a
runat="server" attribute/value pair. Some changes have also been made to the
<FORM>’s attributes before being sent over to the client.

In the next exercise, you will create a proper (but simple) Web application.


Exercise 2.2
Writing a Simple Web Page and Understanding Event
Handlers

The previous exercise has brought you on a whirlwind tour of the VS.NET IDE. In this
exercise, you will learn how to use VS.NET to write an ASP.NET Web form.

Objective:
• Be able to write a simple Web application in VS.NET with a button and event
handling code.

Instructions:

1. Create a new VS.NET project

Start up VS.NET, and select FileNewProject from the menu. Select ‘Visual
Basic Projects’ for ‘Project Types’ and ‘ASP.NET Web Application’ for ‘Templates’.
In the ‘Location’ field, type in http://localhost/SimpleWebApp (figure 2-
13). Click ‘OK’.


www.mokhengngee.per.sg/book

36

Figure 2-13: Create a new ASP.NET Web application project in VB.NET


2. Insert controls to your Web form

Rename WebForm1.aspx to Counter.aspx by right-clicking on
WebForm1.aspx in Solution Explorer, and selecting ‘rename’.

Drag and drop a Label server control from the Toolbox’s ‘Web Forms’ section (not
‘HTML’ section) to your Web form. Drag and drop 2 Button server controls from the
same ‘Web Forms’ section. Notice the tiny green arrow on the upper left corner of the
3 controls indicating that all of them are ‘server-side’ controls (figure 2-14).


Figure 2-14: A Label and 2 Button server controls

Select the Label by clicking once on it; the Properties pane will show the properties
of the Label object.

Change the (ID) property of the label from Label1 (that’s the default ID value) to
lb_count. The ID is an important property of any control which is similar to a
variable name. We will refer to this label object via its ID.

Set the Text property of the Label control to 0 (figure 2-15).


ASP.NET Workbook
37

Figure 2-15: Changing the Label object’s (ID) and Text properties


3. Set the server controls’ properties

Select the Button control on the left, and change its (ID) to bn_increase.
Change its Text property to +. Select the Button control on the right, and change its
(ID) to bn_decrease and its Text property to -.

lb_count will be set to display a number later. When the client clicks on the +
button, we want to increase the number displayed by lb_count. When the client
clicks on the – button, we want to decrease the number displayed.


Figure 2-16: Changing the Buttons’ (ID) and Text properties.

At this point, you may want to switch over to Counter.aspx’s HTML View to see
what HTML codes VS.NET has written for you.


www.mokhengngee.per.sg/book

38

4. Write the event handler for the Button controls

Switch back to Design View and double click on the + button. When you do that,
VS.NET will open up Counter.aspx.vb. This is the ‘code-behind’ file
accompanying Counter.aspx. Here’s where you will enter VB.NET code for the
+ button’s event handler.

What is an event handler? An event is something which happens. An event
handler is a method which executes when that event happens. In this exercise, the
event that you are trying to ‘trap’ is the button click. That is, when the user clicks on
the + button, we want certain VB.NET codes to run in response to this button click.
What you are going to do is to write the event handling codes in the
bn_increase_Click method.

Enter the 4 lines of code into the bn_increase_Click method as indicated
below:

Private Sub bn_increase_Click _
(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles bn_increase.Click

Dim c As Integer
c = Convert.ToInt32(lb_count.Text)
c = c + 1
lb_count.Text = Convert.ToString(c)

End Sub


Is it compulsory for the event handler of bn_increase to be called
bn_increase_Click? bn_increase_Click is just the default name given by
VS.NET to correspond to the clicking of bn_increase. You can change the
method’s name to any other valid name. It is the Handles
bn_increase.Click (which is part of the method declaration) which tells
VS.NET that this method (whatever its name) is the event handler for the Click
event of bn_increase. However, don’t change the default event handler methods
provided by VS.NET unless there is really a good reason to do so.

Similarly, go back to Counter.aspx’s Design View and double click on the –
button. Fill up the bn_decrease_Click method in Counter.aspx.vb:

Private Sub bn_decrease_Click _
(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles bn_decrease.Click

Dim c As Integer
c = Convert.ToInt32(lb_count.Text)

ASP.NET Workbook
39
c = c - 1
lb_count.Text = Convert.ToString(c)

End Sub



VS.NET Intellisense: As you typed your codes into Counter.aspx.vb, you
might observe a few things:

• When you typed something wrongly (such as Di instead of Dim), squiggly blue
lines appear under Di. Squiggly blue lines denote a syntax error. To see the
problem, hover your mouse pointer over the squiggly blue line, and a brief
description will pop up (figure 2-17). You have to ensure that there are no
squiggly lines before even attempting to view the page in a browser.


Figure 2-17: Squiggly blue lines denote a syntax error.

• When you typed the full stop after certain words (such as lb_count., or
Convert.), and wait for half a second, a list appears for you to select from. In
figure 2-18, the list which appears contains the available properties for the
lb_count Label object. You can select the correct property you want from the
list and hit TAB (ENTER will cause the cursor to jump to a new line).


Figure 2-18: Context sensitive assistance is available


5. Test your Web form

It’s time to check out if your page works correctly. Right click on Counter.aspx
in Solution Explorer and select ‘View in Browser’. (If Counter.aspx and/or its

www.mokhengngee.per.sg/book

40
code-behind page Counter.aspx.vb have not been saved yet, VS.NET will save
them for you automatically when you view it in a browser.)

If everything goes fine, you should see your page with the 2 buttons. Try clicking on
the buttons and see what happens.


6. Understand the codes

The first statement simply declares a new local variable c of type Integer:
Dim c As Integer

Let’s examine the second statement:

c = Convert.ToInt32(lb_count.Text)

The expression lb_count.Text returns the Text value of the lb_count Label
server control object. This was original set to “0” (as a string).
Convert.ToInt32() is a method which takes in a string containing numbers
only, and returns the same number value as an integer. So,
Convert.ToInt32("0") will return 0 as an integer, and
Convert.ToInt32("958") will return 958 as an integer. We then assign the
integer returned by the Convert.ToInt32() expression to the variable c.

What we have done is to take the Text value of the label, convert it into an integer,
and assign it to c.

Following that, we increase the value stored in c by 1:
c = c + 1

The next statement is:

lb_count.Text = Convert.ToString(c)
Convert.ToString() is a method which takes in an integer and returns it as a
string. So, Convert.ToString(35)will return "35" as a string.

This string value is then assigned to lb_count’s Text property, which is displayed
on the Web page.

Study the codes in the event handler for the – button; they are essentially the same
except that instead of increasing c by 1, c is decreased by 1.


7. Use C# or J# instead

Some of you may prefer to work using C# or J# instead of VB.NET. You can do so
by selecting ‘Visual C# Projects’ (or ‘Visual J# Projects’) instead of ‘Visual Basic
Projects’ when you selected FileNewProject from VS.NET’s menu in step 1.

ASP.NET Workbook
41

Of course, your code-behind file will be Counter.aspx.cs (or
Counter.aspx.js) instead of Counter.aspx.vb.

All the steps outlined above are the same, except that when you double click on the
buttons to write your event handlers. The codes look different (it’s a different
language!) The following C# codes do exactly the same thing:

// C# - increase button event handler
private void bn_increase_Click(object sender, System.EventArgs e)
{
int c;
c = Convert.ToInt32(lb_count.Text);
c = c + 1;
lb_count.Text = c;
}

// C# - decrease button event handler
private void bn_decrease_Click(object sender, System.EventArgs e)
{
int c;
c = Convert.ToInt32(lb_count.Text);
c = c - 1;
lb_count.Text = c;
}

For programmers who prefer J#, the J# codes follow. Note that you will need to insert
an additional import statement at the top of the file because the Convert class
which is being referred to is in the System namespace, and the System namespace
is not automatically imported in J# projects.


// insert below the package statement
import System.*;

// J# - increase button event handler
private void bn_increase_Click (Object sender, System.EventArgs e)
{
int c;
c = Convert.ToInt32(lb_count.get_Text());
c = c + 1;
lb_count.set_Text(Integer.toString(c));
}

// J# - decrease button event handler
private void bn_decrease_Click (Object sender, System.EventArgs e)
{
int c;
c = Convert.ToInt32(lb_count.get_Text());
c = c - 1;
lb_count.set_Text(Integer.toString(c));
}



8. Understand what gets sent back to the client

View Counter.aspx again in a client browser. View the codes sent back to the
browser (ViewSource from IE’s menu) and study it for a while:

www.mokhengngee.per.sg/book

42

<form name="Form1" method="post" action="Counter.aspx" id="Form1">

<input type="hidden" name="__VIEWSTATE"
value="dDwxNTg5NjY5Njc4O3Q8O2w8aTwxPjs+O2w8dDw7Oz" />

<span id="lb_count" style="Z-INDEX: 101; LEFT: 88px;
POSITION: absolute; TOP: 32px">
0</span>

<input type="submit" name="bn_increase" value="+"
id="bn_increase" style="Z-INDEX: 102; LEFT: 64px;
POSITION: absolute; TOP: 64px" />

<input type="submit" name="bn_decrease" value="-"
id="bn_decrease" style="Z-INDEX: 103; LEFT: 96px;
POSITION: absolute; TOP: 64px" />

</form>

Notice that the Label server control has been replaced by a <span> element to be
sent back to the client, and both <asp:Button> controls have been replaced by
HTML <input type="submit"> (submit buttons) elements.

Also note that your form posts back to itself (action="Counter.aspx"). In
other words, when either button is clicked on, the client browser sends a HTTP POST
request back to the same Web page (Counter.aspx). The business logic for
clicking on either button (i.e. the business logic in the event handlers) is not found in
the HTML code which is being sent over to the client. Instead, when the user clicks
on either button, the client will submit the form back to the server, and codes at the
server will then determine what to do and recreate a new HTML page with the
updated value (1 or -1) in the <span> element to be sent back.


View State: Did you notice that the HTML codes that are sent back to the client
browser has an additional <INPUT type="hidden"> element? ASP.NET
improves over ASP 3.0 by automatically storing data such as text in TextBoxes and
posting it as a hidden <INPUT> element with a name of "__VIEWSTATE" over to
the target Web page (which, in this case, is itself). In the target page, this hidden
<INPUT> element is examined, and ‘decoded’ at the server to recover this
information. The form controls in the target page are then repopulated with the same
information. All this is done transparently from the developer or user. In ASP 3.0 or
other Web application technologies such as JSP, the developer has to write code
manually to perform this ‘memory’ capability.




ASP.NET Workbook
43
Further Exercise

Write a Web form GST calculator which allows users to calculate the net price of a
product after factoring in GST. It can look like this:


Figure 2-19: GST calculation is no longer a headache with this application!

The user enters the Price and GST Rate and clicks on ‘Calculate’. The net price (i.e.
original price + GST) appears in the Net Price field.

Hints:
• Your Price and GST Rate fields should expect double values (decimal values)
instead of only just integers (whole numbers). Use the Convert.ToDouble()
method to convert a string into a double value.
• You will make use of the TextField server control from Toolbox’s ‘Web Forms’
section. The TextField control allows users to enter values. Like Label,
TextField has a Text property which you can use to retrieve or set its
displayed value.


Formatting controls: VS.NET provides a convenient way to ensure that your
controls (such as TextBoxes) are vertically aligned. Select all the TextBoxes by
clicking them individually with the shift key down, then select
FormatAlignLefts from the menu. There are other useful functions such as
FormatMake Same Size, FormatVertical Spacing and FormatHorizontal
Spacing which you can use for creating a neater user interface.



www.mokhengngee.per.sg/book

44
Simple Error Handling

If the user enters a non-numeric string into either the Price or GST Rate fields, and click
on the Calculate button, an exception will be raised (figure 2-20). The reason is that
Convert.ToDouble() takes in only strings containing numeric characters.


Figure 2-20: FormatException resulting from passing in a non-numeric string
into Convert.ToDouble().

You might want to catch this problem and display an error message (by setting the Text
property of a Label server control when the user enters a non-numeric string into either
TextField. Here is a hint:

Try
price = Convert.ToDouble(TextBox1.Text)
rate = Convert.ToDouble(TextBox2.Text)
Catch err As FormatException
lb_error.Text = _
"Enter only numeric values in the Price and GST rate fields"
Return
End Try


When the user enters some non-numeric characters, an error message is shown instead
(figure 2-21).


ASP.NET Workbook
45

Figure 2-21: Your application can trap for exceptions and display error messages.


Validator controls: we will learn how to make use of the Validator controls
provided in the Toolbox to validate text fields in the next chapter. Validators are
extremely convenient to ensure that the user enters only certain ‘valid’ values into
text fields (such as only numbers in our case).

Happy programming!




www.mokhengngee.per.sg/book

46

Exercise 2.3

Understanding Code-Behind Pages

There are 2 ASP.NET programming models:
• Single-page programming model and
• 2-page programming model

In exercise 1.3, you were asked to create a text file called luckyno.aspx and save it
in c:\inetpub\wwwroot. Here is the source code for luckyno.aspx again:

<!-- luckyno.aspx -->
<SCRIPT runat="server" language="VB">
Sub Page_Load
Dim r As Random
r = new Random()
lb1.Text = "Your lucky number today is " + _
Convert.ToString(r.Next(100))
End Sub
</SCRIPT>

<HTML>
<BODY>
<FORM runat="server">
<asp:label id="lb1" runat="server" />
</FORM>
</BODY>
</HTML>

Luckyno.aspx makes uses of the single-page programming model: everything,
including the Page_Load method is coded in the same .aspx file. (Remember that
Page_Load is a special method which runs automatically when the Web page loads
up?)

The 2-page programming model involves code distributed between 2 files: the .aspx file
and the code-behind file which may be a .aspx.vb, .aspx.cs, or .aspx.jc file
depending on which language you chose for your project. In the previous exercises in
which you created a project in VS.NET, you have created a Web form based on the 2-
page programming model. Event handler methods are coded in the code-behind file
while visual elements (server controls, HTML elements etc) are placed in the .aspx
file.

We can ‘restructure’ luckyno.aspx so that it follows the 2-page programming model.


ASP.NET Workbook
47
Objective:
• Understand the difference between single-page programming model, and the two-
page programming model

Instructions:

1. Create a new project

Start up VS.NET and create a new VB.NET Web application project. Rename
WebForm1.aspx to luckyno2.aspx. Go to HTML View of luckyno2.aspx
and replace the <HTML> section with the codes below:

...
<HTML>
<BODY>
<FORM runat="server" ID="Form1">
<asp:label id="lb1" runat="server" />
</FORM>
</BODY>
</HTML>

It is important that you do not delete the statement on top which looks like this:
<%@ Page Language="vb" AutoEventWireup="false"
Codebehind="luckyno2.aspx.vb"
Inherits="WebApplication6.WebForm1"%>

Directives: This statement enclosed within <%@ and %> is a directive. Page
directives are enclosed in <%@Page ... %> and are used to declare a number of
attributes about the page. Of particular significance is the Codebehind attribute
here which ‘links’ the current aspx page to its code-behind file.

Table 2-1 shows what some Page attributes mean.

Attribute
Possible Values
Comments
Language A valid .NET
language
Language used by all source codes on
the page.
AutoEventWireup true or false Indicates if the page events are
automatically wired up. If false, events
(such as Page_Load) must be
enabled by the developer.
Codebehind A code-behind
file name
Informs the compiler which file is the
code-behind file for this aspx page.
EnableSessionState true, ReadOnly,
false
If true, the page has access to the
Session object. If ReadOnly, the
page can read but not change session
variables.

www.mokhengngee.per.sg/book

48
EnableViewState true, false
Page’s ViewState is maintained for
server controls.
Inherits Valid class name Code-behind class that this page
inherits.
ErrorPage Valid URL Page to be redirected to if an
unhandled error occurs
Table 2-1: Some Page attributes


2. Edit the Web form

Double click on luckyno2.aspx.vb in Solution Explorer to edit it. This is
luckyno2.aspx’s code-behind file. (If you cannot see this file in Solution
Explorer, click on the ‘Show All Files’ icon in Solution Explorer.)

Notice that there is already a method in luckyno2.aspx.vb called Page_Load.

Fill in Page_Load with the codes below:

Private Sub Page_Load _
(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles MyBase.Load

'Put user code to initialize the page here
Dim r As Random
r = New Random
lb1.Text = "Your lucky number today is " + _
Convert.ToString(r.Next(100))

End Sub

Line continuation in VB.NET: Notice that line 3 in the Page_Load method
(lb1.Text = "Your lucky number today is " + _) ends with an
underscore. In VB.NET and VB6, the underscore is used to indicate that the current
code line is to be continued on the next line. In C# or Java, each code statement ends
with a semi-colon. VB does not use any special character to mark the end of a
statement and each statement starts on a new line. If you want to break a statement
into two or more lines in VB, you need to use the underscore to indicate that the
current statement is to be continued on the next line.


3. Test out your pages

View luckyno2.aspx in a browser, and you should get the same results as
luckyno.aspx. The only difference is how the codes are structured.


ASP.NET Workbook
49
Defaulting to the 2-page model: When a new Web form is added to an ASP.NET
project using VS.NET, it will always be based on the 2-page model type. The 2-page
model is used in all ASP.NET projects. What are the advantages of using the 2-page
model over the single-page model?

The main advantage about the 2-page model is that it allows a cleaner separation of
presentation-centric code and logical execution code. We place the presentation-
centric ‘material’ (such as controls, HTML codes, client-side JavaScript etc) in the
.aspx page, and the business logic (such as event-handler codes, special page life-
cycle methods including Page_Load) in the code-behind .aspx.vb file.



Exercise 2.4
Creating a More Complex Web Form with Other Server
Controls

In this exercise, you will create a new Web form which allows the client to enter student
information such as name, email address, sex and telephone number. The page also
provides a submit button, which when clicked, will add this information to a TextBox
which will also be displayed on the same page.

Objectives:
• To create a more complex Web form
• Try out the server radio button list, drop down list and check box controls

Instructions:

1. Create a new project

Create a new ASP.NET project with VB.NET. You may want to rename
WebForm1.aspx to some other name. Add the Web server controls to the Web
form and change the (ID) property and other control property values as indicated in
the following table:

Control type
ID
Property values to be modified
asp:TextBox tb_name -
asp:TextBox tb_tel -
asp:TextBox tb_email -
TextMode: MultiLine
asp:TextBox tb_records
ReadOnly: True

www.mokhengngee.per.sg/book

50
asp:DropDownList ddl_course
BorderStyle: Solid
asp:RadioButtonList rbl_sex
RepeatDirection: Horizontal
asp:CheckBox cb_issued
asp:Button bn_insert Text: Insert Record

You should end up with something like figure 2-22.

For labels on your Web form (such as ‘Name’, ‘Course’ etc), use Label controls from
the ‘HTML’ pane (instead of the ‘Web Forms’ pane) of the Toolbox. You can edit the
Label’s text by selecting the Label control, and clicking once on it. Labels dragged
over from the ‘HTML’ pane do not have a Text property which you can change, and
run on the client side instead of the server side by default.

Label dilemma: Why would you prefer to use the (client-side) Label control from
the ‘HTML’ pane instead of the (server-side) Label control from the ‘Web Forms’
pane? In this case, we will not be altering the text of the label programmatically and it
will be more efficient to make use of ‘normal’ client-side labels (which will
eventually become static HTML text in <DIV> elements). Do not make these label
controls ‘run as server control’ since there is no need for them to be processed at the
server.



Figure 2-22: The controls on the form






ASP.NET Workbook
51
2. Populate the DropDownList Control

Select the DropDownList control and view its properties. Scroll down to the Items
property and click on the tiny button with the “…” (figure 2-23).


Figure 2-23: Setting the Items property of your drop down list control

The ListItem Collection Editor pops up (figure 2-24). Here is where you can add in
item values which the DropDownList will show.


Figure 2-24: Adding members into the drop down list of your DropDownList
control

Click on the ‘Add’ button.

On the right of the ListItem Collection Editor, type in a course name (such as
‘Diploma in Business Informatics’) in the ‘Text’ field, and a unique value (such as
‘DBI’) in the ‘Value’ field and click on the ‘Add’ button on the left. The ‘Text’ is
what the user sees in the drop down list, and the ‘Value’ is what gets sent back to the
server as the value of this DropDownList when the form is submitted.


www.mokhengngee.per.sg/book

52
Insert a few courses in the same way. Here is an example of the members you can
insert:
Text
Value
Selected
Diploma in Business Informatics DBI False
Diploma in Information Technology DIT False
Diploma in Engineering (Electrical) DEE False
Diploma in Engineering (Manufacturing) DEM False
Diploma in Chemical and Life Sciences DCL False

You can use the up and down arrow buttons in the ListItem Collection Editor to alter
the order in which the course names appear in the DropDownList. Click on ‘OK’
when you are done. Switch to HTML View to examine what has been done to your
Web form.

3. Populate the RadioButtonList Control

Select the RadioButtonList control and view its properties. Scroll down to the Items
property and click on the tiny button with the “…”. Add in the following items:

Text
Value
Selected
Male M True
Female F False

Select the ‘ListItem’ member and click on ‘Remove’ (figure 2-25).


Figure 2-25: Delete the ‘ListItem’ member from the RadioButtonList control


Populating Lists: In this exercise, you are populating the DropDownList and
RadioButtonList controls manually. This isn’t exactly good practice for real
applications. For more flexibility and convenience for future changes, you should be
populating such controls programmatically at the server side (such as in the
Page_Load method). The members can be read off a configuration file (such as
Web.config, which will be covered later) or from a database table, and bound to
the DropDownList or RadioButtonList control in Page_Load.

ASP.NET Workbook
53

To programmatically insert a string into a DropDownList with an ID of ddl_temp,
you can do this:
ddl_temp.Items.Add("some string")


4. Write the event handler for the Insert Button

Double click on the Insert Button and fill up the event handler:

Private Sub bn_insert_Click _
(ByVal sender As System.Object, ByVal e As System.EventArgs)_