+ All Categories

ASP.NET

Date post: 24-Oct-2014
Category:
Upload: hampehhh2002
View: 94 times
Download: 0 times
Share this document with a friend
Popular Tags:
88
About this Tutorials Welcome to ASP.NET Tutorial (Using VB.Net and C#). By completing the lessons and exercises in this book, you will acquire the skill and knowledge necessary to develop large enterprise web-based application in VB.Net or C#. This tutorial is specially designed for the beginners and students who are in the starting point of their IT carrier. Plain and simple English is used throughout the tutorials so that every one can understand the concepts we are discussing. 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 you need to know before you start ? This tutorial required that students meet the following prerequisites: Have a basic understanding of the Object-oriented programming concepts including classes, properties, methods and events. What do we offer ? The ASP.NET tutorials in this site includes several chapters. We are still adding more and more chapters everyday. This 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. What is a web server? A Web server is a software program which serves web pages to web users (browsers). A web server delivers requested web pages to users who enter the URL in a web browser. Every computer on the Internet that contains a web site must have a web server program. The computer in which a web server program runs is also usually called a "web server". So, the term "web server" is used to represent both the server program and the computer in which the server program runs. Characteristics of web servers A web server computer is just like any other computer. The basic characteristics of web servers are:
Transcript
Page 1: ASP.NET

About this Tutorials Welcome to ASP.NET Tutorial (Using VB.Net and C#). By completing the lessons and exercises in this book, you will acquire the skill and knowledge necessary to develop large enterprise web-based application in VB.Net or C#. This tutorial is specially designed for the beginners and students who are in the starting point of their IT carrier. Plain and simple English is used throughout the tutorials so that every one can understand the concepts we are discussing. 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 you need to know before you start ? This tutorial required that students meet the following prerequisites: Have a basic understanding of the Object-oriented programming concepts including classes, properties, methods and events. What do we offer ? The ASP.NET tutorials in this site includes several chapters. We are still adding more and more chapters everyday. This 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. What is a web server? A Web server is a software program which serves web pages to web users (browsers). A web server delivers requested web pages to users who enter the URL in a web browser. Every computer on the Internet that contains a web site must have a web server program. The computer in which a web server program runs is also usually called a "web server". So, the term "web server" is used to represent both the server program and the computer in which the server program runs. Characteristics of web servers A web server computer is just like any other computer. The basic characteristics of web servers are:

Page 2: ASP.NET

It is always connected to the internet so that clients can access the web pages hosted by the web server. It has an application called 'web server' running always. In short, a 'web server' is a computer which is connected to the internet/intranet and has a software called 'web server'. The web server program will be always running in the computer. When any user try to access a website hosted by the web server, it is actually the web server program which delivers the web page which client asks for. All web sites in the internet are hosted in some web servers sitting in different parts of the world. Web Server is a hardware or a software ? From the above definition, you must have landed up in confusion “Web server is a hardware or a software” Mostly, Web server refers to the software program, which serves the clients request. But as we mentioned earlier in this chapter, the computer in which the web server program is also called 'web server".

Web Server – Behind the Scene Now that you are reading this page, have you ever had a thought how the page is made available to the browser? Your answer would be, “I typed in the URL http://www.aspspider.com and clicked on some link, I dropped into this page.” But what happed behind the scenes to bring you to this page and make you read this line of text. So now, lets see what is actually happening behind the scene. The first you did is, you typed the URL http://www.aspspider.com in the address bar of your browser and pressed your return key. We could break this URL into two parts, The protocol we are going to use to connect to the server (http) The server name (www.aspspider.com) 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.

Page 3: ASP.NET

Where is my web server ? When you try to access a web site, you don't really need to know where the web server is located. The web server may be located in another city or country, but all you need to do is, type the URL of the web site you want to access in a web browser. The web browser will send this information to the internet and find the web server. Once the web server is located, it will request the specific web page from the webserver program running in the server. Web server program will process your request and send the resulting web page to your browser. It is the responsibility of your browser to format and display the webpage to you. How many web servers are needed for a web site? Typically, there is only one web server required for a web site. But large web sites like Yahoo, Google, MSN etc will have millions of visitors every minute. One computer cannot process such huge numbers of requests. So, they will have hundreds of servers deployed in different parts of the world so that can provide a faster response. How many websites can be hosted in one server? A web server can hosted hundreds of web sites. Most of the small web sites in the internet are hosted on shared web servers. There are several web hosting companies who offer shared web hosting. If you buy a shared web hosting from a web hosting company, they will host your web site in their web server along with several other web sites for a Fee. Examples of web server applications 1. IIS 2. Apache So, ready to develop a web site? Any one who want to develop a web application must have the following systems: 1. A web server. 2. An editor to develop the web pages. 3. A browser to view the web page you develop. 4. A database program like MS Access, SQL Server etc, if your web site need to save data into a database. In the real world situation, a web server will be hosted on a secure server, located in a safe place and will 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

Page 4: ASP.NET

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. Editor to develop web pages Ideally, you do not need any special editor to develop a web application. If you are an expert, you can simply use ntoepad to type HTML and the code for the web pages. However, who want to hand-wash the vessels when there is a dish washer ?! You don't need to make your hands dirty! Microsoft gives a tool called 'Visual Studio .NET' to edit web pages and write code for ASP.NET. Visual Studio .NET (VS.NET) Visual Studio .NET allows to easily create web pages. Some of the benefits in using Visual Studio .NEt are: 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. Internet Information Services (IIS) If you have Windows 2000 or Windows XP Professional, you may have IIS already installed in your computer. IIS is part of the Windows operating system, but it is not selected by default. So, if you choose default options when you installed the operating system, you may not have the IIS installed To find if you already have IIS installed, go to the "Control Panel" and select "Administrative Tools". Check if there is a shortcut for "Internet Information Services" exists as part of the "Administrative Tools". If it does not exist, you will need to install IIS.

Page 5: ASP.NET

To install IIS, go to the "Control Panel" and select "Add Remove Programs". Select the option "Add/Remove Windows Components". Make sure the option "Internet Information Services (IIS)" is selected. If it is already selected, that means you already have IIS ! If the checkbox for IIS is not checked, select it and press the "Next" button to proceed to install.

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.

Page 6: ASP.NET

Internet Information Services (IIS) helps you manage the web applications and web sites in your computer. How to open IIS There are several ways you can open the Internet Information Services tool. Method 1: Open the 'Control Panel', select 'Administrative Tools' and then double click the shortcut 'Internet Information Services' 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')

Page 7: ASP.NET

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

Page 8: ASP.NET

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". Stop and start IIS You may never need to stop and start your IIS. When your computer is started, IIS is automtically started. Actually, IIS is a 'windows service'. What you see as 'Internet Information Services' is an admin tool provided by Microsoft to manage the real IIS which works in the background. IIS runs as a windows service in the background and what you see is only a tool to manage the IIS service. If you like to stop or start IIS, select the "Default Web Site" in IIS tool and select "stop" or "start" from the right click menu. If you stop IIS, you cannot access your web sites anymore. Even, if you try to open the ASP.NET project in Visual Studio, it will complain that web site is currently not available. What is a virtual directory ? A virtual directory represents a web application and it points to a physical folder in your computer. A web application is accessed using a virtual directory name instead of a physical folder name. For example, if you have a web application called "Shopcart" in your machine, you will have a virtual directory for this web application. You will access your web application using the URL httP://localhost/Shopcart. If your virtaul directory name is "Test", then your web application url will be http://localhost/Test". Assume you have a web application called "Shopcart", created under the physical folder "C:\MyProjects\Shopcart". You can go to IIS and see this virtual directory listed. Right click on this virtual directory name in IIS and see the properties. You can see that this virtual directory is pointing to the physical location "C:\MyProjects\Shopcart". If you have a file called "File1.aspx" under the folder "C:\MyProjects\Shopcart\", then you can access this file using Internet Explorer with the URL "http://localhost/Shopcart/File1.aspx" How to create a virtual directory ? When you create a new web project using, a new virtual directory will be created automatically for you. This virtual directory will point to a new folder created under C:\Inetpub\wwwroot. If you like to better organize your projects and files in your favourite folder, you must manually create a new folder for each project in your preferred location and convert it into a virtual folder manually There are couple of ways you can do this.

Page 9: ASP.NET

Method 1: Open the IIS. Right click on the node "Default Web Site" and select "new Virtual Directory". When it prompt you to enter the "alias", enter the virtual directory name you want(Eg: Shopcart). In the prompt for "directory", select the folder which you want to make a virtual directory (Eg: C:\MyProjects\Shopcart). Select other default values and press "Finish". Now you should be able to see your new virtual directory in IIS. Method 2: In the explorer, go to the folder(Eg: C:\MyProjects\Shopcart) which you want to make a "virtual directory". Right click on the folder name and select "Properties". Select the tab "Web sharing" and select teh option "Share this folder". It will prompt you with a default Alias name same as the folder name (Eg: Shopcart). Simply select the default values and press "OK". Web applications work quite different from regular windows applications. There are several computers involved when you view a web page. Life Cycle of a Web Request Viewing a web page is a simple process for a visitor. Just type the URL in a web browser like Internet Explorer or click on a hyper link in any existing web page. The web browser will display the page instantly to you. But do you know that there are several computers involved in this process? Even though it is a very complex process, we can summarize the process as shown below: 1. You type the web page address (URL) in a browser. For example, consider the current page http://www.aspspider.com/tutorials.aspx. This URL has 3 parts: The protocol - http: The server name - www.aspspider.com The file name - tutorials.aspx 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.

Page 10: ASP.NET

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. If I say 'web programming is more challenging than windows programming', I am sure lots of windows programmers are going to disagree with me. Ofcourse this is an arguable topic. Both windows 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. Learn a new technology You may be a great C# or VB.NET developer. But if you want to do web development, you need to learn a new technology called ASP.NET. ASP.NET is the latest Microsoft technology for web development. To learn more about the ASP.NET technology, read the chapter titled < ahref='Tutorials.aspx?TutorialId=56'>What is ASP.NET ? Note: ASP.NET is just one of several technologies available for web development. ASP, PHP etc are other examples for web development. Do not know the users If you develop a windows application, you know who is going to use it. You can always give special instructions to the user on how to use it, how to work around if there is any problems in the program etc. But in case of a web application in internet, you will not know who is going to use. Any user can visit your web site and access the application. You do not get any chance to give any special instructions to the user. The application must be self explaining and easy to use. You must have very good error handling so that even if the user enters wrong values, application must respond accordingly and guide user to correct the values. Familiarity with application Most of the windows applications will be accessed by the same users again and again. Over a period of time, the users will become familiar with the menu, screens and various features of the application. But in case of an internet web site, new users may be visiting the site every day. The web application must be self explaining and should be easy to navigate. Most of the users will take a quick look at the site and try to find what they want. If they cannot locate what they want in few seconds, they will simply leave your site!

Page 11: ASP.NET

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. Bad users! Bad data!! You cannot expect all users will use your web application the way you want to. Users may try all bad data or try to find loop holes in your application. Your application must be more secure and should have strict validation of user inputs. 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. Slow and fast Internet connectivity Not all users have high speed internet. Your web application should work well with low speed internet too. If you use lot of graphics, then it may be very slow to load in low speed internet connections. But if you completely avoid graphics, you will not be able to make the application attractive to many users. You must choose a balanced approach, considering the majority of your users. Many new programmers are confused about how ASP.NET is different from C# or VB.NET. Many new programmers mis understand that ASP.NET is just another programming launguage. 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.

Page 12: ASP.NET

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. 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. Programming language - C#, VB.NET or your favourite language You can develop a simple, static web site using plain HTML. You don't need to know C# or VB.NET to develop a web site. But, to display dynamic content in the ASP.NET website, you must use a programming language like C# or VB.NET. For exampe, if you want to display data from database, you will need to write C# or VB.NET code in the web page to access the database and retrieve database. So, you must learn atleast one programming language like C# or VB.NET to become a good ASP.NET developer. Client side scripting language In addition to HTML and C#/VB.NET, you may need to learn one more programming language like Javascript or Vb script for client side scripting. Javascript is the most popular and widely used client side scripting language. You can read more about client side scripting in another chapter. Internet Information Services - IIS IIS is the engine that drives the ASP.NET web sites. But just like a car driver need to know much about the engine of the car, you need not be an IIS expert to develop web sites. Just like your car starts when you turn the key, the IIS is started when you start windows. There are separate chapters for IIS in this tutorials. Visual Studio .NET - VS.NET Visual Studio .NET is the editor from Microsoft which allows you to write code easily. Ideally, you 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

Page 13: ASP.NET

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!! Visual Studio .NET is tool that help you automate lot of work related to creating a web site or web application. However, in this chapter we are going to see how to create a small web site manually, without using VS.NET. This help you understand some of the background work done VS.NET when you create a new project. Let us create a new web site called "ShoppingCart". Step 1: Create folderStep 1: Create folderStep 1: Create folderStep 1: Create folder The first step is, creating a folder for this web site. So, go to explorer and create the following folder: C:\ShoppingCart Step 2: Create virtual directoryStep 2: Create virtual directoryStep 2: Create virtual directoryStep 2: Create virtual directory Create a new virtual directory called "ShoppingCart" pointing to the folder we just created. Refer to this chapter for more information about creating virtual directories and working with IIS. Step 3: Create a web pageStep 3: Create a web pageStep 3: Create a web pageStep 3: Create a web page Let us create a simple page to get started. Open notepad and copy the following content: <html> <head> <title>This is my first web page</title> </head> <body> <br><br><br><br> <center> <font size=5 color=red>Welcome to SpiderShop !</font> <BR><BR> <font size=3 color=darkgreen>Buy softwares and tools online at very low rates....</font> </center> </body> </html>

Page 14: ASP.NET

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. The chapters explains how you can convert an HTML file into as ASP.NET page and how to develop ASP.NET pages. In this chapter, you learned how to create a simple website with an html page. Our aim is to learn ASP.NET. So, let us see how to develop ASP.NET pages. An html file can have the extensions .htm.htm.htm.htm or .html.html.html.html. An ASP.NET page has the extension .aspx.aspx.aspx.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! How to test the ASP.NET page ?

Page 15: ASP.NET

Just like the way you opened your html page in Internet Explorer, open the ASP.NET page. Open Internet Explorer and type the following URL: http://localhost/index.aspx You can see the same output as the html file. How did it work? If you want to change your small grocery store to a big super market, what will you do? You can simply put a big board in front of your store saying "Super Market" and claim that you have a super market. This is exactly what we did with our html page. We simply renamed it. But changing the name is not enough to convert a grocery store to a super market. There is a lot more to go! In the coming chapters, you will learn more about how to convert a grocery store into a super market (well, we mean how to switch from simple html to complex asp.net pages The chapters explains how you can convert an HTML file into as ASP.NET page and how to develop ASP.NET pages. In this chapter, you learned how to create a simple website with an html page. Our aim is to learn ASP.NET. So, let us see how to develop ASP.NET pages. An html file can have the extensions .htm.htm.htm.htm or .html.html.html.html. An ASP.NET page has the extension .aspx.aspx.aspx.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! How to test the ASP.NET page ? Just like the way you opened your html page in Internet Explorer, open the ASP.NET page. Open Internet Explorer and type the following URL: http://localhost/index.aspx

Page 16: ASP.NET

You can see the same output as the html file. How did it work? If you want to change your small grocery store to a big super market, what will you do? You can simply put a big board in front of your store saying "Super Market" and claim that you have a super market. This is exactly what we did with our html page. We simply renamed it. But changing the name is not enough to convert a grocery store to a super market. There is a lot more to go! In the coming chapters, you will learn more about how to convert a grocery store into a super market (well, we mean how to switch from simple html to complex asp.net pages) This chapter explains how browsers display dynamic pages. There are several several technologies exist to develop dynamic web sites and pages. Some of them are ASP, ASP.NET, PHP etc. Whatever technology you use to develop the dynamic web pages, a standard browser should be able to display the page to the visitors. How browsers understand ASP.NET or PHP pages? If visit any web site, no matter what technology is used to develop the site, your browser will be able to display the page for you. The only thing a browser can understand is "HTML". It does not know ASP.NET or PHP. So, even if your web site is developed using ASP.NET, still your browser can understand only HTML. This is how it works: You type a URL in your browser. (Eg: http://www.aspspider.com/tutorials/Tutorials.aspx?TutorialId=61) Your browser will compose a request for this page and send to the web server in internet. The web server analyzes the request and it understands that the request is for an ASP.NET page called "Tutorials.aspx". So, the web server hand over the request to the aspnet service running as part of the web server. (If the page is a .php file, then there must be a php service running on the webserver). The aspnet service loads the page "Tutorials.aspx". Inside this page, we have written code to read the TutorialId passed as a parameter (parameters are called "Query String"). Our code gets this tutorial id and then retrieves the corresponding content from the database. Then our code embeds this content into the page and returns the dynamically modified page content to the web server. Web server returns the dynamically generated page to the browser. This dynamically generated page has only HTML in it, even though this html came from

Page 17: ASP.NET

database. When the browser receives the page, it has only HTML. So, as far as a browser is concerned, it does not care what type of web site it is. It can be any technology like ASP.NET or PHP. It is the responsibility of the web server to generate dynamic content from database or wherever and give only HTML page content to the browser. Other than HTML, what else browsers understand? We said that browsers understand only HTML. That is not fully true. Modern browsers understand something more than HTML, like Javascript, Flash etc. We will talk about these in the coming chapters. This article how ASP.NET pages are sent as HTMl to browsers. In an earlier chapter you learned that browsers can understand only HTML (and some client side scripts like javascript). So, what does that mean? Does it mean you cannot develop ASP.NET pages to view in a browser? This is the concept: You can use web development technologies like ASP.NET, PHP etc to develop web You can use web development technologies like ASP.NET, PHP etc to develop web You can use web development technologies like ASP.NET, PHP etc to develop web You can use web development technologies like ASP.NET, PHP etc to develop web sites. But what is hasites. But what is hasites. But what is hasites. But what is happening behind the scenes is, the above technologies are used to ppening behind the scenes is, the above technologies are used to ppening behind the scenes is, the above technologies are used to ppening behind the scenes is, the above technologies are used to dynamically generate html. What is sent from web server to the browser is just plain dynamically generate html. What is sent from web server to the browser is just plain dynamically generate html. What is sent from web server to the browser is just plain dynamically generate html. What is sent from web server to the browser is just plain html. That why browsers are able to display web pages developed using ASP.NET.html. That why browsers are able to display web pages developed using ASP.NET.html. That why browsers are able to display web pages developed using ASP.NET.html. That why browsers are able to display web pages developed using ASP.NET. Whatever technology you use to develop web pages, what is sent from server to browser is just plain html. Depdning on various conditions, ASP.NET generate different html. I will prove this with an example. If you have NOT logged In to this site, you can see a link called "Login" in the top left corner. If you are logged in, you will see 'Welcome TONY'. (You will see your name instead of TONY, but I am using my name for this example) We use ASP.NET to determine wether user has logged in or not. If logged in, then our ASP.NET code will generate the following html: <a href='ViewProfile.aspx?UserId=tony'>Welcome TONY !</a> If the user is NOT logged in, then our ASP.NET code will generate the following HTML: <a href='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.

Page 18: ASP.NET

Browsers always see plain html (the same html you see by Right click -< View Source) . They don't 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 Static Web Pages A static web page is a page which has the same content always. In case of static web pages, content is written in the page itself as plain html. Until the author of the web page updates the content, the content remains the same in the static pages. Static web pages are meant for providing information which does not change often. For example, visit http://www.google.com/intl/en/about.html. This page is a static page. The content is always the same (until they update the content by uploading a new html file to the web server). HTML files are used to create static web pages. Dynamic Web Pages Dynamic web pages get content from database. Content is NOT hard-coded in the page itself. Dynamic pages are created using "serverside code" when the page is loaded every time. An example for a dynamic page is this tutorial page itself. See the file name in the URL. The file name is "Tutorial8.aspx". We have used only one file to display any tutorial chapter. The chapter number is there as part of the URL (the chapter number is 8 for this chapter). When you type the URL in the browser, this page is dynamically created from database, based on the chapter id in the URL. The content of each chapter is stored in our database, not in the file itself. When you access the page, our server side code will check what is the TutorialId in the URL. Based on the TutorialId, it will retrieve appropriate chapter content from the database and dynamically create the web page. (You can try to change the TutorialId in the URL to some very large number and try. The page will give an error because our code will fail to get the corresponding chapter content from the database). This entire site has only very few files (like index.aspx, Tutorial.aspx etc)

Page 19: ASP.NET

Dynamic web pages are created using technologies like ASP, ASP.NET, PHP etc. 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. This chapter gives an introduction to client side and server side programming. Ever wondered the what is the difference between client side code and server side code? If your anser is YES, this chapter is for you. Server side code In a previous chapter, you learned that dynamica pages are created using code in asp.net web pages. When you request a page, the web server executes the code in the web page and generates an HTML content for that page. It is this HTML content that is sent back to the browser so that it can be displayed to the user. The code that is executed by the web server to generate the dynamic page is called "server side code". It is called "server side code" because it is executed by the web server. When you develop ASP.NET pages, you will use C# or VB.NET (or any other .NET compatible code) code to write the server side code. Server side code is used to retrieve and generate content for the dynamic pages. You may be using the code to retrieve the content from database or something like that. When a dynamic page is requested, the server side code is executed on the server and a page is generated. Once the generated page comes to the browser, there is connection with the server. You cannot do anything from the browser to communicate with the server, othen than requesting another page or same page again. So, if you want to access the database or something like that once the page is displayed, it is not possible. Client side code Client side code is used to do some kind of basic operations in the browser when the page is displayed to the user. As you read above, it is not possible to access the server once the page is displayed. Morover, the browser does not knwo anything about ASP.NET or .NET. The browser undersands only HTML and client side scripting languages. Client side coding is used to do basic operations on the browser. It cannot be used to access the server or database on the server etc. Client side coding is done using scripting languages like Javascript, VbScript, JScript etc. These scripting languages are easy to learn (they are different from vb.net and C#). The scripting languages provide only very minimal functionality. 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

Page 20: ASP.NET

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. You will learn to create a dynamic page in this chapter. In an earlier chapter, you learned how to create a small Shopping Cart web site with a simple HTML page in it. In another chapter you larned how to convert the simple html page to an ASP.NET page. That was fun! You simply renamed the html page to an aspx page. In this chapter you are going to do some real work by writing server side code, which make it a real dynamic page. To write server side code, you must choose a .NET language. It can be any .NET language like C#, VB.NET, C++.NET or J#. For this chapter, let us choose VB.NET. Go back to your index.aspx page in your folder "C:\ShoppingCart\". Open the file using notepad. You can see the following content in the index.aspx file. <html> <head> <title>This is my first web page</title> </head> <body> <br><br><br><br> <center> <font size=5 color=red>Welcome to SpiderShop !</font> <BR><BR> <font size=3 color=darkgreen>Buy softwares and tools online at very low rates....</font>

Page 21: ASP.NET

</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. How to write server side code in a page ? Our index.aspx page has only plain HTML now. We are going to embed some server side code inside it so that the server will process it and generate some output dynamically. Anything you write inside a special tag as shown below will be trated as server side code: <% %> 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>This is my first web page</title> </head> <body> <br><br><br><br> <center> <font size=5 color=red>Welcome to SpiderShop !</font> <BR><BR> <font size=3 color=darkgreen>Buy softwares and tools online at very low rates....</font> <br><br> Now the server time is : <% Response.Write (DateTime.Now.ToString) %>

Page 22: ASP.NET

</center> </body> </html> Now access your page using the URL http://localhost/ShoppingCart/Index.aspx. You will see the following output in browser: Buy softwares and tools online at very low rates.... Now the server time is : 4/28/2005 6:33:45 PM You can see the actual server time displayed in your browser. (Since you are using your own machine as the server and client, you will see your computer time. ) Let us see how it worked. You have writtena piece of code as shown below: Now the server time is : <% 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) The code Response.Write is used to generate output. DateTime.Now.ToString will return the current date and time. So, the resule of the following code is the current date and time and Response.Write() will return that result to the asp.net page which embeds the code. In the page, we have Now the server time is : <% Response.Write (DateTime.Now.ToString) %> In the above lines, Now the server time is : is a plain HTML. The next part gets executes in the server and returns the current time. So, the final output is:

Page 23: ASP.NET

Now the server time is : 4/28/2005 6:33:45 PM 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. This article talks about the default programming language and other supported programming languages supported by ASP.NET In the previous chapter, you learned how to display server time using ASP.NET. The code you wrote was, Now the server time is : <% 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: Now the server time is : <% dim currentTime as string = 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 http://localhost/ShoppingCart/index.aspx. You will see the same old result. You may have noticed that we are using VB.NET syntax to write server side code. 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: Now the server time is : <% string currentTime = DateTime.Now.ToString(); Response.Write ( currentTime );

Page 24: ASP.NET

%> 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). How to use C# in ASP.NET ? VB.NET is the default language for ASP.NET. This does not mean that VB.NET is a better choice than C#. Both VB.NET and C# are equally good for ASP.NET. If you like to use a language other than the default VB.NET language, you must explicitely specify what language you are using so that ASP.NET can use appropriate compiler to compile your server side code. Now we have changed our code to C# syntax. So, we must specify that we want to use C# compiler. What you need to do is, go to the top of the index.aspx page in notepad and type the following line: <%@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. Supported languages for ASP.NET You can use any .NET programming language to write server side code in ASP.NET. The following are the .NET languages provided by Microsoft: 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# This article explains what is ASP.NET and how different it is from ASP.NET ASP stands for AAAActive SSSServer PPPPages. ASP.NET is the next generation of ASP. After the introduction of ASP.NET, old ASP is called 'Classic ASP'. Classic ASP uses vb script for server side coding. Vb Script is not supported any more

Page 25: ASP.NET

in ASP.NET. Instead, ASP.NET supports more languages including C#, VB.NET, J# etc. VB.NET is very similar to vb script, so it should be easy for old Visual Basic or ASP programmers to switch to VB.NET and ASP.NET VB Script is a simple scripting language, where as VB.NET or C# are modern, very powerfull, object oriented programming languages. Just for that reason, you will be able to write much more robust and reliable programs in ASP.NET compared to ASP. In classic ASP, there was no server controls. You have to write all html tags manually. ASP.NET offers a very rich set of controls called Server Controls and Html Controls. It is very easy to drag and drop any controls to a web form. The VS.NET will automatically write the required HTML tags automatically for you. ASP is interpreted, ASP.NET is compiled Since ASP uses vb script, there is no compilation. All ASP pages are interpreted when th page is executed. ASP.NET uses modern .NET languages like C#, VB.NET etc. They can be compiled to efficient Microsoft Intermediate Language (MSIL). When you compile an ASP.NET application, the server side code is compiled to assemblies. These assemblies are loaded at run time which makes the ASP.NET pages perform better than classic ASP. ADO and ADO.NET Classic ASP uses a technology called ADO to connect and work with databases. ASP.NET uses the ADO.NET technology (which is the next generation of ADO). Event driven programming If you have written Visual Basic programs before, you would love the event driven programming approach. It is so easy to drag and drop a button control and double click on the button to write the event handler for the button click event. When you click on the button at turn time, it will execute whatever code you have written in the event handler. This type of event driven programming was not available with classic ASP. You cannot drag and drop a button and write a 'on click' event handler with ASP. With ASP.NET, this is changed. It works pretty much like your Visual Basic program. You can write event handlers for several events like button click event, text changed event etc. However, there is big difference between the way event handling works in regular Visual basic and ASP.NET. In ASP.NET, a page is loaded in the client browser. And the server may be in another location (may be in another country). When you click on the button in an ASP.NET page, the 'click event' handler has to be executed on the server, not on the client. How does the server know when you click on a button your browser? This is a tricky thing in ASP.NET. When you write an event handler for a button lick or something like that in ASP.NET, lot of things happens behind the screens. ASP.NET will produce lot of client side javascript code to handle this and embed this javascript in the html page it sends to the browser. When you click on the button in the browser, the client side javascript will get executed. This javascript will generate

Page 26: ASP.NET

some information required for the server and and submit the page request to the server. There is enough information embedded in this request so that the server will understand that user has clicked a specific button in the browser and it has to execute some 'specific event handler' code in the server side. So, when the user clicks on a button, the page is submitted automatically to the server with some special information. In the server side, it will process the event handler for the button click event and send back the output page to the browser again. Similary, you can write other event handlers like text changed event for Textboxes etc. As a user of the web page, you will not even know what happened in the background. All you can see is, when you clicked the button, it executed the button click event handler in the server side and you got the result. However, you may notice a delay because the page has to be submitted to the server to execute the event handler. NOTE: The event handling we just discussed is server side event handling. In addition to that, you can handle any events in the client side using Javascript. This is supported even in classic ASP. The client side event handling is used for simpel client side validation, displaying messages to the user etc. You cannot do any server side programming in client side java script (like accessing the database etc). This article talks about the Visual Web Developer (VWD) express edition. This tutorial is all about ASP.NET and web development. The ideal environment to develop ASP.NET pages is, using Visual Studio 2005. However, if you cannot spend lot of money to buy the VS.NET license, you can go for VWD (Visual Web Developer). VWD is free, if you download and register the product from Microsoft web site before November 2006. (This means VWD will be free for ever, if you download and register before November 2006). 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. Where can I download Visual web Developer (VWD)? You can download VWD from this Microsoft page - http://msdn.microsoft.com/vstudio/express/vwd/. There is a download link on the right side of the page. Sample projects Our tutorials are targetted for beginners and we assume most of them are using

Page 27: ASP.NET

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. Learn more about the Built in web server that is part of the new development environment. Installing and configuring IIS is a painful job for beginners. Here is the good news. VWD comes with a buil in web server. Now you can build and test applications locally using the built-in Web server, without needing IIS. Just create a new web project using VWD and run it. Your built in web server will automatically start and you can view the web pages. However, the free builtin web server is only for development and testing purpose. If you need to develop a website in a server, you need to install IIS on the server. This article explains what happened to the concept of "project file" in ASP.NET If you are an experienced .NET developer, you must be familiar with the project files with the extension .csproj or .vbproj (depending on the language you choose to develop your project). In ASP.NET 2.0, there is no concept of "project" for web sites. All web pages and related files are organized directly under the "solution". You create a new web site using VWD and a solution will be automatically created for you. If you look at your web site folder using windows explorer, you will just see a couple of default files, but no project files. The solution files are located in your "Documents and Settings" folder by default. After you create a new web site using VWD, look into the folder C:\Documents and Settings\<Your Windows Login Name>\My Documents\Visual Studio

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. Let us get started with a new VWD web site. I believe you have successfully installed Visual Web Developer. if you have not yet installed VWD, download and install now. Create a new web site In the previous chapter you learned the first step to create an application is to 'create

Page 28: ASP.NET

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

Page 29: ASP.NET

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. We have been trying with small web pages created without using Visual studio. In this chapter, you will learn how to use VS.NET to create a web application.

This chapter talks about Visual Studio .NET. If you are using This chapter talks about Visual Studio .NET. If you are using This chapter talks about Visual Studio .NET. If you are using This chapter talks about Visual Studio .NET. If you are using Visual Web Developer Visual Web Developer Visual Web Developer Visual Web Developer Express instead of Visual Studio .NET, you may skip this chapter.Express instead of Visual Studio .NET, you may skip this chapter.Express instead of Visual Studio .NET, you may skip this chapter.Express instead of Visual Studio .NET, you may skip this chapter.

Do you need Visual Studio to create web pages? In an earlier chapter you learned how to create a simple web page without using VS.NET. You simply used notepad to type your code and save as a .aspx page.no You can follow the same approach to develop more complex web pages. But using VS.NET can help you develop web pages much faster than using notepad. What is Visual Studio .NET ? Visual Studio .NET is the editor from Microsoft which allows you to write code easily and fast. Ideally, you 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!! How to create a web application using Visual Studio .NET Open the Microsoft Visual Studio .NET from your programs menu. It will come up with a default start up page. The default startup page shows the list of projects you recently worked under the title 'Open an Existing Project''Open an Existing Project''Open an Existing Project''Open an Existing Project'. If you are using VS.NET for the first time, you may not see any existing projects. In the bottom of the page, you can see two buttons: 1. New Project

Page 30: ASP.NET

2. Open Project Click the 'New Project' button to create a new project.

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 > File > New > File > New > File > New > ProjectProjectProjectProject 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".

Page 31: ASP.NET

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. localhostlocalhostlocalhostlocalhost means you are creating the web site on the local web server on your own computer. The second part (WebApplication1WebApplication1WebApplication1WebApplication1) 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) Files created by VS.NET Now, let us go to the explorer and see where the project and files are created. When you created the project, you didn't specify a physical location. Instead, you said "http://localhost/". In this case, the project will be created in the default location of your web server. The default location for a web server is C:\Inetpub\wwwroot. Go to this folder and you will see that there is a new folder called "WebApplication1" created here. Inside that, there are several other files created by 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. This article explains what happens behind the scenes when you create a new web application using Visual Studio .NET.

Page 32: ASP.NET

In the previous chapter, you created a new web application using Visual Web Developer (Or, Visual Studio.NET). Even though you did not do much work other than simply pressing few buttons, VWD created a web application for you. Files created by VS.NETFiles created by VS.NETFiles created by VS.NETFiles created by VS.NET Now, let us go to the windows explorer and see where the project and files are created. 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:\Inetpub\wwwroot instead of C:\AspSpider\.) 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': <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="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 > Start Without

Debugging (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

Page 33: ASP.NET

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 default.aspx. See the part: <title>Untitled Page</title> Change it to <title>My First Web Site</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. Adding content to the page If you need anything to be displayed in your web page, you must add it inside the <body> tags. Add a welcome message as shown below, inside your BODY tags: <body> <form id="form1" runat="server"> <div> Welcome to my first web page! </div> </form> </body> Note that, in ASP.NET, you must place content inside <Form> tags, within the <BODY> tags. Now build and view the web page by pressing Ctrl + F5. You will see the following text displayed in your web page in Internet Explorer. Welcome to my first web page!

This article gives an introduction to the "build" and "debug" process using VWD. We have mentioned the term couple of times earlier in this tutorials. If you are very new to programming, you may be wondering what is meant by "build". Any one with basic programming knowledge will know that you must compile a source file before you can execute it. A compilation process will convert the source file into a binary executable file. If you have 10 web pages in a web project, you must compile each of these 10 files into 1 or more binary executables. If you are using notepad to develop web applications, you have to use command line tools to compile each file.

Page 34: ASP.NET

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. How to build a web site using VWD ? When you use VWD to build a web site - it is just one button click. There are couple of ways you can do this in VWD: 1. Click on the shortcut toolbar for Build 2. Use the menu option Build -> Build Solution 3. Use the keyboard shortcut Ctrl + Shift + B When you use any of the above optiosn to build a solution, VWD does the following: 1. Identifies all the files part of the project. 2. Checks for compilation errors for each file in the solution. Older versions of ASP.NET projects used to compile all the source files into an assembly and put them into a folder called "Bin". From ASP.NET 2.0 onwards, there won't be any "bin" folder created. Instead, source files will be compiled dynamically when a request is made for that particular piece of code. However, when you "build" the solution using VWD, it verifies each file for compilation errors to avoid any compilation error during run time. How to run the web site from VWD ? Pressing Ctrl + Shift + B will only build the web site, but it will not launch the site. There is another short cut to build and launch the web site with one step. There are different ways you can do this: 1. Click on the shortcut toolbar "View in Browser" (this step will not check for compilation errors) 2. Use the menu option Debug -> Start without Debugging 3. Use the keyboard shortcut Ctrl + F5 You may notice another menu option called Debug -> Start Debugging. This option will also compile and launch the web site in debug mode. You will learn more about debugging later in this tutorials. This article explains what happened to the good old "Bin" folder in ASP.NET 2.0 What happened to Bin folder in ASP.NET 2.0 If you have worked with ASP.NET 1.0 or 1.1, this may be bit confusing for you. Older versions of ASP.NET projects used to compile all the source files into an assembly and put them into a folder called "Bin". When you build a web application project using Visual Studio 2002 or Visual Studio 2003, it used to compile all files

Page 35: ASP.NET

into a DLL and copy them to the special folder called "Bin". From ASP.NET 2.0 onwards, there won't be any "bin" folder created. Instead, source files will be compiled dynamically when a request is made for that particular piece of code. However, when you "build" the solution using VWD, it verifies each file for compilation errors to avoid any compilation error during run time. Where does the referenced assemblies go ? If you have worked with .NET projects before, you must know that a web application may refer to several other class libraries and assemblies. When you add a reference to another DLL using Visual Studio, the DLL will be copied to the Bin folder automatically. This concept still exists. If you add a reference to another DLL using VWD, the "Bin" folder will be automatically created under the web site folder and DLL will be copied to the Bin folder. This chapter explains what is "Solution Explorer" in Visual Studio .NET Solution ExplorerSolution ExplorerSolution ExplorerSolution 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.

Page 36: ASP.NET

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. How to switch between design and html modes ? You can easily switch between modes when an aspx file is opened in VS.NET. Double click on an aspx file in the solution explorer to open it in the editor. Now you can see 2 buttons as shown below in the bottom left corner of the page.

Page 37: ASP.NET

To switch between modes, click on the Design/HTML links. If you drag and drop a control in design mode and switch to the html mode, you can see the corresponding html code. Similarly, you can type code in html mode and switch to design mode to view it. In this chapter you will learn the various files created by Visual Studio when you create a new web project. This chapter talks about default files generated by Visual Studio .NET 2003. We This chapter talks about default files generated by Visual Studio .NET 2003. We This chapter talks about default files generated by Visual Studio .NET 2003. We This chapter talks about default files generated by Visual Studio .NET 2003. We have not yet updated this page for files generated by VS.NET 2005 or Visual Web have not yet updated this page for files generated by VS.NET 2005 or Visual Web have not yet updated this page for files generated by VS.NET 2005 or Visual Web have not yet updated this page for files generated by VS.NET 2005 or Visual Web Developer Express.Developer Express.Developer Express.Developer Express. Let us learn more about the default web page created by Visual Studio in the previous

chapter. 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.

The solution explorer shows the following files:

Page 38: ASP.NET

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.vb.vb.vb file will be opened in VS.NET 2. Click on the project name 'Web Application 1' in the solution explorer. Now click the icon 'Show All Files' in the top portion of the solution explorer. Now the solution explorer view will slightly change and it will show the hidden files also. You can click on the + sign to expand and view all the hidden files. Double click on any file to open and view it in VS.NET

Page 39: ASP.NET

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. In this chapter you will learn the various elements and HTML tags in the default web page created by the Visual Studio. To view the contents of a file, double click on the file name in solution explorer. Open the default aspx file 'WebForm1.aspx' in HTML mode.

The contents of the default web page ('WebForm1.aspx') created by Visual Studio looks like this:

Page 40: ASP.NET

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="WebApplication1.WebForm1"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>WebForm1</title> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1"> <meta name=vs_defaultClientScript content="JavaScript"> <meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5"> </head> <body MS_POSITIONING="GridLayout"> <form id="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. <%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="WebApplication1.WebForm1"%> The element Codebehind="WebForm1.aspx.vb"Codebehind="WebForm1.aspx.vb"Codebehind="WebForm1.aspx.vb"Codebehind="WebForm1.aspx.vb" says that this file uses the vb file "WebForm1.aspx.vb". The next element Inherits="WebApplication1.WebForm1Inherits="WebApplication1.WebForm1Inherits="WebApplication1.WebForm1Inherits="WebApplication1.WebForm1 says this aspx page is inherited from the class WebForm1WebForm1WebForm1WebForm1 which is part of the namespace WebAppliaction1WebAppliaction1WebAppliaction1WebAppliaction1. (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> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1"> <meta name=vs_defaultClientScript content="JavaScript"> <meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5"> </head> <body MS_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.

Page 41: ASP.NET

<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. <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1"> <meta name=vs_defaultClientScript content="JavaScript"> <meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5"> You will learn more about META TAGS later. The following tag is very important for any aspx page. <form id="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. <form id="Form1" method="post" runat="server"> <font size=5 color=red>hello World</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.

Page 42: ASP.NET

This article explains the concept of code behind files in VS.NET In the solution explorer, you can double click and open any aspx file. Also, in one of the previous chapters you learned you can click on "Show All Files" icon to view the related hidden files. You may have noticed that when VS.NET creates an aspx file, it creates 2 other files too. One with the extension .resx.resx.resx.resx and one with the extension .vb.vb.vb.vb (or .cs.cs.cs.cs if you choose C#). When VS.NET created the default file 'WebForm1.aspx', it created the following files also: WebForm1.aspx.resx WebForm1.aspx.vb (When a file name has more than one dot (.) in it, only the last one will be considered for the extension of the file. So, the full file name is WebForm1.aspx.resx and the extension of the file is .resx.resx.resx.resx.) How to create a new ASPX file in Visual Studio? Right click on the project name in the solution explorer. Select the menu "Add" > "Add Web Form". This will prompt you to select a file name. Enter the name "MyProfile.aspx". Now VS.NET will create 3 files for you: MyProfile.aspx MyProfile.aspx.resx MyProfile.aspx.vb 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. What is Code Behind Files ? Now let us come to the key of this chapter - The code behind file. In the above example, MyProfile.aspx.vb is the code behind file. As the name indicates, it is the file which holds the code for the aspx page. It is a nice idea by the ASP.NET team - to separate a web page into different files. The HTML tags and ASP.NET controls for the UI elements goes to the aspx page. The server side code (VB or C# or any other language) goes to the code behind files. This way, the files looks very clean and neat. With this approach, you don't need to mix the html tags and server side tags (<% %>) in the aspx pages.

Page 43: ASP.NET

In the previous chapter you learned how the aspx knows it's code behind file - by using the @Page directive in the top of the page. 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. How to write code in the code behind file ? Open the aspx file and select the "Design Mode". Simply double click on the designer form. This will create an "Page_Load" event handler in the code behind file and open the code behind file automatically. Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load End Sub 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: Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Response.Write ("Hey, my page is loaded ...") End Sub 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. This article gives an introduction to ASP.NET web controls ASP.NET web controls are the controls provided by the ASP.NET team to help you develop complex web pages.

Page 44: ASP.NET

Some of the web controls are: 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:Label id="Label1" style="Z-INDEX: 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 = "Welcome to my First ASP.NET Page. Current Server time is " & 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. Changing Properties of a Web Control VS.NET allows you to set various properties of the web controls in design mode, saving you lot of typing. Switch to design mode in your aspx page. Select the label control you just created and press "F4". Or, you can click on the "Properties" window title on the right edge to open it. This will slide and open the Properties window on the right side of the VS.NET editor. You can change various properties of the label control. (Sometimes, old versions of VS.NET will fail to open the Properties window. It will

Page 45: ASP.NET

simply freeze up. In that case, click on the menu ToolsToolsToolsTools > Options> Options> Options> Options and press the button "Reset Windows Layout".) For our simple testing, change the Font Size property to "XX-Large". ("Size" property is located under the property "Font". You must click the "Font" to view the sub properties.). Also, change the property "Forecolor" to "Red". When you change any property in the design mode, VS.NET actually puts appropriate tags in the aspx page. You can switch to the HTML mode and see the changes. 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. This article explains how to change the properties of web controls at run time. In the previous chapter, you learnt 2 ways to change the properties of a web control: 1. Change in the Properties window in design mode 2. Type the properties manually in aspx page in HTML mode. These two methods allows you to set the properties at the time of designing the page. What if you need to change the properties at run time? You may have one label control in the page which you use to display the success or error message depending some conditions. For example, in a "Login" page, if the login id or password is wrong, you want to display the error message in Red color. If the login information is correct, you want to display a welcome message in Green color. For the both the messages you can use same Label control. Only thing is, you need to change the Font color at run time depending on the login status. To try this out, let us create a sample web page and drag & drop a Label control to it. (You can use the default web page created in the previous chapters.) In the Page_Load event, write the following code:

Page 46: ASP.NET

Label1.Forecolor = Color.FromName("GREEN") Label1.Text = "Successfully processed." 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 = "An error occurred." 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 it's properties in the coming chapters. This article explains how to use various properties and events associated with web controls like Textbox and Button. In the previous chapters you learned how to create a new web form and add a label control to it. You also found how to change the properties of the Label control in design time and run time. In this chapter, you learn the most frequently used controls - the Textbox and the Button controls. Create a new webform Let us start fresh by creating a new web page. Right click on the project name in the solution explorer and select Add > Add Web Form. Select the file name as 'WebForm2.aspx'. Now you have a blank form. In the design mode, drag and drop two Label controls, one Textbox and one Button. Select each control and change the properties as shown below: Label1: ====================== Id - lblMessage Label 2: ====================== Id - lblLabel Text - What is the current day?

Page 47: ASP.NET

Textbox ====================== Id - txtCurrentDay Text - Monday Button ====================== Id - btnSubmit Text - Submit Arrange the position of the controls so that they look as shown below:

Handling events in ASP.NET Let us write an event handler for the click event of the Button control. All you have to do is, just double click on the button control in the designer. Visual Studio will automatically create an event handler for you, as shown below: Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click End Sub Notice the Handles btnSubmit.Click. This statement says this is the method that handles the Click event 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 Handles btnSubmit.Click is there at the end of it. Event Handlers - Difference between VB.NET and C# The event handlers are created slightly different in C#. If you double click on a button in the web form in C#, Visual Studio will create the event handler as shown below: private void btnSubmit_Click(object sender, System.EventArgs e) { } Note that there is no Handles btnSubmit.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 #region Windows Form Designer generated code. You may need to click on the + sign on the left end of the line #region Windows Form

Designer generated code to view the hidden code in this region.

Page 48: ASP.NET

In C#, the line this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click); says which method need to be called when a button is clicked. 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. Dim userDay As String = txtCurrentDay.Text Dim currentDay As String = DateTime.Today.DayOfWeek.ToString() If userDay = currentDay Then lblMessage.Text = "Great! You got it right." lblMessage.ForeColor = Color.FromName("DarkGreen") Else lblMessage.Text = "Oops! You are wrong. Today is '" & currentDay & "'." lblMessage.ForeColor = Color.FromName("Red") End If Here is the C# code, if you are working on C#. string userDay = txtCurrentDay.Text; string currentDay = DateTime.Today.DayOfWeek.ToString(); if (userDay == currentDay ) { lblMessage.Text = "Great! You got it right."; lblMessage.ForeColor = Color.FromName("DarkGreen"); } else { lblMessage.Text = "Oops! You are wrong. Today is '" + 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.

Page 49: ASP.NET

TextChanged event for Textbox in ASP.NET Let us try to learn one more event called 'TextChanged' for the Textbox. This is not widely used, but let us do it for learning purpose. Double click on the Textbox in the designer view. This will create the TextChanged event handler. Simply copy paste the code from the button click event handler to this TextChanged event handler. Run the application and see. You must press 'Tab' from Textbox to trigger the Textchanged event. But in our case, it will not fire the event even though we have written the event handler. We have to do one more step to fire the Textchanged event. Go to the designer and see the properties of the Textbox. You must change the property 'AutoPostBack' to true. This is 'False' by default to avoid triggering Textchanged events unncessarily. Also note that, the Textchanged event will be fired only if you change the current text in the Textbox. If you simply press 'Tab' by leaving the default value 'Monday' there, it will not be fired. Change it to 'Tuesday' and press 'Tab'. You can see that the Textchanged event handler is executed. In windows programming, the textchanged event will fire when you type any character, not after you move out from the textbox control. Write solid application Did you notice that if you type 'mmmmonday' instead of 'Monday', it will not match? Let us modify our code so that it will work even if user type the correct day, with a different case. 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. Write re usable code When you made the above change (if (userDay.ToUpper() == 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:

Page 50: ASP.NET

Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click ' Call the common method ValidateUserData() End Sub Private Sub txtCurrentDay_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtCurrentDay.TextChanged ' Call the common method ValidateUserData() End Sub ' This is the common method which validates the user input and displays the result. Private Sub ValidateUserData() Dim userDay As String = txtCurrentDay.Text Dim currentDay As String = DateTime.Today.DayOfWeek.ToString() If userDay.ToUpper() = currentDay.ToUpper() Then lblMessage.Text = "Great! You got it right." lblMessage.ForeColor = Color.FromName("DarkGreen") Else lblMessage.Text = "Oops! You are wrong. Today is '" & currentDay & "'." lblMessage.ForeColor = Color.FromName("Red") End If End Sub This is a fundamental concept you have to learn. Always break your code into small small methods and call these methods in your application. 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 Take the first example - System.Web.HttpRequest. In the above example, HttpRequest is the name of the class, which is defined in the namespace System.Web

Page 51: ASP.NET

In object oriented programming, if you want to create an object of a class, you may use a syntax like below: dim mySocket as Socket = new Socket() 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: dim request as System.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. This article talks about the Request object in ASP.NET Before we go deep into the ASP.NET Request object, you must understand 'What is a Request ?'. What is a web request ? In simple words, a web request a 'request sent from a client to the server, asking for a specific web page'. When you type a URL in a web browser or when you click on a hyper link in any web page, your browser is actually making a 'Request' to the server for the specific URL. Who makes the Request ? If you are using a browser to view a web page, then your browser is making the actual request to the server. You simply typed a URL in the browser, but the browser does lot of work in the background. It composes a Request in the proper format that the server can understand and sends the request to the server using the HTTP procol. Composing the Request

Page 52: ASP.NET

Composing and sending the request involves lot of work, even though a user need not worry about it. It is the responsibilty of the browser to compose and send the request in the proper format. 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') ASP.NET Request Object 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. Commonly used Methods and Properies of Request object Request.FilePath This property returns the currently executed file path. 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: ' Get the current tutorial Id from the query string. dim tutorialId as Int32 = Request.QueryString("TutorialId") ' Now get the chapter from database based on the tutorialId.

Page 53: ASP.NET

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 value from the Cookie as shown below: Dim cookie As System.Web.HttpCookie = Request.Cookies("AspSpiderUserId") if cookie is nothing then Response.write ("Cookie 'AspSpiderUserId' not found.") else Response.write ("Value of Cookie 'AspSpiderUserId': " & cookie.Value) end if 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: dim ipAddress as string = Request.ServerVariables("REMOTE_HOST'") Response.Write ("Your IP Address is : " & ipAddress) You can find which version of browser they are using to access your web site. dim browser as string = Request.ServerVariables("HTTP_USER_AGENT'") Response.Write ("You are using this browser to access our web site: " & browser)

Page 54: ASP.NET

There are several server variables available to find more information from the Request. Try the following server side code in your web page: dim str as string For Each str in Request.ServerVariables.AllKeys Response.write ("Key : '" & str & "' - Value '" & Request.ServerVariables(str) & "'") Next

This article explains the ASP.NET Response object and various methods of it. 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. How does a browser process the Response ? The response includes several information about the page requested including the cookies to be saved on the client machine, the actual content to be displayed to the user etc. The browser accepts the response and processes it. Browser does several things including saving the cookies, checking the security etc and then displays the page content to the user. Note that displaying the page content to the user in the browser is only a small portion of the actual work. ASP.NET Response Object The ASP.NET provides a class called HttpResponse 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 response. 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 Response. In old ASP days, the Response object was the only way to write data to the page. ASP.NET provides the event handling mechanism and web controls so that you can write content to the page in an easier way. Frequently used Methods and Properies of Request object Response.Write This method is used to write dynamic text to the web page. In old ASP days, this was the only way to generate dynamic text and display to the user. 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

Page 55: ASP.NET

below: Response.Write("<table width=500>") Response.Write("<tr>") Response.Write("<td align=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 = "your user id" 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. Dim cookie As System.Web.HttpCookie = Request.Cookies("AspSpiderUserId") if cookie is nothing then Response.write ("Cookie 'AspSpiderUserId' not found.") else Response.write ("Value of Cookie 'AspSpiderUserId': " & cookie.Value) end if 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.

Page 56: ASP.NET

if (bStatus = True) then Response.Redirect("Success.aspx") else Response.Redirect("Error.aspx") end if 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. This article explains what is a session and how to handle sessions in ASP.NET 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". This article explains when a session is established and expired. When is a session established ? A new session is established when a page is requested first time from a website. When you typed the URL http://www.aspspider.com, a new session is established for you in our web server. The same session is re used every time you hit another page. If you open another browser and type the URL again, it is another session. In that case, two sessions will exists for you at the same time independently. When and how the session expires ? A session expires in the web server, if the browser does not request a page from the server for a 'specific' period of time. This period is configurable and each web server can have it's own session timeout. The default session time out in ASP.NET is 20 minutes. This means, if you take more than 20 minutes to read a page and click another link, then your session is already

Page 57: ASP.NET

expired. But you may never notice that your session is expired. If you hit a page after the session is expired, the web server will treat this as a brand new request and establish a new session for you. There may not be any visible change for you, in most cases. But if you are logged in into a web site, most of the sites store your user information in session. If you sit idle for long time, your session may expire and the server will lose all your information from the session. When you hit the site again, it will establish a new session. This is why you are automatically logged out from many sites, if you sit idle for some time. 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. How many session IIS can have? There are some practical limits, but for each user accessing the site, there will be a separate session. If 5000 visitors are accessing this site at a time, we will have 5000 active sessions in our web server. How to change session time out in ASP.NET ? The session timeout can be changed in web.config. Open your web.config file and you may see an entry like this: <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

Page 58: ASP.NET

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. This article explains various methods and proeprties of the ASP.NET Session Object. ASP.NET Session Object ASP.NET provides a class called HttpSessionState, which is part of the namespace System.Web.SessionState. Just like Request and Response objects, an HttpSessionState object is also created automatically for you in ASP.NET pages. This object is called "Session". You can access various methods and properties of this object. 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. How to store and retrieve values in ASP.NET session ? Just like you can store values in variables, you can store values in session. Basically, you can assign values to session variables. See the following example: The following code sample shows how to store a string value 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. How long a session variable is valid ? A session variable retains it's value as long as the session is valid. Session variables are valid across all pages, as long as you access all those pages from the same browser and within the timeout period. If you assign a value into a session variable from Page1.aspx and try to retrieve it from Page2.aspx, it will 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. What can be stored in a session? The above examples show storing and retrieving simple strings in session. But you can store complex datatypes like Dataset also into session. Many websites retrieve lot of user data from database and store into session so that it can be accessed faster from memory (session) rather than retrieving from database.

Page 59: ASP.NET

However, it is not reccommded to store lot of data into session for large websites. Session data is stored in memory and if there are thousands of online users at the same time, server may run out of memory. This article explains the purpose of Session variables In most of the web sites, when a user log In in the login page, they set few variables to session. if (bLoginSuccess = true) then Session("UserId") = txtLoginName.Text Session("Name") = GetUserNameFromDatabase(txtLoginName.Text) else Response.Redirect ("LoginError.aspx") end if 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". dim userId as string = Session("UserId") if ( userId = "" ) then Response.Redirect("Login.aspx") else Response.Write ("Welcome " & Session("Name")) end if 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. dim userId as string = Session("UserId") if ( userId = "" ) then Response.Write("<a href='Login.aspx'>Login</a>") else Response.Write ("Welcome <a href='MyAccount.aspx'>" & Session("Name") & "<a>) end if 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

Page 60: ASP.NET

be valid only until the session expires. Also, this value will not be accessible for another user/session. This article explains how a web server identify repeated requests from a web browser. How does the server identify a browser ? The first time when a browser request a page, server establishes a session and creates a session Id. Server returns this ID to the browser as part of the 'Response'. This ID is not displayed to the user. Browser will keep this internally. There are cases where this Session ID can be visible to the users. Visit HomeDepot.com and hit any link from the home page. Then check the URL in the browser. You can see a string like BV_SessionID=@@@@0941891585.1123945660@@@@. This number represents the session id. This particular site sends the session id as a query string in the URL. If you delete this session id from the url, server will treat it as a new session and will create a new session. But ideally, in a ASP.NET web site, there is no need to make the session id publicly visible. Server can keep it internally and send to server without annoying you. After the browser gets a session ID, it will send the session ID to the server along with each additional page requests it makes. The webserver can identify the sessions using this Id. For some reason, if the 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. 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 can access this value. Example: Application("Current Stock Price") = 145.25

Page 61: ASP.NET

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("Current Stock Price") = GetFromExternalAgency() Example - retrieving from application variable: lblStockPrice.Text = "Stock Price: " & Application("Current Stock Price") Scope of an Application Variable An application variable is valid till the application shuts down or the aspnet process is terminated. In a web server, this process may run for several days without shutting down. In the above example, if stock price is retrieved and stored in the application variable, it will remain there until the process is restarted. The stock prices may change during this time, but you will not get the updated price. In such cases, you must have some mechanism to retrieve the stock price from external agency at some regular intervals and store into the application variable so that you will see the updated price. One way to do this is, store the retrieval time also into another application variable and check often how long it has been after it was last retrieved. If the elapsed time is more than 1 hour or so, retrieve again. ASP.NET provides another class called "Cache" which can be used to store key/value pairs like Application variables. This class is more efficient than using Application variables. Also, it provides several additional methods which will allow you to automatically expire the value in cache after some interval of time or when some "specific" event happens. You will learn more about the Cache class in upcoming chapters. This chapter gives an introduction to Cookies used in internet world. What is a cookie ?

Page 62: ASP.NET

Cookies are small files stored on the client computer. What can be stored in a cookie ? Web sites can store small pieces of information as key-value pairs in the cookie files. Any information can be stored in cookie as key-value pairs. However, there is alimitation on the total size of data that can be sent as cookie. Also, it is not safe to store sensitive information in cookie. Since cookies are stored as text files in client computers, a smart user can edit and change the values in the cookie files. Most of the web sites store information like your login name, last visit date etc so that when you visit the website next time, they can surprise you with messages like "Welcome back, Mr. John !" Also, you may have noticed that when you login to many websites, there is an option called "Remember my User Id". Those sites will store your user id into the cookies. When you visit the web site next time, they will retrieve the login id from the cookie. Based on the login id, they can retrieve all information about you from the database and automatically login you to the website. Note that they will not store all details about you. Only login id is stored in the cookie. And most often the login id will be stored as encrypted so that nobody can alter it to some other user's login id. Who creates cookies ? Cookies are created in your computer, by your browser, if the website send any cookie information as part of the page you visit. Browser seetings allow you to disable cookies. If you disable cookies, it will not store any cookies in your computer, even if the web site send any cookie to your computer. But note that, several websites assume you have cookies enabled and such websites may not work as expected any more, if you disable cookies. Where is it saved in your computer ? In windows machines, cookies are stored in the Cookies directory in your user directory within within the Documents And Settings directory. This directory contains text files with this filename format: your login name @ web site name.txt A cookie from AspSpider.com can be like this: [email protected] 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.

Page 63: ASP.NET

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. This chapter talks about storing and retrieving cookies in ASP.NET ASP.NET has 3 classes which allow you to work with Cookies. HttpCookie: provides a way to create and manipulate individual HTTP cookies. HttpResponse: The Cookies property allows to create and save cookies on client machines. HttpRequest: The Cookies property allows access to cookies from the client maintains. How to create a Cookie ? It is really easy to create a cookie in ASP.NET. You can use the Response object in ASP.NET to create cookies as key-value pairs. 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. How to retrieve values from Cookies ? You can use the Request object to retrieve values from the cookies which are already stored. Dim name As String = Me.context.Request.Cookies("UserName").Value If there is no cookie with the name "UserName", the above code sample will return an empty string. The HttpCookie class HttpCookie is another usefull class in ASP.NET which allows you to work with Cookies. Here is a code snippet which shows how to use this class: Dim myCookie As New HttpCookie("UserName") myCookie.Value = "Mr. John" myCookie.Expires = DateTime.Now.AddDays(1)

Page 64: ASP.NET

myCookie.Domain = "aspspider.com" Response.Cookies.Add(myCookie) How cookies are stored and retrieved ? You saw the sample code which uses Request and Response objects to store and retrieves values in Cookies. Do you know how they really work? When you execute the line Response.Cookies("UserName").Value = "Mr. John", it runs on the server. It has no connection with the client computer. Then how is it saving on the client computer? When your browser request a URL from the web server, what it gets back is a 'big packet'. This packet has lot of information which includes the meta data, cookies, content of the page to be displayed to you etc. So, the cookies is part of the response the browser gets back from the web server. Browser knows 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. This article gives an introduction to the configuration files used in .NET applications. Configuration File for .NET applications .NET gives an easy way to store configuration information in an Application Configuration File. In the simple implementation, you can store information as Key-Value pairs. For example, consider a case where you use a database in your application. If you hardcode the data base information in your code, you will have a tough time when you have to change this data source. You have to change your source code and re-compile it. This won't work every time you give your product to different customers or when you run your application in different machines! In earlier days, programmers used to store this information in special files called .ini files or in windows registry. The database information will be stored in the .ini file or registry and application can read the information from these locations. No need to re-compile the code when the values are changed in .ini file or registry. But this is a pain most of the time. It is not fun opening the registry, locate your entries and make appropriate changes. It is quite possible that you may mess up with some important entries in the registry and make your system not run any more. In fact, in secured systems, administrator may deny access to the registry and users will not have the choice to edit the registry at all. Ini files also have some draw backs. We can store only simple string values as key/value pairs.

Page 65: ASP.NET

.NET gives you a simple and easy solution for this problem - the Application Configuration File. This file is usually called as config file. Each application can have a configuration file, which is actually an XML file. You can use any text editor (including Notepad) to open the configuration file and change the values. The application will load the values from this configuration file and you do not have to change your source code every time you change your data source or any other information stored in the 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. This chapter explains the App.config file used for Windows applications app.config for Windows applications Windows applications in VS.NET use the name app.config by default for the configuration file. This will not be automatically created when you create a Windows application. If you need a configuration file for your application, open your project in VS.NET, go to the 'Solution Explorer' and right click on the project name. Choose Add > Add new item from the menu and select 'Application Configuration file' from the list of choices. This will create an app.config file for you in the application root. By default, the app.config file will have the following content: <?xml version="1.0" encoding="utf-8" ?> <configuration> </configuration> To store values in the configuration file, you can create XML elements in the format: <add key="MyKey" value="MyValue" /> See the sample config entries below: <?xml version="1.0" encoding= "utf-8" ?> <configuration> <appSettings> <add key="DatabasePath" value="c:\\projects\data\tutorials.mdb" /> </appSettings> </configuration> And to read from this config file, just use the following code in your application:

Page 66: ASP.NET

dim dbPath as string = System.Configuration.ConfigurationSettings.AppSettings("DatabasePath"); 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: using System.Configuration; If you have the above directive on top of the file, then you can directly use the class ConfigurationSettings. string dbPath = ConfigurationSettings.AppSettings("DatabasePath"); In C#, you have to use "[ ]" instead of the "( )", as shown below: string dbPath = 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. Web.config for Web applications The web applications use the same concept, but they use a config file with the name web.config. There are couple of things to note in this case. * web.config is created automatically by VS.NET when you create any web project. * When you compile the web application, web.config is NOT renamed or copied to the BIN folder. * web.config has several default entries in it to support web/IIS configuration & security. * You can add the <appSettings> section in the web.config and add your key/value pairs in that section. * You can have separate web.config files for each directory in your web application, in addition to the one in the root. For each web page, by default, system will look for

Page 67: ASP.NET

a web.config in the same folder as the page and if not found, then looks in the parent folder. You can store and retrieve key/value pairs in the web.config file just like the app.config files: <?xml version="1.0" encoding= "utf-8" ?> <configuration> <appSettings> <add key="DatabasePath" value="c:\\projects\data\tutorials.mdb" /> </appSettings> </configuration> To read key/value pairs from <appSettings> section, use the following code: dim dbPath as string = System.Configuration.ConfigurationSettings.AppSettings("DatabasePath"); 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="data source=127.0.0.1;user id=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. This chapter explains the purpose of global.asax file Every web application created in VS.NET creates a file called 'global.asax' and 2 related files called 'global.asax' and 'global.asax.resx'. The files global.asax is a replacement for the global.asa file used in classic ASP. Global.asax.vb is the code behind file for he global.asax. This file is used to handle global events in the web application. You must be already familiar with event handling in ASP.NET. If a page level event

Page 68: ASP.NET

happens, it can be handled in code behind file of the corresponding page. But there are couple of events which are not specific to any page. These events are applicable to the entire application. Global.asax and the code behind file global.asax.vb are used to handle such global events. When VS.NET creates the global.asax file, it creates these event handlers without any code in it. If you want to handle any of these events, you just need to insert your code to appropriate event handler. This article explains the Global.asax file and various events handled in Globa.asax file. The following are the global events handled in the global.asax.vb file. Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) End Sub 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. Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs) End Sub Session_Start event is fired each time a new session is started. Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs) End Sub Application_BeginRequestis fired each time a new page is requested in the website. This event is fired after the Session_Start event. Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs) End Sub Application_AuthenticateRequest is fired upon attempting to authenticate the user

Page 69: ASP.NET

and after the Application_BeginRequest event. Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs) End Sub 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. Sub Session_End(ByVal sender As Object, ByVal e As EventArgs) End Sub 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. Sub Application_End(ByVal sender As Object, ByVal e As EventArgs) End Sub 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 event will never be fired. 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 Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs) End Sub 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

Page 70: ASP.NET

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: Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs) ' Retrieve the last error in the website Dim ErrorInfo As Exception = Server.GetLastError().GetBaseException() ' Email the error message to the webmaster System.Web.Mail.SmtpMail.Send("[email protected]", "[email protected]", "Un expected error", ErrorInfo.Message) ' Redirect the user to a friendly error page. Response.Redirect("Error.aspx?Message=" & ErrorInfo.Message, True) End Sub The above code will find the last error occurred, send an email to webmaster and then redirect the user to an Error page. This article explains how to organize the learning projects from this tutorial. We will be doing several small and large sample ASP.NET projects part of this tutorials. Let us organize all the sample projects into one folder. Create a folder called "AspSpiderAspSpiderAspSpiderAspSpider" in your C:. This will be the place where you will do all your learning projects from this site. When you create a new project, make sure it is stored under the folder C:\AspSpider. Optional steps when use Visual Studio.NET The below steps are applicable only if you are using Visual Studio. You can skip the below steps if you are using Visual Web Developer Express (VWD)Visual Web Developer Express (VWD)Visual Web Developer Express (VWD)Visual Web Developer Express (VWD) When you create a new ASP.NET project, first create a folder under C:\AspSpider with the folder name same as the project name. Then make the new folder a virtual folder. This will ensure that VS.NET will create the project within this new folder and put all the files under this. When you create a new ASP.NET project, VS.NET will look for a virtual directory with the name of the project. If it finds one, it will copy all the files under this. If it cannot find a virtual directory, it will create a new folder with the project name under C:C:C:C:\\\\InetpubInetpubInetpubInetpub\\\\wwwrootwwwrootwwwrootwwwroot and make it a virtual directory. For example, assume you are creating a project called "AddressBook" using VS.NET. First, Visual Studio will search your system to find if there is already a virtual directory called "AddressBook". If it finds one, it will create the project within this folder. If it cannot find one, it will create a new folder called "AddressBook" under C:\Inetpub\wwwroot.

Page 71: ASP.NET

This chapter leads you to create a small project where we can try various concepts you learned so far. This sample project is developed using Visual Studio.NET 2003. IsThis sample project is developed using Visual Studio.NET 2003. IsThis sample project is developed using Visual Studio.NET 2003. IsThis sample project is developed using Visual Studio.NET 2003. Is you are using you are using you are using you are using VS.NET 2005, you can just follow almost all the steps wihtout much changes and re VS.NET 2005, you can just follow almost all the steps wihtout much changes and re VS.NET 2005, you can just follow almost all the steps wihtout much changes and re VS.NET 2005, you can just follow almost all the steps wihtout much changes and re compile the downloadable samples. But if you are using Visual Web Developer compile the downloadable samples. But if you are using Visual Web Developer compile the downloadable samples. But if you are using Visual Web Developer compile the downloadable samples. But if you are using Visual Web Developer Express (VWD), the samples and screenshots may not work for you. If you are using Express (VWD), the samples and screenshots may not work for you. If you are using Express (VWD), the samples and screenshots may not work for you. If you are using Express (VWD), the samples and screenshots may not work for you. If you are using VVVVWD, you may skip this project. All our upcoming projects will be using VWD.WD, you may skip this project. All our upcoming projects will be using VWD.WD, you may skip this project. All our upcoming projects will be using VWD.WD, you may skip this project. All our upcoming projects will be using VWD. Even if you are using VWD, you may go through the pages to understand the Even if you are using VWD, you may go through the pages to understand the Even if you are using VWD, you may go through the pages to understand the Even if you are using VWD, you may go through the pages to understand the concepts.concepts.concepts.concepts. Tired of reading too much theory? Ok, it is time to try out whatever you learned so far. In this chapter, we will create a small project and try various concepts we learned so far. This is a small project with no real world usage, but you can learn lot of things from this. 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 won't 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. Create new project Under C:\AspSpider, create a new folder called "UserTracker". Make this folder a virtual

directory by right clicking on the folder name and selecting "Properties > Web Sharing > Share this folder". We did this to ensure that VS.NET will create the web project within this folder. Now go to Visual Studio and create a new ASP.NET application. Select VB.NET or C# whichever you are comfortable with, but this tutorial will use VB.NET language for code samples. Create the project with the name "UserTracker" by selecting options as shown below:

Page 72: ASP.NET

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. You will expand your UserTracker project here and add a Login page. In the previous chapter, you created a new project called "UserTracker". We are going to expand it to have some real features! Create a Login page When VS.NET created the project, it created a default page called "WebForm1.aspx". Right click on this file in solution explorer and rename it to "Login.aspx". Note that when you rename the aspx file, the code behind file also will get renamed. Add controls to Login page We are going to add some controls to the login page. You can drag and drop controls from Toolbox to the page when the page is in design mode. For time being, copy paste the following code to the aspx page when it is in HTML mode. <asp:Label id="lblMessage" style="Z-INDEX: 101; LEFT: 95px; POSITION: absolute; TOP: 58px" runat="server" Width="194px" Font-Bold="True" ForeColor="#C00000"></asp:Label> <asp:Panel id="pnlName" style="Z-INDEX: 102; LEFT: 13px; POSITION: absolute; TOP: 130px" runat="server" Width="398px" Height="46px"> <asp:Label id="Label1" runat="server">Enter your name:</asp:Label> <asp:TextBox id="txtName" runat="server"></asp:TextBox> <asp:Button id="btnProceed" runat="server" Text="Proceed"></asp:Button>

Page 73: ASP.NET

</asp:Panel> <asp:HyperLink id="HyperLink1" style="Z-INDEX: 103; LEFT: 17px; POSITION: absolute; TOP: 211px" runat="server" NavigateUrl="ShowNames.aspx">Show Names</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:

Controls in Login Page The above code sample adds the following controls to the page: 1. lblMessage - This is a Label controlLabel controlLabel controlLabel control, used to display some messages. We have changes xomep properties like Forecolor, Font-Bold etc. 2. pnlName - This is a Panel controlPanel controlPanel controlPanel control. A panel is an invisible control, used to just group some other controls. In this page, our panel includes another label, textbox and a button. If we set some properties like 'Visible = False' for the panel, it will hide all controls within the panel. So, if we want to hide several controls at the same time, we can put all of them in the panel and just set panel.Visible = False 3. Label1 - This Label controlLabel controlLabel controlLabel control has the static text "Enter your name:". 4. txtName - This Textbox controlTextbox controlTextbox controlTextbox control will be used to accept inputs from user. 5. btnProceed - This Button controlButton controlButton controlButton control will be used to submit the form, after user enters the name. 6. HyperLink1 - This is a HyperLink controlHyperLink controlHyperLink controlHyperLink control used to give hyperlinks to other pages. In our case, we use this link to navigate to our next page. Compile and Run the project

Page 74: ASP.NET

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. In this chapter, you will add code to the event handlers in the Login Page and add the real functionality to it. Let us add some code in the Login page and give it some real action. What is this page supposed to do ? User can enter their name into the textbox and submit. Whatever name user enters, it will be saved to session variable and application variable. Once the name is added to the session variable, the textbox and button will be hidden and a welcome message will be displayed. Add code to event handlers Switch to design mode and double click on the button. This will add a button_click event handler in the code behind file, as shown below: Private Sub btnProceed_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnProceed.Click End Sub Let us add the following code to the above event handler. Dim name As String = txtName.Text ' store the name into the session variable. Session("Name") = name AddNameToApplicationVariable(name) ' We have selected a name. Display the name and disable the 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

Page 75: ASP.NET

panel. Here is the code for the function AddNameToApplicationVariable() Private Sub AddNameToApplicationVariable(ByVal name As String) Dim nameList As ArrayList nameList = Application("Names") If nameList Is Nothing Then ' There is no names added to application variable yet. ' Let us create a new ArrayList nameList = New ArrayList() End If ' Add the name to the arry list nameList.Add(name) ' Add ArrayList object itself to the application variable. Application("Names") = nameList End Sub 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 = New ArrayList() 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(): Private Sub DisplayCurrentUser() Dim name As String = Session("Name") If name = String.Empty Then ' There is no name in the session variable. This means ' there is no name selected yet.

Page 76: ASP.NET

Return End If ' The name is already in the session. ' This user has already entered the name. ' So, let us disable to the panel so that all controls within ' the panel will be invisible. pnlName.Visible = False ' Display the name in the message label. lblMessage.Text = "Welcome " & name End Sub 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. Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _ MyBase.Load ' When we load the page, first check if the user name is already in session. DisplayCurrentUser() End Sub Launch the page After you finish the above code, compile and launch the page. You will see the page in action. After you enter a name and submit, you will see the welcome message. Read the code several times and clearly understand how it works. This chapter explains how you can extend your UserTracker project to display the list of currently online users. In the previous chapter, you created a login page and added some functionality to it. When a user enter his name and submit the page, the name is stored in session variable and also an ArrayList. The arraylist is stored into an Application variable. In this chapter, we will create another page, which will retrieve all names from the arraylist in the Application variable and display it. Create a new page Let us create a new page called "ShowNames.aspx". Right click on the project name in the solution explorer and create this new page. Copy and paste the following code in to the aspx page, in the HTML mode:

Page 77: ASP.NET

<B>All Users</B> <hr> <asp:Label id="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: Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim names As ArrayList = Application("Names") If names Is Nothing OrElse names.Count = 0 Then lblNames.Text = "No names are added to application variable." Else Dim name As String ' Append each of the names from the arraylist to the label. For Each name In names lblNames.Text = lblNames.Text & name & " " Next End If End Sub Let us analyze the above code. The statement Dim names As ArrayList = 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 control's 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. Run the application

Page 78: ASP.NET

Compile and run the application. You can notice couple of things: 1. After you enter your name in the login page, the text box will be hidden and a welcome message will be displayed. 2. The name you entered is added to the application variable. 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). Download sample application If you get confused or can't get the above mentioned sample project properly on your own, you may download the sample project from this site. Extract the zip file contents into your UserTracker folder, which is already converted into a virtual directory. When you extract files, make sure you do not create another folder within your UserTracker folder. Open the project file from the extracted files using VS.NET. Simply compile and run the project. If VS.NET prompt you to set a default page, set the Login.aspx as the default page. We like to know if you are able to fully understand what we explained in this chapter and previous chapters regarding this small sample ASP.NET project. Please post your feedbacks, questions and comments using the Feedback link below. We will do our best to make things more clear and clarify your doubts.

Page 79: ASP.NET

In this chapter, we will extend the UserTracker project and learn how to use Cookies to remember settings. What we learned so far ? In the previous chapters, we learnt how to use session variables and application variables in a web application. Both session variables and application variables are stored in the server memory and will lose the data when web server is reset. 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:Label id="lblLastVisit" style="Z-INDEX: 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.

Page 80: ASP.NET

Add code to save and retrieve cookie information We have to do 2 things here: 1. Store the date/time and login name into cookie, when user press the "proceed" button. 2. Retrieve values in cookie and display in label control every time the page is loaded. Go to the event handler btnProceed_Click. Add the following code to the end of the event handler. ' Save current name and time to cookie 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. Dim nameCookie As HttpCookie = Request.Cookies("Name") Dim timeCookie As HttpCookie = Request.Cookies("SaveTime") If nameCookie Is Nothing Then lblLastVisit.Text = "This is first time you are visiting this stie from this computer." Else

Page 81: ASP.NET

lblLastVisit.Text = "You last visited this site as '<B><U>" & nameCookie.Value & "</U></B>' on '<B><U>" & timeCookie.Value & "</U></B>'." End If 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. In this chapter, you will learn what are validator controls and how to use them in the UserTracker project. Validate name in Login page Validator controls are used to validate user inputs from a webpage. For example, when you have a webpage which requires that user must enter some data, you can use a "Require Field Validator" control to ensure that the form will not be sumitted until some valid data is entered. In our UserTracker project, user is required to enter a name in the login page. But you have noticed that even if you do not enter a name and press the "proceed" button, it will not complain. It will still process the login and save the values in to Cooikes etc. This is not good. We want to make sure that the Login page will not be processed until they enter a name. Open the Login.aspx page in design mode. Drag and drop a control called "RequiredFieldValidator" from the toolbox to the form. Place this validator control near the textbox. You must set the following properties for the validator control. 1. ErrorMessage - This is the error message you want to be displayed to the user, if no value is entered in the textbox. Set it to "Please enter your name." 2. ControlToValidate - This property says which control will be validated using this validator. In our case, we want to validate our textbox. So, select the textbox name for this property. Thats all you have to do use the validator control. Compile and run the project. You can see that you will get an error message if you submit the form without entering a name. Client side validation Note that when you use Validator controls, the validation happens in the client side. Since this is happening in the client browser, a smart user can by pass this validation and still submit empty names to the server by various tricks.

Page 82: ASP.NET

So, in case of secure applications, it is a good idea to do server side validations, in addition to the validator controls. In case of our sample, all you have to do is, check if the name string is empty or not just before it is processed. If it is empty, then do not process the login. Just give an error message to the user (This is not illustrated in the sample project). This chapter talks about various validator controls provided with ASP.NET ASP.NET comes with several handy validator controls. You used the RequiredFieldValidator in the previous chapter. You will learn more about various validator controls in this chapter. This tutorial will teach you Database concepts and ADO.NET in a very simple and easy-to-understand manner with many code snippets and samples. Database 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!!) 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). DataAccess Providers in .NET ADO.NET comes with few providers providers, including: OleDb

Page 83: ASP.NET

SqlClient 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 hold and manipulate data. This chapter introduces various classes provided by ADO.NET to perform various database operations. Classes for communicating with database The Connection, Command, DataReader,Connection, Command, DataReader,Connection, Command, DataReader,Connection, Command, DataReader, and DataAdapterDataAdapterDataAdapterDataAdapter objects are the core elements of the ADO.NET provider model.

ObjectObjectObjectObject DescriptionDescriptionDescriptionDescription SqlClient SqlClient SqlClient SqlClient ObjectsObjectsObjectsObjects

OleDb ObjectsOleDb ObjectsOleDb ObjectsOleDb Objects

ConnectionConnectionConnectionConnection Establishes a connection to a specific data source.

SqlConnection OleDbConnection

CommandCommandCommandCommand Executes a command against a data source.

SqlCommand OleDbCommand

DataReaderDataReaderDataReaderDataReader Reads a forward-only, read-only stream of data from a data source.

SqlDataReader OleDbDataReader

DataAdapterDataAdapterDataAdapterDataAdapter Populates a DataSetDataSetDataSetDataSet and resolves updates with the data source.

SqlDataAdapter OleDbDataAdapter

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

Page 84: ASP.NET

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. Classes for holding and manipulating data The following are the main classes used to hold data in Ado.NET: DataSet DataTable DataRow A DataSet is an in-memory representation of the database. DataSet contains one or more DataTables (and more like Views etc...) A DataTable represents a database table DataTable contains one or more DataRows (and more...) A DataRow represents a record in a database table. DataRow is a collection of all fields in a record. We can use the DataAdapter or DataReader to populate data in DataSet. Once we populate data from database, we can loop through all Tables in the DataSet and through each record in each Table. On the first look, this may look bit confusing, but once you understand the concept and get familiar with the Ado.NET classes, you will appreciate the power and flexibility of Ado.NET. This article talks about the basic database operations using the ADO.NET classes. The basic database operations performed on a database table are: 1. Create (insert record) 2. Read (select data) 3. Update (update existing data) 4. Delete (delete records) The above operations are sometimes called "CRUD" (CCCCreate, RRRRead, UUUUpdate, DDDDelete) 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.

Page 85: ASP.NET

This page will be using an SQL Query which will look something like this: insert into EMPLOYEES (id, name, age, salary, designation) values (1, 'john', 30, 25000, 'Vice President') 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 * from EMPLOYEES 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. 3. Screen to update the details of an existing employee. Typically, you can view the list of employees from the screen in step 2 and select a user to edit and update the details. This Update page will allow you to enter all details of the employee. This page will be using an SQL Query similar to this: update EMPLOYEES set name = 'john', age = 30, salary = 25000, designation = 'Vice President' where id = 1 4. The Delete screen will allow you delete any existing employee. The sql query will be something like this: delete EMPLOYEES where id = 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". This article explains 2 types of database operations - that return data from database and that does not return any results. In an earlier chapter, you learned the basic CRUD operations. Let us further classify them in to 2 categories: 1. Operation that returns data from database

Page 86: ASP.NET

2. Operations that do not return any data, but just changes data in the database. A SelectSelectSelectSelect operation belong to the first category. It selects some data and returns results. The UpdatedUpdatedUpdatedUpdated, Insrt, Delete, Insrt, Delete, Insrt, Delete, Insrt, Delete operations do not return any results. Instead, they change the data in the database. Let us learn the various classes available in the ADO.NET class library to perform the above operations. All the classes used in the samples below are part of the namespace System.Data.OleDb. So, make sure you import the namespace in the top of the class as shown below: #include System.Data.OleDb The following code snippet shows an example of category 2 (returns no data) string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\Employee.mdb"; OleDbConnection myConnection = new OleDbConnection( connectionString ); myConnection.Open(); string query = "insert into EMPLOYEE_TABLE (EmployeeID, Name, Address) VALUES (101, 'John', '3960 CliffValley Way')"; OleDbCommand myCommand = new OleDbCommand(); 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 doesn't exists or if it is not able to open a connection for some other reason,

Page 87: ASP.NET

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: string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\Employee.mdb"; OleDbConnection myConnection = new OleDbConnection( connectionString ); string query = "select * from EMPLOYEE_TABLE"; OleDbDataAdapter myAdapter = new OleDbDataAdapter( query, myConnection ); DataSet employeeData = new DataSet(); myAdapter.Fill ( employeeData ); Here we are creating a OleDbConnection object and it to the OleDbDataAdapter object. Also, we pass the 'select ...' query to the OleDbDataAdapter. Next, we call the '.Fill()' method of the 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: string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\Employee.mdb";

Page 88: ASP.NET

OleDbConnection myConnection = new OleDbConnection( connectionString ); string query = "select * from EMPLOYEE_TABLE"; OleDbDataAdapter myAdapter = new OleDbDataAdapter( query, myConnection ); DataSet employeeData = new DataSet(); myAdapter.Fill( employeeData ); // Repeat for each table in the DataSet collection. foreach ( DataTable table in employeeData.Tables ) { // Repeat for each row in the table. foreach ( DataRow row in table.Rows ) { Response.Write( "Employee Number : " + 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


Recommended