Beruflich Dokumente
Kultur Dokumente
Intended Audience
The targetted audience for this tutorials are:
Engineering and Computer Science Students
Beginner level programmers who want to develop their career in ASP.NET based web
development.
Senior programmers who like to switch over to ASP.NET web programming.
What do we offer?
The ASP.NET tutorials in this site include several chapters. We are still adding more and more chapters
everyday. These tutorials may be completed by end of the year 2005.
Many chapters in this tutorials include small small exercises you can try on your computer.
By end of this tutorials, we will start an advanced 'Shopping Cart' project. We will lead you through each
and every step of developing a large dynamic website.
Also, some of the last chapters will guide you through the webmaster world which may help you develop
and own your commercial websites and even make money from running your own websites.
The browser breaks up the URL into these parts and then it tries to communicate with the server looking
up for the server name. Actually, server is identified through an IP address but the alias for the IP address
is maintained in the DNS Server or the Naming server. The browser looks up these naming servers,
identifies the IP address of the server requested and gets the site and gets the HTML tags for the web
page. Finally it displays the HTML Content in the browser.
You can create your own simple browser application using C++, C#, VB.NET or any other
language you like. All you need to know is, how to compose a request which web server can
understand, how to parse and display the response from web server and communicate with
webserver using HTTP protocol.
Even though the basic job of browser is just send requests to web server and receive response
from the server, modern browser provide several other enhanced features including
Back/Forward buttons, save viewed files to disk so that they can be viewed later, cache images
so that the same images need not be downloaded again and again etc.
Internet Explorer, Netspace, Mozilla are some of the popular web browsers currently available
in the market.
Netscape was the most popular web browser till 4-5 years back, but currently more than 90% of
the internet users use "Internet Explorer" to browse the websites.
Developers are often confused about the difference between Windows Applications and Web
Applications. This chapter gives brief information about various types of computer applications and
provides an introductions to web applications.
Embedded Systems
Have you ever used a digital diary (also called 'digital organiser') or a mobile phone ? Do you know when
you save a name and address, how does it get saved in it?
It is a small computer program 'Embedded' in that device. It is similar to any small address book computer
program that you can write using your favorite visual basic or c++. The only difference is, it is written using
soem special language and 'embedded' into a chip in the device inside the mobile phone or digital diary.
If you find a bug in a regular computer program, you can simply write a better program, compile it and
copy to your computer. But if you find a bug in your mobile phone's embedded program, you cannot copy
it! The manufacturer has to embed the new program in a new chip and replace the chip in your mobile
phone!!
Windows Applications
If you don't know what is a 'Windows Application', probably you have never seen a computer. Almost any
application you see on a desktop computer is called 'Windows Application'.
It is also called 'desktop applications' since they are mostly used in desktop computers.
Some common examples of desktop applications are:
1. Paint Brush program
2. Calculator program
3. MSN Messenger
4. Yahoo Messenger
The first three windows applications are written by some programmers sitting in Microsoft office and they
give it free to all who buy Windows operating system. The Yahoo messenger is written by Yahoo
programmers and they give it free to download from their web site.
If your neighbour ask you to write small 'Address book' application for his personal use, you are going to
write a 'windows application'.
Now you must have a good idea of what is windows application.
Web Applications
I am sure you have seen atleast one web application! Do you know how I guessed it?
It was easy to guess. This tutorial is a web application and you are currently reading this tutorial from our
web site (unless you copied it to somewhere...)
Hope this chapter gave a clear picture about web applications and how they are different from windows
applications.
be always connected to high speed internet. However, to develop a web application, you don't need to
worry about security and internet connectivity. You can use your own development computer as the 'Web
Server'.
So, your development computer must have all the 4 systems mentioned above.
Since this tutorial is guiding you to develop web sites using ASP.NET, all the tools we are going to talk
here will be the ASP.NET specific tools.
Web Server
There are several types of web servers. But if you like to develop ASP.NET web applications, you need a
specific web server called 'Internet Information Server' (IIS).
IIS comes as part of Windows. But it is not installed by default, when you install Windows. Please see the
chapter 'Installing IIS' to find more about installing IIS.
You can simply drag and drop html controls to the web page and VS.NET will automatically write
the HTML tags for you.
Start typing an HTML tag and VS.NET will complete it! When you start typing a tag, VS.NET will
show you the HTML tags starting with the characters you typed. So, you don't need to even
remember all the tags.
If you type any HTML tags wrong, VS.NET will highlight the errors and tell you how to correct it.
So, even if you are not an expert, VS.NET can help you develop great web pages.
Browser
You need a browser to view the web pages you create. If you have any windows operating system in your
computer, you will already have a free browser (called 'Internet Explorer')
Database program
A database program like MS Access or SQL Server is required only if you need to save data into
database. It is not mandatory that all web sites need a database program.
The Windows Components Installation Wizard may prompt you to insert the CD for WIndows. So, keep
the Windows CD handy. Or, if you have the I386 folder copied in your hard drive, you can use that when
you are prompted to insert the CD.
Method 2: Go to the "start" menu, select "Run" and then type "inetmgr". Press "OK" to open the IIS tool.
The IIS admin tool look like this:
In the above image, the name "MANJU" represents the computer name. Under the node "Web Sites", it
displays all the web sites. When you install IIS, it creates a default web site for you. Under the "Default
Web Site" node, you can see all virtual directories listed.
Only on server operating systems like 'Windows 2000 Server' or 'Windows 2003 Server', you can create
multiple Web Sites. In other systems like Windows XP, Windows 2000 Professional etc, you can have
only 1 web site (which is the 'Default Web Site' created by the system). But you can have any number of
web applications under this default web site. Each web application will need to be created as a 'virtual
directory' under any one of the 'web sites'. If you do not have a server operating system
, you have to always create your web applications under the 'Default Web Site'.
Each web application you create in your machine needs a virtual directory. In the above image, we have
two web applications (named 'WebApplication1' and 'WebApplication2')
When you create a new ASP.NET project using Visual Studio .NET, it will automatically create a virtual
directory for you.
For example, if you create a new ASP.NET project using Visual Studio .NET called "ShoppingCart", it will
create a new virtual directory with the name "ShoppingCart". After you create the ASP.NET project, you
can see the virtual directory listed in the IIS.
You can right click on the virtual directory name in IIS and select 'Properties' to view various properties of
the virtual directory. One important property is "Local Path". The "Local Path" property represents the
actual location of the web application.
By default, when you create a new ASP.NET project, visual studio creates the project under the folder
"C:\Inetpub\WWWRoot". For example, if you create a new ASP.NET project called "ShopCart", VS.NET
creates a folder called "C:\Inetpub\WWWRoot\ShopCart" and all files related to the proejct will be placed
inside this folder. This folder will be set as a "Virtual Folder" so that you can access the web site using the
URL "http://localhost/ShopCart".
If you are working on several projects, you may want to organize your projects in some specific folder
instead of "C:\Inetpub\WWWRoot". What you need to do is, create a virtual folder manually before you
create the project.
For example, if you need to create an ASP.NET applciation called "Shopcart" under the folder
"C:\MyProjects", first create the folder "C:\MyProjects\Shopcart". Now convert this folder as a virtual
folder. Now you are ready to create the project using VS.NET. If the virtual folder already exists, VS.NET
will NOT create a new virtual folder under the WWWRoot folder. It will use the existing virtual folder.
What is "localhost" ?
"localhost" represents "current machine". If you are accessing any web applications in your own machine,
you can use the url http://localhost/XXXXXXX. If your web site is in another machine, you can use the IP
Address of the computer instead of "localhost". For example, if the "Shopcart" web application is in a
computer with the IP Address "128.32.65.21", then you can access the site from your comptuer using the
url "http://128.32.65.21/Shopcart".
2. Browser communicates with a computer in internet called 'Domain Name Server' to find out the IP
Address of the server (Eg: www.aspspider.com).
3. Browser established a connection to the web server at that IP Address.
4. Server composes a 'Request' for the specified URL and sends the request to the web server to which it
has established a connection.
5. The web server identifies the type of the page requested. If it is an asp.net web page, then browser
knows that needs some processing by the asp.net service running as part of the web server. The request
is handed over to the asp.net service. The asp.net service processes the asp.net page and generates the
html output.
6. Web server sends the requested page to the browser.
7. When a response is received by the browser, it displays the web page to the user who typed the URL.
After you typed the URL in the browser, the request sent by the browser may go through several
computers in the internet before it reaches the actual web server.
You must be surprised to know that so many things happen and several computers are involved before a
simple web page is displayed to you. Most of the steps in the above process happens behind the screen.
A visitor need not worry about how a web page is processed and served to the browser.
So, by now you must have got a better picture about how a windows application is different from a web
application. When you run a windows application (desktop application), only one computer is involved in
the whole process. You start an application in your computer and it runs in your computer. But when you
request a web page from your home computer, the request goes through several servers in the internet
and finally it reaches a computer called 'Web Server'. The actual web page is processed in the web
server.
programming and web programming has its own challenging areas. My intention is to explain some of the
challenges faced by programmers when they switch from windows programming to web development.
Since this is an ASP.NET tutorials site, my topics are based on ASP.NET development.
Hackers
There are several hackers looking for opportunities to hack systems in the internet. There are several
security issues you must consider when you develop a web site so that you can secure your web site
from hackers.
Different environments
You do not know what kind of system a user will have. Some users may have Windows XP and some
others may have Windows 98. Some people may be accesing your site using Internet Explorer and others
may be using Netscape browser. Even, within in Internet Explorer, there are several versions available.
You must take care of all these and make sure your application works well with most of the known
browsers and should support multiple versions of the version. Also, application should work well with
different screen resolutions.
What is ASP.NET ?
ASP.NET is the name of the Microsoft technology used for web site development.
ASP.NET is NOT a programming language like C# or VB.NET
ASP.NET development requires a programming language like C# or VB.NET to write code.
ASP stands for Active Server Pages.
There are several other technologies exist for web development (Eg: PHP). ASP.NET is the
technology from Microsoft and it he widely used one.
ASP.NET technology comes with a rich set of components and controls that make the web
development very easy.
Visual Studio .NET is the editor from Microsoft which helps you develop ASP.NET web sites faster
and easily.
IIS is the web server from Microsoft which supports ASP.NET. To develop ASP.NET web sites,
you must have IIS installed in your computer.
In ASP.NET programming, a web page is developed using HTML and a .NET programming language like
C#, VB.NET or J#. You can choose your favourite .NET language to develop ASP.NET pages.
So, now you must be clear that ASP.NET is not a programming language and it requires a language like
C# or VB.NET to develop ASP.NET web sites
The article talks about what you must learn to become an ASP.NET web developer.
You must have read in the earlier chapters that ASP.NET is a technology which includes several other
technologies.
So, unlike C# or VB.NET windows programmers who need to know only the programming language, an
ASP.NET developer must learn several things.
HTML
HTML is a very simple language used to develop web pages. It may not take more than a couple of days
to to become a reasonable good HTML programmer.
VS.NET makes the life of a programmer very easy. It does lot of work in the backgroud for you. When you
create a new web project, it automatically creates a virtual directory for you in the IIS. If you use notepad
to develop web site, you will have to manually create virtual folder in IIS, which requires some knowledge
about IIS. Also, it is 1-click operation in VS.NET to compile and build all web pages. In addition, VS.NET
creates lot of default files and code for you, which you will have to do manually if you are not using
VS.NET. If you want to display a text box or a button control, just drag and drop the control in VS.NET.
There is no need to type even a single line!!
<html>
<head>
<title>Thisismyfirstwebpage</title>
</head>
<body>
<br><br><br><br>
<center>
<fontsize=5color=red>WelcometoSpiderShop!</font>
<BR><BR>
<fontsize=3color=darkgreen>Buysoftwaresandtoolsonlineatvery
lowrates....</font>
</center>
</body>
</html>
Save the above text into a file called "index.html" into the folder "C:\ShoppingCart".
You are done with your first web site. Since you have configured your folder as a virtual directory, you can
access all html files in that folder using a web browser.
Open internet explorer and type the URL
http://localhost/ShoppingCart/index.html
You can see the following output in Internet Explorer:
Welcome to SpiderShop !
Buy softwares and tools online at very low rates....
Try to alter the html in the file and see how it appears in internet explorer. Also, you can create more html
files in the same folder (like index2.html, AboutMe.html etc) and access them using the url
http://localhost/FileName (Eg: http://localhost/ShoppingCart/AboutMe.html)
If your file is already open in Internet Explorer (IE) and you make some changes in the html file, the
changes will not be visible in IE until you refresh the page in IE. Just hit F5 button in IE to reload the page
after you make any changes to the file using notepad.
An html file can have the extensions .htm or .html. An ASP.NET page has the extension .aspx. So, the
very basic difference between an html page and an ASP.NET page is, they have different file extensions.
By looking at the file extension, the web server understands what type of file it is and decides how to
process them. An html file and ASP.NET need to be processed differently by the server.
We said the basic difference is, html and ASP.NET pages have different extensions. So, you may ask
"what if simply change the extension of the file?"
You are right. You can simply change the extension of an html file to make it an ASP.NET page!
In an earlier chapter, you created a simple web site called "ShoppingCart" with an html page
"index.html". Go to the folder "C:\ShoppingCart" and rename the file to "index.aspx". You have created
your first ASP.NET page!
http://localhost/index.aspx
You can see the same output as the html file.
Whatever technology you use to develop the dynamic web pages, a standard browser should be able to
display the page to the visitors.
<ahref=ViewProfile.aspx?UserId=tony>WelcomeTONY!</a>
If the user is NOT logged in, then our ASP.NET code will generate the following HTML:
<ahref=Login.aspx>Login</a>
Did you notice that the above samples show plain html? Depending on various conditions, ASP.NET
generate appropriate HTML. This is what sent to browsers. You can right click on in any web page and
select View Source to see the actual HTML. Try to see the source html of this page.
Browsers always see plain html (the same html you see by Right click -< View Source) . They dont care
how the html is generated, what is the technology or programming language (ASP or ASP.NET or PHP)
used to generate those html etc. . Even if some other company comes up with a new technology for web
development, all browsers will still work as long as those technologies generate proper html.
This is the fundamental concept behind web development. It is very important to understand this concept
clearly before you proceed with ASP.NET programming.
The chapter talks about the difference between Static web pages and Dynamic web pages.
We can broadly classify web sites and web pages into two categories:
1. Static web pages
2. Dynamic web pages
HTML pages cannot be dynamic. All HTML files are static pages. If you want to write dynamic pages, you
must use some technologies like ASP.NET.
The main use of client side scripting is to validate user input before submitting a page to server. For
example, suppose you have a "Registration" page. Once user enter all data and press the "submit"
button, all the user input will be sent to server. In the server side, you may have written vb.net or C# code
to validate all user inputs like Name cannot be empty etc. If the user do not enter a name and press
submit, your server side code will generate an error message and return the page to you.
In this case, the page was sent to the server and came back with an error message. It was an expensive
operation. It consumed lot of resources to send a page to the server and get it back to the browser with
an error message.
If we can catch this validation error in the browser itself, instead of sending to server and coming back
with an error, that will save lot of time and resources. User need not wait to send the page to server and
come back.
Since, a browser does not know VB.NET or C#, you cannot write such code to validate it in the browser.
Client side scripting comes here to help. You can write Javascript, VBScript or JScript code to validate the
name field in the browser itself and submit it to the server only if all user inputs are correct.
You can learn more about client side scripting in coming chapters.
<html>
<head>
<title>Thisismyfirstwebpage</title>
</head>
<body>
<br><br><br><br>
<center>
<fontsize=5color=red>WelcometoSpiderShop!</font>
<BR><BR>
<fontsize=3color=darkgreen>Buysoftwaresandtoolsonlineatvery
lowrates....</font>
</center>
</body>
</html>
As you can see, it is plain HTML even though the page is an aspx page. Yes, you can have plain HTML
inside an ASP.NET page. In this case, there is no server side code and the server has no processing to
do, other than simply returning the HTML content as it is, to the browser. Only when there is some server
side code is present in the code, the server will process it and return the output embedded in other HTML
content.
<%
%>
You can write your favourite C# or VB.NET code inside the <% %> tags and it will be processed by the
.NET runtime to generate html output.
Change the content of your index.aspx as shown below:
<html>
<head>
<title>Thisismyfirstwebpage</title>
</head>
<body>
<br><br><br><br>
<center>
<fontsize=5color=red>WelcometoSpiderShop!</font>
<BR><BR>
<fontsize=3color=darkgreen>Buysoftwaresandtoolsonlineat
verylowrates....</font>
<br><br>
Nowtheservertimeis:
<%
Response.Write(DateTime.Now.ToString)
%>
</center>
</body>
</html>
Now access your page using the URL http://localhost/ShoppingCart/Index.aspx. You will see the following
output in browser:
Nowtheservertimeis:
<%
Response.Write(DateTime.Now.ToString)
%>
Since this page has an extension .aspx, the page will be given to the aspnet service to process it. The
aspnet service will use the .NET runtime to process all lines enclosed between <% and %>.
In the above case, there is only one line of server side code.
Response.Write(DateTime.Now.ToString)
Nowtheservertimeis:
<%
Response.Write(DateTime.Now.ToString)
%>
In the above lines, Nowtheservertimeis:is a plain HTML. The next part gets executes
in the server and returns the current time. So, the final output is:
Nowtheservertimeis:
4/28/20056:33:45PM
What a browser gets back from the server is just the above lines. Your server side code is not there
anymore. It is processed by the server to produce some output!
Now you must have got a better picture about how the server side code works.
In the coming chapers, we will explain how to write advanced code to write a more dynamic page, which
access database and retrieve content just like this Tutorial page.
Nowtheservertimeis:
<%
Response.Write(DateTime.Now.ToString)
%>
Now let us make some minor changes to the code so that we can explain some concepts better. Change
the server side cide in your file Index.aspx under the folder C:\ShoppingCart as shown below:
Nowtheservertimeis:
<%
dimcurrentTimeasstring=DateTime.Now.ToString
Response.Write(currentTime)
%>
We have declared a string variable and assigned the current time to it. Then we are doing a
Response.Write ( currentTime ) so that the value is sent to the page output.
Let us view the new page now in browser. Type the URL
In one of the previous chapters we mentioned that ASP.NET supports any programming language. Let us
try it.
Change your server side code to C# syntax:
Nowtheservertimeis:
<%
stringcurrentTime=DateTime.Now.ToString();
Response.Write(currentTime);
%>
Try to view the page. You will get an error. What happens is, ASP.NET is trying to compile the server side
code using vb compiler and it is giving an error (because it does not understand C# syntax).
<%@Language="C#"%>
The above line must be the first line in the aspx file. This statement tells the aspx page that it has to use
C# compiler to compile the page.
We cannot mix more than one language in one page. If a page uses C# syntax, then you cannot use
VB.NET syntax for some portion of the code in the same page.
You will learn about User Controls in one of the coming chapters. You can develop each User Control
using a different language and place all those controls in one page.
C#
VB.NET
C++
J#
Other companies are developing more .NET languages, which you will be able to use with ASP.NET.
However, the widely used programming languages for ASP.NET are VB.NET and C#
What is VWD ?
VWD is a light weight version of Visual Studio 2005. It has most of the features of Visual Studio so that
you can develop web applications. it comes with all interesting features like intellisense, drag and drop
designer etc.
However, if you are an advanced web developer or if you need to work on windows applications and web
applications at the same time, you may need to go for Visual Studio instead of VWD.
Also, VWD supports only web projects. You cannot create windows applications using VWD. Microsoft
has released separate express editions for windows application development.
Sample projects
Our tutorials are targetted for beginners and we assume most of them are using VWD. So, we provide
majority of our sample projects and code in VWD. Most of the screenshots we show in the tutorials are
refering to VWD.
If you are using Visual Studio, then all the sample projects can be opened in Visual Studio. The only issue
will be, the screens and pictures we refer in the tutorials may be different in Visual Studio.
Make sure you download and install VWD before you proceed with the rest of the tutorials.
LoginName>\MyDocuments\VisualStudio
2005\Projects\MyFirstProject. You will see a file called "MyFirstProject.sln" (assuming
"MyFirstProject" is the name of your web site.)
You will also notice that there is no "Bin" folder and no binary executable created for the web site you
build the web application. The source files are compiled dynamically in ASP.NET 2.0.
Read more about the Bin folder in ASP.NET 2.0.
In the previous chapter you learned the first step to create an application is to create a new web site. Let
us take a look at VWD and see how can you create a new web site.
Go to Start Menu > Programs and select "Microsoft Visual Web Developer 2005 Express Edition". This
will launch the VWD application. Go to the File menu and select "New Web Site". You will get a screen as
shown below:
The screen shows different options to create a web site. For time being, let us start with a ASP.NET web
site. You will learn more about other types of projects later.
Select "ASP.NET Web Site" from the top part of the dialog box.
Now, look at the bottom left corner. It gives you the option to select the language for your ASP.NET
project. You learned in an earlier chapter that ASP.NET is a technology and you need to select a
programming language to develop ASP.NET projects.
Select Visual C# or Visual Basic as the language. We will be using "Visual C#" for this example. So, we
reccommend you also select Visual C#.
The next step is selecting a location. Just above the Language option, you will see an option to select the
location. Select "File System" and in the right side of it, specify the location where you want the project to
be created.
Let us organize all our projects in one location. have you already created a folder called "AspSpider" in
your C drive? If not, create now. We will be keeping all our sample projects under C:\AspSpider.
Now, in the space provided to specify the project location, type the path
C:\AspSpider\MyFirstProject and press OK. You are done! VWD has created a new
project for you. In this case, "MyFirstProject" is the name of your project and "C:\AspSpider\" is the
location where the project will be created.
Go to windows explorer and look at the folder C:\AspSpider\. You will see that VWD has created a
new folder called "MyFirstProject". This is how VS.NET or VWD organize the projects. For each project
(or, web site), a new folder will be automatically created. If you navigate to this folder, you will see that a
set of files are automatically created for you. This is another advantage of using VWD or VS.NET
compared to using notepad. Many required files will be automatically created for you by VS.NET or VWD
and save lot of time for you.
You will notice that there is no solution file and project file under the web site folder. You can learn more
about the location of the solution file in this chapter.
This chapter talks about Visual Studio .NET. If you are using Visual Web Developer Express
instead of Visual Studio .NET, you may skip this chapter.
do not need VS.NET to develop ASP.NET web sites. You can simply use notepad to type your code and
use command line options to compile the code.
But you may not want to use notepad to write web pages, if you want to finish your learning in the next
couple of years!!
VS.NET makes the life of a programmer very easy. It does lot of work in the backgroud for you. When you
create a new web project, it automatically creates a virtual directory for you in the IIS. If you use notepad
to develop web site, you will have to manually create virtual folder in IIS, which requires some knowledge
about IIS. Also, it is 1-click operation in VS.NET to compile and build all web pages. In addition, VS.NET
creates lot of default files and code for you, which you will have to do manually if you are not using
VS.NET. If you want to display a text box or a button control, just drag and drop the control in VS.NET.
There is no need to type even a single line!!
If for some reason, the start up page is not visible for you, or if you cannot locate the New Project button,
you can go to the menu of VS.NET and select File > New > Project
This will popup a screen as shown below, asking you to select a project type.
On the leftside of the screen, you can see the section for Project Types. Here you can select the language
you want to use for your asp.net application. For this sample, let us choose "Visual Basic Projects".
See the section called "Templates". This section allows us to select the type of the project you want to
create. There are several options like "Windows application", "Class Library", "ASP.NET Web Application".
Since we want to create a web application, let us select the template "ASP.NET Web Application".
The last option you have to select the is the location. If you are creating a windows application, you have
to select the folder where you want the project need to be created and the name of the project. In case of
a web application, we have to select the web server and the application name.
The default value for the location may be something like this:
http://localhost/WebApplication1
The first part represents your web server. localhost means you are creating the web site on the local web
server on your own computer.
The second part (WebApplication1) is the name of the web application. The VS.NET will create a new
folder with this name and convert this folder to a virtual directory.
Let us leave the default location (http://localhost/WebApplication1) as it is and press
OK. VS.NET may take few seconds to create a new web application for you.
If your IIS is not properly configured, you may get an error. If the VS.NET fails to create a web application
in the above step, read how to install IIS properly.
If everything is configured correctly, VS.NET will perform the following tasks:
1. Create a new folder called "WebApplication1" (or, whatever name you select)
2. Convert the folder to a virtual directory.
3. Create couple of files for you. (If you use notepad, you will have to create each of these files manually
and type the content. See how much time you saved by using VS.NET)
Virtual Directory
Now let us go to the IIS and see the virtual directory created by VS.NET. If you do not remember how to
open and work with IIS, read this chapter.
If you expand the node Default Web Site in IIS, you will notice that there is new virtual directory created
with the name WebApplication1. You can right click on this virtual directory name and see various
properties of this.
You selected C:\AspSpider\MyFirstProject as the web site location. So, go to explorer and see the folder
C:|AspSpider. You will notice that VWD has created a new folder called "MyFirstProject". This shows that
when you create a new project, VWD creates a new folder with the name of the web site you choose.
(If you used Visual Studio.NET, look into the folder
C:\AspSpider\.)
C:\Inetpub\wwwroot instead of
Look inside the folder "MyFirstProject". You will see couple of files:
Default.aspx
Default.aspx.cs
In addition to the above files, there will be a folder called "App_Data". The "default.aspx" if a web page
created by VWD for you, even though you did not specify it.
Look at the contents of the file default.aspx:
<%@PageLanguage="C#"AutoEventWireup="true"
CodeFile="Default.aspx.cs"Inherits="_Default"%>
<!DOCTYPEhtmlPUBLIC"//W3C//DTDXHTML1.0Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title>UntitledPage</title>
</head>
<body>
<formid="form1"runat="server">
<div>
</div>
</form>
</body>
</html>
Most of the above content is non visible html. Which means, if you run this web site now, you will see a
web page with no content. Select the menu Debug>StartWithoutDebugging (or press
"Ctrl + F5").
This will compile and run the default web page. You will see that internet explorer will be automatically
opened and your web page will be displayed. But as you can see from the content of your page in VWD,
there is no visible content in the page. But if you right click on the web page in internet explorer and view
the source, you will see that the source has the exact same content as what you see in the default.aspx
file in VWD.
Let us try a quick change. Go back to VWD and see the file
<title>UntitledPage</title>
Change it to
<title>MyFirstWebSite</title>
Now compile and run the page again. You will see that the title of the page in the browser is changed to
what you specified.
Welcometomyfirstwebpage
executables. If you are using notepad to develop web applications, you have to use command line tools to
compile each file.
VWD and VS.NET comes with a handy feature to compile and organize all source files. This process is
usually referred to as "build" process.
Before you can run a web site, you must build the project - which means that you must compile all files
files of the project.
Compiling files from command line is a pain. You have to pass several parameters to the compiler
command. You must specify the source file to compile, the name of the binary executable to be generated
etc.
This article explains what happened to the good old "Bin" folder in ASP.NET 2.0
Solution Explorer
This chapter explains what is "Solution Explorer" in Visual Studio .NET
Solution Explorer
Solution Explorer is a window within the VS.NET editor, which allows you to manage various files part of
the solution (web site). This windows displays all the files part of the web site. You may select any file and
view properties, rename, delete or move to other folders through the solution explorer.
By default, Solution Explorer is located on the top right corner of the VS.NET editor. This windows may be
minimized on the top right bar. If for some reason, you cannot view the solution explorer, go to the menu
and select "View > Solution Explorer". This will launch the solution explorer window.
You may click on the tab to expand the solution explorer, as shown below.
The solution explorer shows the list of files associated with the project. You may double click on any file to
open it in the editor.
Note the icons in the top of the solution explorer.
These icons allow you to do certain things related to the project. Some of the icons will be active only
when an aspx page is open in the editor.
The first icon in the above image allows you to view the source code (code behind file) of an aspx page.
The second icon allows you to view the aspx page itself.
See the 5th icon. This allows you to view all files which are in the same directory as the web project but
not included in the project. Click on this to view the files in the same folder which are not included in the
project. Probably you may not have any files to see. Add some files manually to the project folder and
then click on this icon. It will show you the files you copied manually.
You can right click on any file and include in the project or exclude from the project.
Click on the same icon again to hide non-included files.
This chapter explains what is design mode and HTML mode in VS.NET
An aspx page can be opened in 2 modes in VS.NET
Design mode
HTML mode
Design mode
In design mode, you can actually view how the page is going to look like when it is displayed in the
browser. It will show you all the controls like textbox, labels etc. You can drag and drop controls to the
page when it is opened in design mode.
HTML mode
In this mode, you can see the actual content of the aspx page in plain text. Whatver controls you see in
design mode, you will see the corresponding code here.
Ideally, a web page is just one file. For example, if you are viewing a web page called 'Hello.aspx', there
will be one physical file called 'Hello.aspx' located in the web server.
But when you use Visual Studio to create ASP.NET project and web pages, Visual Studio creates several
files for you. Let us look at the solution explorer of the sample project we created in the previous chapters.
AssemblyInfo.vb
Global.asax
Styles.css
Web.config
WebForm1.aspx
We will learn more about each of the above files later. Now let us go to the folder
'C:\Inetpub\wwwroot\WebApplication1'. You will see the physical files created. Here you can see more
files than what you see in the solution explorer.
WebApplication1.vbproj
AssemblyInfo.vb
Global.asax
Global.asax.resx
Global.asax.vb
Styles.css
Web.config
WebForm1.aspx
WebForm1.aspx.resx
WebForm1.aspx.vb
WebApplication1.vbproj is the project file. This file is not visible in solution explorer. The project file is just
a list of other files included in the project. When you double click on a project file in windows explorer,
Visual Studio will open the file and find out the list of files included in the project. Then it displays those
files in solution explorer.
If you like to see the contents of the project file, open WebApplication1.vbproj in notepad. If you can
understand the format of the project file, you can even edit and make changes it in notepad. Remember
that you alter the content of the project file, it may get corrupt and will become useless. So, edit the
project file outside VS.NET only after you become an expert!
The files shown in brown font are not visible in solution explorer. Why? Those are files depending on
other files. The file Global.asax.vb and Global.asax.resx are related to Global.asax. Similarly,
WebForm1.aspx.resx and WebForm1.aspx.vb are related to WebForm1.aspx.
VS.NET hides such related files in the solution explorer so that they are better organized.
If you want to see those hidden files in VS.NET, there are couple of ways.
1. Right click on Global.asax or WebForm1.aspx in solution explorer and select 'View Code'. The .vb file
Click on the icon 'Show All Files' again to hide the related files.
Now let us try another thing now. Go to the physical folder (C:\Inetpub\wwwroot\WebApplication1) of our
project in windows explorer. Right click inside the folder and create a new text file called 'Hello.txt'.
Now come back to the Visual Studio. Since you created this file inside our project folder, you must be able
to view this file in the solution explorer. If you do not see the file, click on the icon 'Show All Files' couple
of times to make sure the view is refreshed. You will see the file 'Hello.txt' with a slightly different icon.
This indicates that this file exists in the folder, but included in our project. If you like to include this file in
the project, right click on the file and select 'Include In Project'. Now the icon will change and the file will
become part of the project.
Since 'hello.txt' is a text file, this file will not be compiled. But if you rename the file to .vb or .cs, then this
file also will be compiled along with other source files and if there is any compilation error, VS.NET will
complain.
Let us learn more about the 'WebForm 1.aspx' in the next chapter.
The contents of the default web page ('WebForm1.aspx') created by Visual Studio looks like this:
<%@PageLanguage="vb"AutoEventWireup="false"
Codebehind="WebForm1.aspx.vb"
Inherits="WebApplication1.WebForm1"%>
<!DOCTYPEHTMLPUBLIC"//W3C//DTDHTML4.0Transitional//EN">
<html>
<head>
<title>WebForm1</title>
<metaname="GENERATOR"content="MicrosoftVisualStudio.NET
7.1">
<metaname="CODE_LANGUAGE"content="VisualBasic.NET7.1">
<metaname=vs_defaultClientScriptcontent="JavaScript">
<metaname=vs_targetSchema
content="http://schemas.microsoft.com/intellisense/ie5">
</head>
<bodyMS_POSITIONING="GridLayout">
<formid="Form1"method="post"runat="server">
</form>
</body>
</html>
Let us analyze each line of the aspx file and try to understand some basic concepts. We will explain only
the simple elements now and leave the complex portions for later study.
<%@PageLanguage="vb"AutoEventWireup="false"
Codebehind="WebForm1.aspx.vb"
Inherits="WebApplication1.WebForm1"%>
The element Codebehind="WebForm1.aspx.vb" says that this file uses the vb file
"WebForm1.aspx.vb". The next element Inherits="WebApplication1.WebForm1 says this aspx page is
inherited from the class WebForm1 which is part of the namespace WebAppliaction1. (You can learn
more about namespaces here.)
So, the above statement binds the 2 files together - WebForm1.aspx and WebForm1.aspx.vb. This is how
VS.NET understands that these files are related and thus hide the .vb file in solution explorer.
WebForm1.aspx.vb is known as the 'Code behind File' for WebForm1.aspx. You will learn more about the
code behind files in the next chapters.
<html>
<head>
<title>WebForm1</title>
<metaname="GENERATOR"content="MicrosoftVisualStudio.NET
7.1">
<metaname="CODE_LANGUAGE"content="VisualBasic.NET7.1">
<metaname=vs_defaultClientScriptcontent="JavaScript">
<metaname=vs_targetSchema
content="http://schemas.microsoft.com/intellisense/ie5">
</head>
<bodyMS_POSITIONING="GridLayout">
</body>
</html>
You must be already familiar with the HTML tags <html>, <head>, <title>, <body> etc. They are
mandatory tags for any html and aspx files. Withotu these tags, any web page is not a valid web page.
<title>WebForm1</title> represents the title of the web page when displayed in the browser. You can see
this title in the top left corner of the web browser when this web page is displayed. If you like, you can
change this title to anything yoiu want.
The following tags are called META TAGS. They are not displayed to the user. They are only for
documentation purpose and for the attention of browsers and other search engines etc who will analyze
and study the web pages in a different way. Even if you delete the below meta tags from your web page,
nothing will happen.
<metaname="GENERATOR"content="MicrosoftVisualStudio.NET
7.1">
<metaname="CODE_LANGUAGE"content="VisualBasic.NET7.1">
<metaname=vs_defaultClientScriptcontent="JavaScript">
<metaname=vs_targetSchema
content="http://schemas.microsoft.com/intellisense/ie5">
You will learn more about META TAGS later.
The following tag is very important for any aspx page.
<formid="Form1"method="post"runat="server">
</form>
The <Form> tags are not mandatory for a web page, but is required for any aspx page if you like to use
any of the web controls provided by ASP.NET. All the web controls must be places within the <Form>
</Form> tags. It is reccommded you place all your html code within these tags.
Let us try a simple example:
Add some simple html to your Form tags as shown below.
<formid="Form1"method="post"runat="server">
<fontsize=5color=red>helloWorld</font>
</form>
Now execute the web page. To compile and run any project in VS.NET, you can simply press Ctrl + F5.
(Or, go to the menu 'Debug > Start without debugging.) This will compile your project and launch the web
page in Internet Explorer.
Sometimes, VS.NET will complain that there is no 'Start Page'. In that case, you can right click on the file
'WebForm1.aspx' in the solution explorer and select 'Set as Start Page'.
When your web page is displayed in the browser, you will see the following:
Hello World
Now you can play around with this file by changing the HTML content. Try your html experience here and
see how the page works.
In the above example, you used an aspx page, but didn't try any real aspx controls. You simply used
some basic html tags in an aspx page. In the up coming chapters you will learn how to use the advanced
asp.net controls to create rich html pages.
Resource File
The .resx file is know as the resource file. You may not use this file much until you need to work on some
advanced features.
The resource file is used to store various resource objects related to the aspx file. You can store strings or
other objects as key-value pairs in this file. You will learn more about the resource files in later chapters.
How to open the code behind file for the aspx page
?
You can right click on the aspx file name in the solution explorer and select 'View Code'. This will open the
code behind file associated with the aspx page.
Alternatively, you can press "F7" from the aspx page to open the code behind file.
How to open the aspx file from the code behind file
?
When you have the code behind file opened in the editor, you can right click on the file name in solution
explorer and select 'View Designer' to view the aspx page.
Alternatively, you can press 'Shift + F7" from the code behind file to open the corresponding aspx file.
And within the aspx page, you can switch between "Design" mode and "HTML" mode by using the links in
the bottom left corner as shown in the top of this chapter.
PrivateSubPage_Load(ByValsenderAsSystem.Object,ByValeAs
System.EventArgs)HandlesMyBase.Load
EndSub
The Page_Load event will be fired when the page is loaded. Let us try a small example. Write the
following code inside the Page_Load event:
PrivateSubPage_Load(ByValsenderAsSystem.Object,ByValeAs
System.EventArgs)HandlesMyBase.Load
Response.Write("Hey,mypageisloaded...")
EndSub
Now compile and run the web page by pressing "Ctrl + F5". You will see the line "Hey, my page is
loaded ..." in the web page.
Note that, you will not use Response.Write much in your asp.net programming. Instead, you will
use ASP.NET web cotnrols to display data dyamically. You will learn more about the web controls in the
later chapters.
Label
Textbox
Button
Listbox
Datagrid
Let us try the most simple web control - the Label control. Label controls are used to display text in the
web page.
VS.NET allows you to drag and drop any web controls to the web page. Open your default aspx page and
select the 'Design' mode. Now click on the 'Toolbox' on the top left corner of the VS.NET. The toolbox will
be available only when you have the aspx file opened in design mode.
From the toolbox, drag and drop a Label control to the web form. Now switch to the 'HTML' mode. You
can see the difference. What happened when you dropped a Label control to the web form is, VS.NET
just added a line of code to the aspx page. The code looks like this:
<asp:Labelid="Label1"style="ZINDEX:101;LEFT:232px;
POSITION:absolute;TOP:56px"runat="server">Label</asp:Label>
In fact, you can manually type this line of code instead of doing the drag and drop. After typing this code,
if you switch to the design mode, you can see the Label control.
Note the id="Label1" in the above code. It says the id of the control is "Label1". You can use this id
in the code behind file to manipulate the Label control.
Switch to design mode and double click on the Form. This will create a Page_Load event handler. Write
the following code in the Page_Load event handler:
Label1.Text="WelcometomyFirstASP.NETPage.CurrentServer
timeis"&DateTime.Now.ToString()
Ok, now compile and run the page by pressing Ctrl + F5. You can see the above text and the server time
displayed in the web page.
Alternatively, you can type the tags in the aspx page in HTML mode and switch to design mode to view
your changes. Be carefull when you type the properties manually. If you make any mistakes, it will be
difficult to identify and solve the error.
Now run the application and see how the text appears in the web page. Play around with other properties
of the Label control and get familiar.
Some of the commonly used properties are:
ID
Font
Text
Width
Since this is a simple control used to display text to users, the events associated with this control are not
commonly used. But the events are important for other controls like Textbox, Button etc. You will learn
more about these controls in the coming chapters.
Label1.Forecolor=Color.FromName("GREEN")
Label1.Text="Successfullyprocessed."
Run the page. You will see your message in green color.
Now change the code as shown below:
Label1.Forecolor=Color.FromName("Red")
Label1.Text="Anerroroccurred."
If you run the page now, it will show your message in red color.
In the above example, "Color" is a class part of .NET Framework and "FromName()" is a method of this
class.
Using the above approach, you can change any of the properties of the web controls at run time. In
addition to changing the properties, you can retrieve the values also from the web controls using the
same approach. For example, if you have a Textbox control in the web page, you can get the value typed
by user using the above approach.
You will learn more about Textbox control and its properties in the coming chapters.
Id - lblMessage
Label 2:
======================
Id - lblLabel
Text - What is the current day?
Textbox
======================
Id - txtCurrentDay
Text - Monday
Button
======================
Id - btnSubmit
Text - Submit
Arrange the position of the controls so that they look as shown below:
PrivateSubbtnSubmit_Click(ByValsenderAsSystem.Object,ByVale
AsSystem.EventArgs)HandlesbtnSubmit.Click
EndSub
Notice the HandlesbtnSubmit.Click. This statement says this is the method that handles the
Clickevent for the button btnSubmit.
You can change the event handler name btnSubmit_Click() to whatever you want and it will still
work as long as HandlesbtnSubmit.Click is there at the end of it.
privatevoidbtnSubmit_Click(objectsender,System.EventArgse)
{
}
Note that there is no HandlesbtnSubmit.Click in the end of the event handler declaration.
Instead, there is another hidden lin as shown below:
this.btnSubmit.Click+=new
System.EventHandler(this.btnSubmit_Click);
The above line is hidden within the #regionWindowsFormDesignergenerated
code. You may need to click on the + sign on the left end of the line #regionWindowsForm
Designergeneratedcode to view the hidden code in this region.
In C#, the line this.btnSubmit.Click+=new
Handling events
Ok, now you have created an event handler for the button clicked event. Let us write some code.
What we are going to try is, get the text user typed in the Textbox and compare against the current day. If
the day user typed matches with current day, we will display a success message in the label. If the day
does not match, we will display an error.
Copy and paste the following code below to your event handler.
DimuserDayAsString=txtCurrentDay.Text
DimcurrentDayAsString=DateTime.Today.DayOfWeek.ToString()
IfuserDay=currentDayThen
lblMessage.Text="Great!Yougotitright."
lblMessage.ForeColor=Color.FromName("DarkGreen")
Else
lblMessage.Text="Oops!Youarewrong.Todayis'"¤tDay
&"'."
lblMessage.ForeColor=Color.FromName("Red")
EndIf
Here is the C# code, if you are working on C#.
stringuserDay=txtCurrentDay.Text;
stringcurrentDay=DateTime.Today.DayOfWeek.ToString();
if(userDay==currentDay)
{
lblMessage.Text="Great!Yougotitright.";
lblMessage.ForeColor=Color.FromName("DarkGreen");
}
else
{
lblMessage.Text="Oops!Youarewrong.Todayis'"+currentDay
+"'.";
lblMessage.ForeColor=Color.FromName("Red");
}
Please note that there is only syntax difference between C# code and VB.NET. So, here onwards, we will
provide the example code only in one language.
Now let us run the web page to see how it works. You may need to right click on your form
(WebForm2.aspx) and select 'Set as Start Page' so that when press 'Ctrl + F5', this new page will be
launched instead of your default page.
Build and launch the web page. You will see the textbox appearing with the default value 'Monday'. Press
the 'Submit' button. If your current day is a Monday, you will get a success message. Otherwise, you will
see the error message.
The code is self explanatory. The call DateTime.Today.DayOfWeek.ToString() returns
the current system day and you are comparing aginst the data typed by the user. You can retrieve the text
typed by user by accessing the property txtCurrentDay.Text.
if(userDay.ToUpper()==currentDay.ToUpper())
Make a small change as shown above. Here we are converting the user typed text into all upper case. We
are converting the system day also into upper case. So, whatever user typed does not matter. Everything
is converted into upper. Now run the page and you will see that user can type in any case (upper or lower)
and it will still match. If you take care of such small small things, you can write great applications.
currentDay.ToUpper()), you had to actually change in two places because you had copied
and pasted the same code in two places.
You should never copy paste the same code in two places. Instead, you must move that code into a
method and call the same method from both the places. This way, if you need to make any change, you
need to make the change only once.
See the improved code:
PrivateSubbtnSubmit_Click(ByValsenderAsSystem.Object,ByVal
eAsSystem.EventArgs)HandlesbtnSubmit.Click
'Callthecommonmethod
ValidateUserData()
EndSub
PrivateSubtxtCurrentDay_TextChanged(ByValsenderAs
System.Object,ByValeAsSystem.EventArgs)Handles
txtCurrentDay.TextChanged
'Callthecommonmethod
ValidateUserData()
EndSub
'Thisisthecommonmethodwhichvalidatestheuserinputand
displaystheresult.
PrivateSubValidateUserData()
DimuserDayAsString=txtCurrentDay.Text
DimcurrentDayAsString=DateTime.Today.DayOfWeek.ToString()
IfuserDay.ToUpper()=currentDay.ToUpper()Then
lblMessage.Text="Great!Yougotitright."
lblMessage.ForeColor=Color.FromName("DarkGreen")
Else
lblMessage.Text="Oops!Youarewrong.Todayis'"¤tDay
&"'."
lblMessage.ForeColor=Color.FromName("Red")
EndIf
EndSub
This is a fundamental concept you have to learn. Always break your code into small small methods and
call these methods in your application.
ASP.NET Objects
This article explains various objects used in ASP.NET programming.
We mentioned in come of the previous chapters that ASP.NET uses object oriented languages like C# or
VB.NET. You can use any classes available in the .NET library to write robust programs.
ASP.NET provides some Classes which make web development easier. Some of the classes used
specifically for ASP.NET development are:
System.Web.HttpRequest
System.Web.HttpResponse
System.Web.SessionState.HttpSessionState
System.Web.ApplicationState
System.Web
In object oriented programming, if you want to create an object of a class, you may use a syntax like
below:
dimmySocketasSocket=newSocket()
In the above example, we are creating an object ('mySocket') for the class 'Socket'. Similary, if you need
to create an object of class 'System.Web.HttpRequest', it must be something like this:
dimrequestasSystem.Web.HttpRequest=new
System.Web.HttpRequest()
But the ASP.NET system has made your life easier. An object called 'Request' is already created for you,
which is ready to use. You do not need to create an object for the class System.Web.HttpRequest. The
name of the object is 'Request'.
Similary, there are objects created by default for the other classes like HttpResponse,
System.Web.SessionState.HttpSessionState and System.Web.ApplicationState. The name of objects are
'Response', 'Session' and 'Application' respectively.
In one of the previous chapters, you learned how to display the current time using the Response.Write()
method. 'Response' is the name of the object for the class 'HttpResponse' which is created by the system
for you. That is why we could use 'Response.Write()' without creating an instance of the class
'HttpResponse'.
The above mentioned 4 objects are widely used in ASP.NET programming. It is important to learn these
objects and their methods. You will learn more about these objects in the coming chapters.
What is in a Request ?
As you can think, a request obviously includes the URL which is requested. In addition to that, a Request
includes several other information, including:
1. Details about the browser who makes the request (like version number, browser type etc)
2. Computer information like screen resolution, IP address of the user etc.
3. Cookies - the information stored in the client machine by the same web site.
4. Data inputted by the user (for example, when you register in a site, you are entering your registration
details in the input fields. These details are sent to the server as part of the 'Request')
The ASP.NET provides a class called HttpRequest which is defined in the namespace
System.Web. This class provides various methods and properties which help you use various
information related to a web request.
An instance of this class is created by default in all the pages, so that you can use this object without
creating again each time in all the pages. The name of this object is Request.
In old ASP days, the Request object was the only way to retrieve the input data entered by the user in the
input fields in the page. ASP.NET provides the event handling mechanism and web controls so that you
can access user inputs in a more easy way.
Request.QueryString
This method is used to retrieve short key value pairs passed along with the URL. For example, if you can
look at the URL of this page, you can see a query string called TutorialId and a value of 35. We
pass this query string to indicate which chapter need to be displayed. You may simply change the Tutorial
Id in the URL and this page will display the appropriate chapter.
In our ASP.NET code, we will check for the current Tutorial Id using the following code:
'GetthecurrenttutorialIdfromthequerystring.
dimtutorialIdasInt32=Request.QueryString("TutorialId")
'NowgetthechapterfromdatabasebasedonthetutorialId.
If the tutorialId is invalid or a chapter not found for the corresponding tutorialid, this page will show an
error.
Request.Cookies
Cooikes are used to store small pieces of information in the client computer. Many web sites store
information like when did you visit their site last, your user name etc.
When you login to a site and choose the option 'Remember my password', do you know how they
remember your password? Your user name is stored in a cookie in your computer.
For example, when you login to this site, if you choose the option 'Remember my password', we will save
your user name into a cookie in your computer. If you come back to our site again later, we will read the
DimcookieAsSystem.Web.HttpCookie=
Request.Cookies("AspSpiderUserId")
ifcookieisnothingthen
Response.write("Cookie'AspSpiderUserId'notfound.")
else
Response.write("ValueofCookie'AspSpiderUserId':"&
cookie.Value)
endif
If the user name already exists in Cookie, we understand that you selected the option 'Remember my
password' last time. So, we will not ask for your password again. We will automatically login you to the
application.
Many sites use Cookies to store more information like when did you visit their site last, what are the
pages you visited etc. For example, if you go to an online shopping site and add few items to the
shopping cart, they will store this information to the Cookies. When you come back to the same site
again, those items will be automatically there in your Shopping cart because they had saved it in your
computer cookie and put into your shopping cart when you came back to the site.
Request.ServerVariables
This property can be used to extract specific information about the client who is making the request. For
example, if you want to find the server IP address of the computer who is visiting your web page, use the
following code:
dimipAddressasstring=Request.ServerVariables("REMOTE_HOST'")
Response.Write("YourIPAddressis:"&ipAddress)
You can find which version of browser they are using to access your web site.
dimbrowserasstring=
Request.ServerVariables("HTTP_USER_AGENT'")
Response.Write("Youareusingthisbrowsertoaccessourweb
site:"&browser)
There are several server variables available to find more information from the Request. Try the following
server side code in your web page:
dimstrasstring
ForEachstrinRequest.ServerVariables.AllKeys
Response.write("Key:'"&str&"'Value'"&
Request.ServerVariables(str)&"'")
Next
What is a Response ?
In the web server world, a Response is exactly opposite to the Request. A 'Response' is the message
sent from the web server to the client, when client makes a 'Request'. For each request from a client, the
server gives a response, unless there is an error.
When you type a URL in a web browser or when you click on a hyper link in any web page, your browser
makes a 'Request' to the server for the specific URL. Then server process the request and send a
response back.
This article explains the frequently used Methods and Properties of Request object
Response.Write(DateTime.Now.ToString())
The above code will generate the current time as text and display to the user. But note that the text will be
displayed on the top of the page. There is no way you can specify the location and format the text.
If you want to move the location of the text, you may have to do something like below:
Response.Write("<tablewidth=500>")
Response.Write("<tr>")
Response.Write("<tdalign=right>")
Response.Write("<BR>")
Response.Write("<BR>")
Response.Write("<BR>")
Response.Write(DateTime.Now.ToString())
Response.Write("</td>")
Response.Write("</tr>")
Response.Write("</table>")
ASP.NET provides several web controls including the Label control which allow you to specify the exact
location where you want the control to be displayed. Due to this, the Response.Write() method is
not widely used now.
Response.Cookies
Cookies are used to store small pieces of information in the client computer. In ASP.NET, the Response
object is used to send cookies to the client browser. If you select the 'Remember Me' option at the time of
login, we use the following code to store your user id in a cookie in your computer. When you come back
to this site later, we retrieve the user id from the Request and load your information automatically, without
asking you to login again.
Response.Cookies("AspSpiderUserId").Value="youruserid"
Response.Cookies("AspSpiderUserId").Expires=
DateTime.Now.AddDays(7)
We use the above code to store your user id in a cookie. The name of the cookie used is
"AspSpiderUserId". The cookie will expire after 7 days. This means, if you come back to our site after 7
days, we will not remember you! So, come back often!
As you saw in the previous chapter, the Request object is used to retrieve the values from the cookie.
DimcookieAsSystem.Web.HttpCookie=
Request.Cookies("AspSpiderUserId")
ifcookieisnothingthen
Response.write("Cookie'AspSpiderUserId'notfound.")
else
Response.write("ValueofCookie'AspSpiderUserId':"&
cookie.Value)
endif
Response.Redirect()
This may be the most frequently used method of the Response object. Response.Redirect() is used to
redirect user from one page to another page or website.
Response.Redirect("Login.aspx")
When the above line of code is executed, the page will be redirected to the login page. Let us see another
example.
if(bStatus=True)then
Response.Redirect("Success.aspx")
else
Response.Redirect("Error.aspx")
endif
The above code redirects to error or success page according to the status of some operation performed.
For example, when user try to login to the website, if the user name and password are correct, the page
can be re directed to a welcome page. Otherwise, an error page can be displayed.
What is a session ?
A session represents the relationship between a client(browser) and the webserver, during the period the
user is actively accessing the website.
The relation between a client(browser) and web server is 'Stateless'. This means, once a browser
requests a page and server returns it, there is no direct connection between browser and server (until the
next page is requested). Once a page is returned by the server and displayed in the browser, the user can
view the page as long as he wants.
However, even though there is no connection is retained between the browser and web server after a
request is served, the webserver will still remember the browser's Identity for 'some more' time. If the
browser requests another page within this short timeframe, the server knows that this is a repeated
request from a browser it knows. This mechanism is called "Session".
Usually, I take more than 20 minutes to type one chapter in this tutorials. By the time I type this chapter
and press 'Submit', my session will expire and I will get an error saying 'You cannot submit a tutorial. You
have not logged In". So, now a days, I will type everything in notepad
and then copy paste many chapters to this site in one shot.
A session lives for this duration (20 minutes by default) even if you close the browser. The reason is, if
you close the browser or shutdown your browsing computer, the server will never know it. It will still
remember your session and wait for another request from you until it times out.
The only way a session can be lost before the timeout period is, restarting the IIS in the web server. If the
IIS is restarted, all the sessions will be lost and all requests coming up after that will be treated as new
requests.
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data
source=127.0.0.1;Trusted_Connection=yes"
cookieless="false"
timeout="20"
/>
The line timeout="20" represents the timeout value in minutes. You can change this value to any
value you want.
If you reduce timeout to a small number, the sessions will timeout faster and your users may experience
automatic logout if they take few minutes to read a page.
If you increase this number to a very big number, your server will remember each session for this long
duration of time, even if the user close the browser and go home! This will be an overload for the server
consuming lot of memory. For heavy traffic web servers, there will be some limitaion on the total sessions
it can handle.
What is in a session ?
A session has several information including a session ID. Some information is created and used by the
server itself. But the most important use of session is, it allows to store custom information.
You can store any key-value pairs in session.
Session("UserId")="john"
In the above sample, the value "john" is assigned to a session variable called "UserId". One important
different here is, you do not declare the session variable as any datatype. Just assign any value to any
session variable. The session variables will be automatically created when you simply assign values to
them.
work. But if you try to access the Page2.aspx from another browser or close your original browser and
open again, the session variable would have lost it's value because a new session is created.
if(bLoginSuccess=true)then
Session("UserId")=txtLoginName.Text
Session("Name")=GetUserNameFromDatabase(txtLoginName.Text)
else
Response.Redirect("LoginError.aspx")
endif
The above code stores the user's userid into a session variable called "UserId". All other pages will check
if the user id is set in the session and if not, it will give an error message saying "you have not logged in".
dimuserIdasstring=Session("UserId")
if(userId="")then
Response.Redirect("Login.aspx")
else
Response.Write("Welcome"&Session("Name"))
endif
The above validation will be required only in the pages which needs user login. For example, in
AspSpider.com, you can access most of the pages without logging in. Only when you submit an article or
feedback, we will use the above code and validate your login. If you are not logged in, we will redirect you
to login page automatically.
If you look at the top left corner of this site, you can either see 'Login" or "Welcome <Name>". We have
used a logic similar to what is shown below, to display appropriate message.
dimuserIdasstring=Session("UserId")
if(userId="")then
Response.Write("<ahref='Login.aspx'>Login</a>")
else
Response.Write("Welcome<ahref='MyAccount.aspx'>"&
Session("Name")&"<a>)
endif
As you can see from the above examples, session variables are used to store small key-value pairs in the
memory. You can use session variables to store values from one page and access the values from other
pages for the same user. If you set a value in session variable from one page, you can retrieve the value
from any other page in the same session.
The most important point to remember is, whatever value you store in session will be valid only until the
session expires. Also, this value will not be accessible for another user/session.
session times out, then this ID will be no longer valid. In such cases, server will create a new session and
will treat this request as a new request.
Application Variables
Just like you can store values in session variables, you can store key/value pairs in Application variables
too. The scope of an Application variable is the entire web application, while the scope of a session
variable is only a particular session.
For example, if you assign a value into an Application variable as shown below, all users of the web site
can access this value.
Example:
Application("CurrentStockPrice")=145.25
You can store values that do not change often and store them in the application variable. For example,
your web site displays the current stock price of your company in the top of all pages of your web site.
This stock price is not specific for any users. You may need to access other government agencies
database to retrieve this value.
There is no need to contact an external agency and get this value for all pages displayed in the site. You
can retrieve it once and save into an Application variable.
Once the value is retrieved and stored in Application variable, you can get it from this variable and display
in all the pages. It will be several times faster to retrieve value from application variable (which is in the
memory) than accessing an external agency.
Example - storing to application variable:
Application("CurrentStockPrice")=GetFromExternalAgency()
Example - retrieving from application variable:
lblStockPrice.Text="StockPrice:"&Application("CurrentStock
Price")
object in ASP.NET
This article explains the Application object and it's various methods in ASP.NET
In an ASP.NET page, the Application object represents the web application in which the page belongs.
.NET provides a class called HttpApplication, which is part of the System.Web namespace. This class
represents the Application object in ASP.NET. An instance of this class is already created for you and this
is called "Application". You can access various methods and properties of the class HttpApplication using
the object "Application".
Application Variables
Just like you can store values in session variables, you can store key/value pairs in Application variables
too. The scope of an Application variable is the entire web application, while the scope of a session
variable is only a particular session.
For example, if you assign a value into an Application variable as shown below, all users of the web site
Application("CurrentStockPrice")=145.25
You can store values that do not change often and store them in the application variable. For example,
your web site displays the current stock price of your company in the top of all pages of your web site.
This stock price is not specific for any users. You may need to access other government agencies
database to retrieve this value.
There is no need to contact an external agency and get this value for all pages displayed in the site. You
can retrieve it once and save into an Application variable.
Once the value is retrieved and stored in Application variable, you can get it from this variable and display
in all the pages. It will be several times faster to retrieve value from application variable (which is in the
memory) than accessing an external agency.
Example - storing to application variable:
Application("CurrentStockPrice")=GetFromExternalAgency()
Example - retrieving from application variable:
lblStockPrice.Text="StockPrice:"&Application("CurrentStock
Price")
You will learn more about the Cache class in upcoming chapters.
What is a cookie ?
Cookies are small files stored on the client computer.
yourloginname@websitename.txt
A cookie from AspSpider.com can be like this:
john@aspspider.txt
These are the cookie files stored in your computer by various web sites. In addition to the cookie files,
there will be one file called "index.dat". This is a file used by Internet Explorer to track all the cookie files.
You may delete all the cookie files from the "Cookies" folder. But you may need to re login to all the
websites where you have specified 'Remember my login', because those web sites can't find your user
information any more from the Cookies.
There is another way to delete all the Cookies. Open Internet Explorer and select the menu "Tools >
Internet Options". Press the button "Delete Cookies". This will delete all cookie files from your computer.
Response.Cookies("UserName").Value="Mr.John"
Response.Cookies("UserName").Expires=DateTime.Now.AddDays(1)
In the above sample code, the first line will save a cookie with the name "UserName" and value "Mr.
John" to the client computer.
The second line says that this cookie is valid for 1 more day from current time.
As shown above, you can store any key-value pairs to client computer as cookies.
DimnameAsString=Me.context.Request.Cookies("UserName").Value
If there is no cookie with the name "UserName", the above code sample will return an empty string.
DimmyCookieAsNewHttpCookie("UserName")
myCookie.Value="Mr.John"
myCookie.Expires=DateTime.Now.AddDays(1)
myCookie.Domain="aspspider.com"
Response.Cookies.Add(myCookie)
what to do with each piece of data in the response. It saves the cookies to your local computer, and
displays the page content in your browser.
Now, you might have understood why you use
Response.Cookies("UserName").Value=
"Mr.John" to save cookies to client computer. You are actually adding a cookie to the response
which will be sent to the browser.
The same thing happens when you retrieve cookies from the Request object. Everytime when browser
makes a request, it sends a "big packet" to the web server. This big packet contains lot of information
including the URL requested, details about the brower itself and all the cookies stored in the client
computer from that website. This is why you are able to retrieve the cookie information from the "Request"
object.
Configuration File
In the simple implementaion, config files allow you to store key-value pairs. But you can extend it to use
complex data types in the form of xml.
<?xmlversion="1.0"encoding="utf8"?>
<configuration>
</configuration>
To store values in the configuration file, you can create XML elements in the format:
<addkey="MyKey"value="MyValue"/>
See the sample config entries below:
<?xmlversion="1.0"encoding="utf8"?>
<configuration>
<appSettings>
<addkey="DatabasePath"
value="c:\\projects\data\tutorials.mdb"/>
</appSettings>
</configuration>
And to read from this config file, just use the following code in your application:
dimdbPathasstring=
System.Configuration.ConfigurationSettings.AppSettings("DatabaseP
ath");
ConfigurationSettings is the class used to access the contents of the configuration file. Since this class is
part of the namespace System.Configuration, we have to use the fully qualified name
System.Configuration.ConfigurationSettings. As a shortcut, you can use the using directive on top of the
file like below:
usingSystem.Configuration;
If you have the above directive on top of the file, then you can directly use the class
ConfigurationSettings.
stringdbPath=
ConfigurationSettings.AppSettings("DatabasePath");
In C#, you have to use "[ ]" instead of the "( )", as shown below:
stringdbPath=ConfigurationSettings.AppSettings["DatabasePath"]
Note: When you compile your application, VS.NET will automatically create a file called <your application
name>.exe.config in your bin\debug folder. The contents of the app.config will be automatically copied to
this new config file when you compile the application. When you deliver the application to the end user,
you have to deliver the exe and this new config file called <your application name>.exe.config and NOT
the app.config. Users can modify the data in <your application name>.exe.config file and application will
read the data from the config file, when restarted.
By default, you can have only one configuration file for a windows application. If you need to read from
more than one config file, you have to do some additional coding.
This chapter explains the web.config and various entries in the config file.
<?xmlversion="1.0"encoding="utf8"?>
<configuration>
<appSettings>
<addkey="DatabasePath"
value="c:\\projects\data\tutorials.mdb"/>
</appSettings>
</configuration>
To read key/value pairs from <appSettings> section, use the following code:
dimdbPathasstring=
System.Configuration.ConfigurationSettings.AppSettings("DatabasePa
th");
In addition to the <appSettings> section, another interesting entry in the web.config file is,
<sessionState />. A typical sessionState section looks like this:
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="datasource=127.0.0.1;userid=sa;password="
cookieless="false"
timeout="20"/>
The above section allows you to set the session handling details for your web application. The
mode="InProc" says the session will be stored in memory of the web server. The attributes
stateConnectionString and sqlConnectionString are not used if the session is stored in memory. You will
learn more about various session handling methods later.
The last attribute timeout="20" sets the session time out in minutes. If you want to change the default
session timeout, change this value in the web.config file. You can learn more about session time out in
this chapter.
SubApplication_Start(ByValsenderAsObject,ByValeAs
EventArgs)
EndSub
This event is fired when the application is started. The application starts when the first request
comes to the web server after the IIS is started.
The Application start event can occur if the IIS is restarted, server rebooted, web.config file is
changed or if the ASP.NET process recycles.
ASP.NET process recycles for various reasons like insufficient memory, server overload, other un
expected errors etc.
This is the first event fired in ASP.NET after the application starts.
SubSession_Start(ByValsenderAsObject,ByValeAsEventArgs)
EndSub
Session_Start event is fired each time a new session is started.
SubApplication_BeginRequest(ByValsenderAsObject,ByValeAs
EventArgs)
EndSub
Application_BeginRequestis fired each time a new page is requested in the website. This event is
fired after the Session_Start event.
SubApplication_AuthenticateRequest(ByValsenderAsObject,
ByValeAsEventArgs)
EndSub
Application_AuthenticateRequest is fired upon attempting to authenticate the user and after the
Application_BeginRequest event.
SubApplication_Error(ByValsenderAsObject,ByValeAs
EventArgs)
EndSub
If there is any unexpected error or un handled exception in the application, this event is fired. You
can use this event to keep track of un expected errors in your web site and also to report such
errors to the web master.
You will learn more about this event in the next chapter.
SubSession_End(ByValsenderAsObject,ByValeAsEventArgs)
EndSub
This event is fired when the session expires. Note that even if the user close the browser and
leave, this event will not be fired immediately. Only after the session times out, the server will
know that the user is no longer accessing the site and this event will be fired.
Session_End event will be fired if the application restarts.
SubApplication_End(ByValsenderAsObject,ByValeAs
EventArgs)
EndSub
Application_End event is fired when the application ends like shutting down server, re starting
IIS, recycling ASP.NET process etc.
Note that, if somebody power off the server, server will not get a chance to fire the events and
This article explains how to use the Application_Error event in Global.asax file to handle all un
handled exceptions in a web site.
You may have noticed that certain sites will redirect you to a global error page if any un handled error in
the web site. For example, if you type a non existing URL in a site, you will be redirected to an error page
which tells you that "The URL you typed does not exists any more."
This chapter explains how to handle
SubApplication_Error(ByValsenderAsObject,ByValeAs
EventArgs)
EndSub
If there is any unexpected error or un handled exception in the application, this event is fired. You can use
this event to keep track of un expected errors in your web site and also to report such errors to the web
master.
You can see this type of approach in action in AspSpider.com. See the URL of this web page. It is
http://www.aspspider.com/tutorials/Tutorial28.aspx. Change the Tutorial28.aspx to Tutorial9999.aspx
which is a non existing URL. This will throw an error and we have a piece of code in our Application_Error
event handler, which will redirect the user to the Error.aspx page, after sending an email to our web
master about the nature of the error.
The code in Application_Error event handler looks similar to what is shown below:
SubApplication_Error(ByValsenderAsObject,ByValeAs
EventArgs)
'Retrievethelasterrorinthewebsite
DimErrorInfoAsException=
Server.GetLastError().GetBaseException()
'Emailtheerrormessagetothewebmaster
System.Web.Mail.SmtpMail.Send("error@aspspider.com",
"error@aspspider.com",
"Unexpectederror",ErrorInfo.Message)
'Redirecttheusertoafriendlyerrorpage.
Response.Redirect("Error.aspx?Message="&ErrorInfo.Message,
True)
EndSub
The above code will find the last error occurred, send an email to webmaster and then redirect the user to
an Error page.
UserTracker
Let us name the project "User Tracker". This application will display the list of users currently logged in.
Also, we will use this small project to learn some more concepts in the upcoming chapters.
In the first page of this web application, it will prompt you to enter your name in a textbox. Once you enter
the name, it will be stored in the session variable and hide the textbox. It wont allow you to enter the
name again, if the name is already stored in the session variable. Instead, it will display a welcome
message with your name in a Label control.
There will be another page which will display the name of all the users who entered their name in the first
page. How do we do this? Each time a user enter the name, we will store the name into an ArrayList
object and this ArrayList object will be stored in an Application variable. Application variables are visible to
all users of the application. So, you can view the list of all users.
After you press OK, visual studio will create the project files and default pages into the folder
C:\AspSpider\UserTracker. If you have not configured the virtual directory correctly, then visual studio will
create a folder called "UserTracker" under C:\Inetpub\wwwroot.
<asp:Labelid="lblMessage"style="ZINDEX:101;LEFT:95px;
POSITION:absolute;TOP:58px"runat="server"Width="194px"Font
Bold="True"ForeColor="#C00000"></asp:Label>
<asp:Panelid="pnlName"style="ZINDEX:102;LEFT:13px;
POSITION:absolute;TOP:130px"runat="server"Width="398px"
Height="46px">
<asp:Labelid="Label1"runat="server">Enteryour
name:</asp:Label>
<asp:TextBoxid="txtName"runat="server"></asp:TextBox>
<asp:Buttonid="btnProceed"runat="server"
Text="Proceed"></asp:Button>
</asp:Panel>
<asp:HyperLinkid="HyperLink1"style="ZINDEX:103;LEFT:17px;
POSITION:absolute;TOP:211px"runat="server"
NavigateUrl="ShowNames.aspx">ShowNames</asp:HyperLink>
NOTE: Make sure you copy the above code within the <Form></Form> tags in the aspx file.
If you switch to Design mode after copying the above code, the designer will look like this:
We have added all the required controls to the login page. Now, let us see it in action. Compile and run
the web application by pressing Ctrl + F5. You can see that the Login page is launched with all the
controls in it.
You can enter some text in the textbox and press the button. Since we have not added any code to the
event handlers, nothing much will happen.
You will add code to the event handlers in the next chapters and see more functionality of this page.
Let us add some code in the Login page and give it some real action.
PrivateSubbtnProceed_Click(ByValsenderAsSystem.Object,_
ByValeAsSystem.EventArgs)HandlesbtnProceed.Click
EndSub
Let us add the following code to the above event handler.
DimnameAsString=txtName.Text
'storethenameintothesessionvariable.
Session("Name")=name
AddNameToApplicationVariable(name)
'Wehaveselectedaname.Displaythenameanddisablethe
textboxes.
DisplayCurrentUser()
The first statement gets the name from text box and assigns to a variable. The second statement adds it
into the session variable.
The statement AddNameToApplicationVariable(name) is calling a function called
AddNameToApplicationVariable. This function will add the name into an ArrayList object and
add the ArrayList object to an application variable so that this can be accessed by other users also.
The last statement DisplayCurrentUser() displays a welcome message and hides the panel.
Here is the code for the function
AddNameToApplicationVariable()
PrivateSubAddNameToApplicationVariable(ByValnameAsString)
DimnameListAsArrayList
nameList=Application("Names")
IfnameListIsNothingThen
'Thereisnonamesaddedtoapplicationvariableyet.
'LetuscreateanewArrayList
nameList=NewArrayList()
EndIf
'Addthenametothearrylist
nameList.Add(name)
'AddArrayListobjectitselftotheapplicationvariable.
Application("Names")=nameList
EndSub
The first statement declares an object called "nameList" as the type "ArrayList". ArrayList is a class
provided by .NET Framework. This class is similar to "Array" and provides several methods to
add/remove items to the list. You can add/remove any type of objects to an ArrayList.
The second statement is retrieving the value of application variable "Names". This may be null initially. If
this is null, we will create a new ArrayList object and assign to it to the variable "nameList". This is done in
the statement nameList=NewArrayList()
So, now we have a valid ArrayList (either retrieved from Application variable or created new). Now we are
going to add our user name into this array list. This is done in the statement
nameList.Add(name). This statement will add the current name to the array list. This arraylist may
already have other user names, if any other has already logged in.
The last statement Application("Names")=nameList will save this array list to the
Application variable.
Note an important point here - what we save into the application variable is an ArrayList, not just a string.
This ArrayList will have the names of all users currently logged in to the application.
Whenever a user log in to the application, this array list will be retrieved from the application variable, add
the new user's name into the array list and save it back to the application variable.
See the code for the method DisplayCurrentUser():
PrivateSubDisplayCurrentUser()
DimnameAsString=Session("Name")
Ifname=String.EmptyThen
'Thereisnonameinthesessionvariable.Thismeans
'thereisnonameselectedyet.
Return
EndIf
'Thenameisalreadyinthesession.
'Thisuserhasalreadyenteredthename.
'So,letusdisabletothepanelsothatallcontrolswithin
'thepanelwillbeinvisible.
pnlName.Visible=False
'Displaythenameinthemessagelabel.
lblMessage.Text="Welcome"&name
EndSub
The above method will check if the name is already in the session variable. If it is there, it will understand
that the user has already logged in. Then it will display a welcome message and hide the panel
"pnlName". When a panel is hidden, all controls inside the panel also will be hidden. So, after a user is
logged in, the textbox and button will not be visible any more.
Let us do a last step. Switch to design mode and double click on the form. This will create a Form_Load
event handler. Call the method DisplayCurrentUser() from the Form_Load event, to make sure
whenever we load this page, it will check if the user is already logged in or not and display controls
accordingly.
PrivateSubPage_Load(ByValsenderAsSystem.Object,ByValeAs
System.EventArgs)Handles_
MyBase.Load
'Whenweloadthepage,firstcheckiftheusernameisalready
insession.
DisplayCurrentUser()
EndSub
<B>AllUsers</B>
<hr>
<asp:Labelid="lblNames"runat="server"></asp:Label>
Now switch to the design mode and make sure the controls appear properly.
What we have done is, display a static title ("All Users") and put a horizontal line below the title. Below
that, we have added a label control named "lblNames".
Now, in the code behind file, we will retrieve all names from the arraylist in application variable and
display it in the label.
Double click on the form in design mode. It will create a Page_Load event handler. Replace the
Page_Load event handler with the following code:
PrivateSubPage_Load(ByValsenderAsSystem.Object,ByValeAs
System.EventArgs)HandlesMyBase.Load
DimnamesAsArrayList=Application("Names")
IfnamesIsNothingOrElsenames.Count=0Then
lblNames.Text="Nonamesareaddedtoapplicationvariable."
Else
DimnameAsString
Appendeachofthenamesfromthearraylisttothelabel.
ForEachnameInnames
lblNames.Text=lblNames.Text&name&"
"
Next
EndIf
EndSub
Let us analyze the above code. The statement DimnamesAsArrayList=
Application("Names")
declares an arraylist object with the name "names" and assigns the ArrayList from application variable
"Names". Next we are checking if we got a valid arraylist object from application variable. It is possible
that user come to this page directly and no value is set to the application variable yet. In this case, you will
get null value from application variable. If there is no valid object in application variable, we will display an
appropriate error message ( "No names are added to application variable.").
If we get a valid arraylist object from Application variable, then we will loop through the arraylist items and
add to the label controls Text property.
Once we have created the ShowNames.aspx page, let us go back to our Login.aspx page and provide a
link from that page to our new page.
We have already added a HyperLink control to the Login page. Go to the properties window for this
control and set the NavigateUrl property to "ShowNames.aspx". If anyone click on the hyperlink, he
will be redirected to the ShowNames.aspx page.
3. Now you can click on the hyper link and it will redirect to the ShowNames.aspx page, which will display
the name you just entered.
4. Open another window. This will create another session. You can enter another name in the login page
and go to the ShowNames.aspx page. Now this page will display both the names you entered from both
browsers. This is because the application variables retain the values across sessions.
5. You can keep opening any number of new browsers(sessions) and all the login names will be added to
the arraylist in application variable.
6. If you reset IIS, the application variables will be cleared.
7. If you go back to the login page after you enter the name once, it will not allow you to enter the name
again. This is because browser retains the session until you close browser or it times out (or you restart
web server).
Cookies are stored in client browser. So, it can be stored until user clear the cookies or until it is expired
based on the expiry date we specify.
In this chapter, we will display a Label in the Login page which will show the date and time user last
logged in to the web site.
Each time the user login again, a new date/time will be stored into the cookie in the client so that next
time when user come back, we can surprise him saying when was his last login!
Open the Login page in UserTracker project you already created. You already have several controls in the
login page. Just add one more to the Login.aspx page. Note that you must add teh below code within the
<Form></Form> tags.
<asp:Labelid="lblLastVisit"style="ZINDEX:104;LEFT:458px;
POSITION:absolute;TOP:16px"runat="server"
Width="465px"></asp:Label>
This is a label control, which we can use to display the last login date to the user. This control will appear
in the top right corner of the page.
Switch to the design mode and ensure that the control is located in the visible portion of the page.
Now the Login page must look as shown below in the design mode.
'Savecurrentnameandtimetocookie
Response.Cookies("Name").Value=name
Response.Cookies("Name").Expires=DateTime.Now.AddDays(7)
Response.Cookies("SaveTime").Value=DateTime.Now.ToString()
Response.Cookies("SaveTime").Expires=DateTime.Now.AddDays(7)
The above statements will store 2 variables in the Cookie and set the expiry time as 7 days. This means
whatever value is stored in the cookie is valid for 7 days. Since the cookie is stored as physical files in the
client machines, it does not matter even if you restart web server or client computer. The cookie can
retain it's values.
Now let us add another piece of code in the Page_Load event handler.
DimnameCookieAsHttpCookie=Request.Cookies("Name")
DimtimeCookieAsHttpCookie=Request.Cookies("SaveTime")
IfnameCookieIsNothingThen
lblLastVisit.Text="Thisisfirsttimeyouarevisitingthis
stiefromthiscomputer."
Else
lblLastVisit.Text="Youlastvisitedthissiteas'<B><U>"&
nameCookie.Value&"</U></B>'on'<B><U>"&timeCookie.Value&
"</U></B>'."
EndIf
The above code will retrieve the name and last login time from the cookies. If it finds some values, it will
display the values in the label control.
Compile and run the project now. You must be able to view the last login time every time you launch this
application, except for the first time. It can remember the settings for 7 days (the expiry value we set),
even if we reboot the machine.
Database concepts
This tutorial will teach you Database concepts and ADO.NET in a very simple and easy-tounderstand manner with many code snippDatabase is the media to store data. If you have an
application that has to store and retrieve data, your application must be using a database.
A 'File' is the simplest form of saving the data in the disk, but is not the most 'efficient way' of managing
application data. A database is basically a collection of one or more files, but in a custom format, and data
is organised in a specific format such a way that it can be retrieved and stored very efficiently.
Some examples for databases are :
MS Access
SQL Server
Oracle
MS Access is a very light weight database provided by Microsoft for applications with less number of
users and relatively small quantity of data. MS Access saves data into database files with the
extension .mdb. Usually, MS Access comes along with MS Office package. If you already have the .mdb
database file, you can freely use it with your application and you do not need MS Access software. The
MS Access software is required only if you want to directly open the database and manipulate the data or
change the database schema.
SQL Server (Microsoft product) and Oracle (Oracle Corp.) are more complex, advanced, relational
databases and they are much more expensive. It can support large number of users and very high
quantity of data. If you are developing a software, which might be accessed simulatenously by 100s of
users or if you expect your data may grow 100s of MBs, you might consider one of these. (We are
learning Microsoft .NET.. so you might want to consider the SQL Server than Oracle, for which Microsoft
provides special data access components!!) ets and samples.
Introduction to ADO.NET
This chapter introduces you to Active Data Objects in .NET (ADO.NET)
ADO.NET is the data access model that comes with the .NET Framework. ADO.NET provides the classes
required to communicate with any database source (including Oracle, Sybase, Microsoft Access, Xml,
and even text files).
There are other providers available, but we are not including them here as this tutorial is meant for
beginners! When you want them, search for ADO.NET providers in Google or MSDN
Microsoft made the SQL Server. So they gave a separate provider, specifically made for SQL Server. We
can use the OleDb provider for all other database sources including MS Access, Oracle, Sybase etc.
There is a separate provider available for Oracle.
A DATA PROVIDER is a set of classes that can be used to access, retrieve and manipulate data from the
databases.
Both OleDb and SqlClient has it's own set of classes, but they have the same concepts. We would like to
classify the classes into two broad categories (this is not a microsoft classification, anyway!)
Classes for communicating with database
Classes for holding/manipulating data
The job of first category of classes is to communicate with database and send or retrieve data
from the database. The second category of the classes will be used hol
Object
Description
SqlClient
Objects
OleDb Objects
Connection
SqlConnection
OleDbConnection
Command
SqlCommand
OleDbCommand
DataReader
SqlDataReader
OleDbDataReader
SqlDataAdapter
OleDbDataAdapte
r
Each provider may have classes equivalent to above objects. The name of the classes vary slightly to
represent the provider type appropriately.
Depending on the type of database you work on, you will have to choose either OleDb or SqlClient (or,
some other provider) objects. Since all our samples use MS Access database, we will be using OleDb
objects in all the samples. If you like to use SqlServer, you just need to replace the OleDb objects with the
equivalent SqlClient objects.
DataSet
DataTable
DataRow
The above operations are sometimes called "CRUD" (Create, Read, Update, Delete)
Most of the simple applications you develop will have the screens to perform the above operations.
For example, assume you are developing an application to manage the list of employees in a company.
The first thing you may do is, create a database table called "Employees" in your database. Next thing is
to develop couple of screens.
1. Create Employee
This screen will have the fields to accept various details of an Employee. User has to enter all the details
and press a button to save all details to database.
This page will be using an SQL Query which will look something like this:
insertintoEMPLOYEES(id,name,age,salary,designation)values
(1,'john',30,25000,'VicePresident')
2. A screen (page) which displays the list of all employees.
This page will be using an SQL Query which will look something like this:
select*fromEMPLOYEES
The above query will return all the records from the database table. You will use some code in the page to
display the records in a user friendsly manner. ASP.NET provides a control called "DataGrid" which can
be used to display large number of records properly formatted.
updateEMPLOYEESsetname='john',age=30,salary=25000,
designation='VicePresident'whereid=1
4. The Delete screen will allow you delete any existing employee.
The sql query will be something like this:
deleteEMPLOYEESwhereid=1
Even though most of the applications allow all the above 4 operations for most of the tables, it is not
necessary to have 4 pages each. Some people design the screens such a way that all 4 operations can
be performed in one page. My personal preferance is 2 pages - 1 page to display the data and delete
selected records and 1 page to create and update the record. Since the create and update page need to
have the same set of fields, I prefer to use the same page for both operations. I will pass a query string to
identify whether I have to insert a record or update.
All of the tables in your database does not require screens to perform CRUD operations. Only specific
tables will need such screens. Generally, the tables which gets data from users of the application will
need the screens to perform CRUD operations. Here is the general rule: "If you need to capture data from
user to a table, you must provide the screens to perform the basic operations - create, read, update and
delete".
#includeSystem.Data.OleDb
The following code snippet shows an example of category 2 (returns no data)
stringconnectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\\Samples\\Employee.mdb";
OleDbConnectionmyConnection=new
OleDbConnection(connectionString);
myConnection.Open();
stringquery="insertintoEMPLOYEE_TABLE(EmployeeID,Name,
Address)VALUES(101,John,3960CliffValleyWay)";
OleDbCommandmyCommand=newOleDbCommand();
myCommand.CommandText=query;
myCommand.Connection=myConnection;
myCommand.ExecuteNonQuery();
myConnection.Close();
See the above sample code. It executes an insert statement to add a record to a table called
EMPLOYEE_TABLE in an MS Access database called Employee.mdb. Let us analyze the classes used
in the above sample:
1.OleDbConnection
2.OleDbCommand
There are only 2 classes used to execute an sql statement that do not return any result.
OleDbConnection class is used to open a connection to the database. This class is required to
perform category 1 and category 2 operations. You must specify a connection string to represent the
database. The connection string has various formats and it depends on the database type (MS Access,
SQL Server, Oracle etc)
Let us analyze the code. First we have declared a connection string. The connection string points to an
MS Access database. Before you execute this code, make sure you have the database in the path
specified. Or, change the path accordingly.
In the next step, we are creating a OleDbConnection object and passing the connection string to this
object. The line myConnection.Open(); will open a connection to the MS Access database specified in the
connection string. If the database doesnt exists or if it is not able to open a connection for some other
reason, the .Open call will fail.
Next step is, creating a OleDbCommand object. This command object is used to execute sql statements
and uses the connection opened by the OleDbConnection object.
Note that before executing a command, we have to establish a valid connection to the database.
And finally, after we have executed with the command, we will close the connection.
The above sample code executes a sql statement and returns no data from database. We are calling the
method ExecuteNonQuery() on the command object. If we have a select ... statement which returns data
from database, we cannot use the ExecuteNonQuery() method.
This article demonstrates the usage of OleDbDataAdapter Object and DataSet to retrieve data
from databbase.
In the previous chater, you learned how to use OleDbConnection and OldDbCommand classes to
execute an sql statement that returns no data.
In this chapter, you will learn how to use the ADO.NET classes to execute sql statements and retrieve
data from database.
See the following sample code:
stringconnectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\\Samples\\Employee.mdb";
OleDbConnectionmyConnection=new
OleDbConnection(connectionString);
stringquery="select*fromEMPLOYEE_TABLE";
OleDbDataAdaptermyAdapter=newOleDbDataAdapter(query,
myConnection);
DataSetemployeeData=newDataSet();
myAdapter.Fill(employeeData);
OleDbDataAdapter and pass a dataset object to this method. This step will populate the
dataset (called employeeData ) with the data retrieved for the sql statement select * from EMPLOYEE.
As you already know, a DataSet can contain a collection of tables. But in our case, our sql statement
will retrieve data from only one table. So, our DataSet will have only one table.
In our sample code, the dataset contains one table and the table contains one or more records. We
can iterate through the table in the dataset and retrieve all the records. See the following code
demonstrating this:
stringconnectionString=
"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\\Samples\\Employee.mdb";
OleDbConnectionmyConnection=new
OleDbConnection(connectionString);
stringquery="select*fromEMPLOYEE_TABLE";
OleDbDataAdaptermyAdapter=newOleDbDataAdapter(query,
myConnection);
DataSetemployeeData=newDataSet();
myAdapter.Fill(employeeData);
//RepeatforeachtableintheDataSetcollection.
foreach(DataTabletableinemployeeData.Tables)
{
//Repeatforeachrowinthetable.
foreach(DataRowrowintable.Rows)
{
Response.Write("EmployeeNumber:"+
row["EmployeeNumber"].ToString());
Response.Write("Name:"+row["Name"].ToString());
Response.Write("Address:"+row["Address"].ToString());
}
}
The above code retrieves all the records from the employee table and displays the value of the
following fields:
EmployeeNumber
Name
Address