ASP DOT NET

Description

ASP.NET tutorials for beginners
A huge collection of simple tutorials will guide you through various stages of web programming.

Reviews
Shared by: ARUN PRAKASH
Stats
views:
229
rating:
not rated
reviews:
0
posted:
9/11/2009
language:
English
pages:
0
ASP.NET tutorials for beginners A huge collection of simple tutorials will guide you through various stages of web programming. Chapter 1 : ASP.Net Tutorial for Beginners - What is this all about? Chapter 2 : About the Author of ASP.NET Tutorials for beginners Chapter 3 : What is a Web Server? Chapter 4 : What is a browser? Chapter 5 : Windows Applications and Web Applications Chapter 6 : Infrastructure to develop a web application (web site) Chapter 7 : Installing and configuring IIS Chapter 8 : Working with IIS and virtual directories Chapter 9 : What is a Virtual Directory and how to create it? Chapter 10 : How web applications work ? Chapter 11 : Switching from windows programming to web programming Chapter 12 : What is ASP.NET ? How is it different from VB.NET or C# ? Chapter 13 : What you should know to become an ASP.NET web developer Chapter 14 : Create your first web page Chapter 15 : Moving from HTML to ASP.NET Chapter 16 : How browsers understand ASP.NET web pages? Chapter 17 : How ASP.NET is converted to HTML? Chapter 18 : Static and Dynamic web pages Chapter 19 : Client side scripting and server side scripting Chapter 20 : Your first dynamic page Chapter 21 : Default programming language for ASP.NET Chapter 22 : Difference between ASP and ASP.NET Chapter 23 : Download Visual Web Developer 2005 Express Edition Chapter 24 : SQL Server 2005 Chapter 25 : Built-in web server for VWD Chapter 26 : Project file in ASP.NET 2.0 Chapter 27 : Your first web application using VWD Chapter 28 : Your first web application using Visual Studio Chapter 29 : Creating a new web application - behind the scenes Chapter 30 : The "Build" process Chapter 31 : ASP.NET 2.0 and Bin folder Chapter 32 : Solution Explorer Chapter 33 : Design mode and HTML mode Chapter 34 : Files created by default by VS.NET Chapter 35 : Analyze the default web page created by Visual Studio C hapter 36 : Code Behind Files Chapter 37 : Introduction to ASP.NET Web Controls Chapter 38 : Changing properties dynamically at run time Chapter 39 : TextBox and Button controls in ASP.NET Chapter 40 : ASP.NET Objects Chapter 41 : ASP.NET Request Object Chapter 42 : ASP.NET Response object Chapter 43 : Frequently used Methods and Properties of Request object Chapter 44 : Introduction to Session handling Chapter 45 : Establishing and expiring sessions Chapter 46 : The ASP.NET Session Object Chapter 47 : Purpose of Session variables Chapter 48 : How does server identify a session? Chapter 49 : Application object in ASP.NET Chapter 50 : What is Cookies in the web world Chapter 51 : Working with Cookies in ASP.NET Chapter 52 : Configuration File for .NET applications Chapter 53 : App.config for Windows applications Chapter 54 : Web.config for Web applications Chapter 55 : What is Global.asax file? Chapter 56 : Global events in ASP.NET Chapter 57 : Handling global errors in ASP.NET using Application_Error event Chapter 58 : Organize the learning projects and samples Chapter 59 : User Tracker project Chapter 60 : User Tracker: Login Page Chapter 61 : Add life to Login page Chapter 62 : Display currently online users Chapter 63 : Using Cookies to remember user settings Chapter 64 : Validate name in Login page using RequiredFieldValidator control Chapter 65 : Validator Controls in ASP.NET Chapter 66 : Database concepts Chapter 67 : Introduction to ADO.NET Chapter 68 : Core classes in ADO.NET Chapter 69 : Basic Database operations using ADO.NET Chapter 70 : Database operations - Learn more Chapter 71 : Retrieving data from database 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: - 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, 1. The protocol we are going to use to connect to the server (http) 2. 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. 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 Definitions for browser           Browser is an application, which helps us to view the Web sites and the web content. Web sites are located in some remote systems, which needs a special kind of program or an application to access them, such an application is called browser. A browser is an application which you can use to retrieve web pages from web sites and view. When you type a URL in the browser, the browser will convert it into a web request which web server can understand. Browser will send the request to web server using the HTTP protocol. When a web server returns a web page as a Response, the browser will understand the response and display the body of the response to the user in browser. In simple terms a browser can be defined as “A software application used to locate and display Web pages” You can create your own simple browser application using C++, C#, VB.NET or any other language you like. All you need to know is, how to compose a request which web server can understand, how to parse and display the response from web server and communicate with webserver using HTTP protocol. Even though the basic job of browser is just send requests to web server and receive response from the server, modern browser provide several other enhanced features including Back/Forward buttons, save viewed files to disk so that they can be viewed later, cache images so that the same images need not be downloaded again and again etc. Internet Explorer, Netspace, Mozilla are some of the popular web browsers currently available in the market. Netscape was the most popular web browser till 4-5 years back, but currently more than 90% of the internet users use "Internet Explorer" to browse the websites. Developers are often confused about the difference between Windows Applications and Web Applications. This chapter gives brief information about various types of computer applications and provides an introductions to web applications. Different types of computer applications It is very hard to divide applications into any strict categories. There is no clear definition exists to categorize computer applications. However, here is a small list of different types I can think of: 1. Embedded Systems 2. Windows applications (also called 'Desktop applications') 3. Web Applications Embedded Systems Have you ever used a digital diary (also called 'digital organiser') or a mobile phone ? Do you know when you save a name and address, how does it get saved in it? It is a small computer program 'Embedded' in that device. It is similar to any small address book computer program that you can write using your favorite visual basic or c++. The only difference is, it is written using soem special language and 'embedded' into a chip in the device inside the mobile phone or digital diary. If you find a bug in a regular computer program, you can simply write a better program, compile it and copy to your computer. But if you find a bug in your mobile phone's embedded program, you cannot copy it! The manufacturer has to embed the new program in a new chip and replace the chip in your mobile phone!! Windows Applications If you don't know what is a 'Windows Application', probably you have never seen a computer. Almost any application you see on a desktop computer is called 'Windows Application'. It is also called 'desktop applications' since they are mostly used in desktop computers. Some common examples of desktop applications are: 1. Paint Brush program 2. Calculator program 3. MSN Messenger 4. Yahoo Messenger The first three windows applications are written by some programmers sitting in Microsoft office and they give it free to all who buy Windows operating system. The Yahoo messenger is written by Yahoo programmers and they give it free to download from their web site. If your neighbour ask you to write small 'Address book' application for his personal use, you are going to write a 'windows application'. Now you must have a good idea of what is windows application. Web Applications I am sure you have seen atleast one web application! Do you know how I guessed it? It was easy to guess. This tutorial is a web application and you are currently reading this tutorial from our web site (unless you copied it to somewhere...) So, what is a web application ? A web application is also called 'web site'. A web site is a collection of web pages hosted on a special computer called 'web server'. Now you are reading this tutorial. This chapter is a page among several other pages part of our web application. The name of our web application is 'AspSpider.com'. This web site (web application) is running in our web server, which is located in a safe place in USA. You are a 'visitor' to our site and you are accessing our web application using a tool called 'Internet Explorer' (or, some other browser like Netscape etc). We don't know where you are (we have several ways to find it, which we will explain in some other chapter) So, here is some interesting points about a web application:     A web application is a collection of web pages. A web application needs a web server to run. Web server can be located anywhere and visitors need not be even in the same country of the web server. Visitors can access the web application using a tool called 'browser'. There are many browsers exists. Most widely used browser is 'Internet Explorer'. This is provided by Microsoft and it is free. Another famous free browser is 'Netscape'. 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 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. 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. 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') When you create a new ASP.NET project using Visual Studio .NET, it will automatically create a virtual directory for you. For example, if you create a new ASP.NET project using Visual Studio .NET called "ShoppingCart", it will create a new virtual directory with the name "ShoppingCart". After you create the ASP.NET project, you can see the virtual directory listed in the IIS. You can right click on the virtual directory name in IIS and select 'Properties' to view various properties of the virtual directory. One important property is "Local Path". The "Local Path" property represents the actual location of the web application. By default, when you create a new ASP.NET project, visual studio creates the project under the folder "C:\Inetpub\WWWRoot". For example, if you create a new ASP.NET project called "ShopCart", VS.NET creates a folder called "C:\Inetpub\WWWRoot\ShopCart" and all files related to the proejct will be placed inside this folder. This folder will be set as a "Virtual Folder" so that you can access the web site using the URL "http://localhost/ShopCart". If you are working on several projects, you may want to organize your projects in some specific folder instead of "C:\Inetpub\WWWRoot". What you need to do is, create a virtual folder manually before you create the project. For example, if you need to create an ASP.NET applciation called "Shopcart" under the folder "C:\MyProjects", first create the folder "C:\MyProjects\Shopcart". Now convert this folder as a virtual folder. Now you are ready to create the project using VS.NET. If the virtual folder already exists, VS.NET will NOT create a new virtual folder under the WWWRoot folder. It will use the existing virtual folder. What is "localhost" ? "localhost" represents "current machine". If you are accessing any web applications in your own machine, you can use the url http://localhost/XXXXXXX. If your web site is in another machine, you can use the IP Address of the computer instead of "localhost". For example, if the "Shopcart" web application is in a computer with the IP Address "128.32.65.21", then you can access the site from your comptuer using the url "http://128.32.65.21/Shopcart". 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. 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". 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. 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! 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. What is ASP.NET ?         ASP.NET is the name of the Microsoft technology used for web site development. ASP.NET is NOT a programming language like C# or VB.NET ASP.NET development requires a programming language like C# or VB.NET to write code. ASP stands for Active Server Pages. There are several other technologies exist for web development (Eg: PHP). ASP.NET is the technology from Microsoft and it he widely used one. ASP.NET technology comes with a rich set of components and controls that make the web development very easy. Visual Studio .NET is the editor from Microsoft which helps you develop ASP.NET web sites faster and easily. IIS is the web server from Microsoft which supports ASP.NET. To develop ASP.NET web sites, you must have IIS installed in your computer. In ASP.NET programming, a web page is developed using HTML and a .NET programming language like C#, VB.NET or J#. You can choose your favourite .NET language to develop ASP.NET pages. So, now you must be clear that ASP.NET is not a programming language and it requires a language like C# or VB.NET to develop ASP.NET web sites. 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 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 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 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 page Let us create a simple page to get started. Open notepad and copy the following content: This is my first web page



Welcome to SpiderShop !

Buy softwares and tools online at very low rates....
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. 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 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) 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 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. 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 sites. But what is happening 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 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: Welcome TONY ! If the user is NOT logged in, then our ASP.NET code will generate the following HTML: Login Did you notice that the above samples show plain html? Depending on various conditions, ASP.NET generate appropriate HTML. This is what sent to browsers. You can right click on in any web page and select View Source to see the actual HTML. Try to see the source html of this page. Browsers always see plain html (the same html you see by Right click -< View Source) . They dont care how the html is generated, what is the technology or programming language (ASP or ASP.NET or PHP) used to generate those html etc. . Even if some other company comes up with a new technology for web development, all browsers will still work as long as those technologies generate proper html. This is the fundamental concept behind web development. It is very important to understand this concept clearly before you proceed with ASP.NET programming. 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) 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. Ever wondered the what is the difference between client side code and server side code? If your answer is YES, this chapter is for you. Server side code In a previous chapter, you learned that dynamic 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 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. 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. This is my first web page



Welcome to SpiderShop !

Buy softwares and tools online at very low rates....
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: This is my first web page



Welcome to SpiderShop !

Buy softwares and tools online at very low rates....

Now the server time is : <% Response.Write (DateTime.Now.ToString) %>
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: 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. 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 ); %> 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# ASP stands for Active Server Pages. 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 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 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). 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 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. 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. f 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\\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. Create a new web site In the previous chapter you learned the first step to create an application is to create a new web site. Let us take a look at VWD and see how can you create a new web site. Go to Start Menu > Programs and select "Microsoft Visual Web Developer 2005 Express Edition". This will launch the VWD application. Go to the File menu and select "New Web Site". You will get a screen as shown below: The screen shows different options to create a web site. For time being, let us start with a ASP.NET web site. You will learn more about other types of projects later. Select "ASP.NET Web Site" from the top part of the dialog box. Now, look at the bottom left corner. It gives you the option to select the language for your ASP.NET project. You learned in an earlier chapter that ASP.NET is a technology and you need to select a programming language to develop ASP.NET projects. Select Visual C# or Visual Basic as the language. We will be using "Visual C#" for this example. So, we reccommend you also select Visual C#. The next step is selecting a location. Just above the Language option, you will see an option to select the location. Select "File System" and in the right side of it, specify the location where you want the project to be created. Let us organize all our projects in one location. have you already created a folder called "AspSpider" in your C drive? If not, create now. We will be keeping all our sample projects under C:\AspSpider. Now, in the space provided to specify the project location, type the path C:\AspSpider\MyFirstProject and press OK. You are done! VWD has created a new project for you. In this case, "MyFirstProject" is the name of your project and "C:\AspSpider\" is the location where the project will be created. Go to windows explorer and look at the folder C:\AspSpider\. You will see that VWD has created a new folder called "MyFirstProject". This is how VS.NET or VWD organize the projects. For each project (or, web site), a new folder will be automatically created. If you navigate to this folder, you will see that a set of files are automatically created for you. This is another advantage of using VWD or VS.NET compared to using notepad. Many required files will be automatically created for you by VS.NET or VWD and save lot of time for you. You will notice that there is no solution file and project file under the web site folder. You can learn more about the location of the solution file in this chapter. This chapter talks about Visual Studio .NET. If you are using Visual Web Developer Express instead of Visual Studio .NET, you may skip this chapter. Do 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. 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 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 > Project This will popup a screen as shown below, asking you to select a project type. On the leftside of the screen, you can see the section for Project Types. Here you can select the language you want to use for your asp.net application. For this sample, let us choose "Visual Basic Projects". See the section called "Templates". This section allows us to select the type of the project you want to create. There are several options like "Windows application", "Class Library", "ASP.NET Web Application". Since we want to create a web application, let us select the template "ASP.NET Web Application". The last option you have to select the is the location. If you are creating a windows application, you have to select the folder where you want the project need to be created and the name of the project. In case of a web application, we have to select the web server and the application name. The default value for the location may be something like this: http://localhost/WebApplication1 The first part represents your web server. localhost means you are creating the web site on the local web server on your own computer. The second part (WebApplication1) is the name of the web application. The VS.NET will create a new folder with this name and convert this folder to a virtual directory. Let us leave the default location (http://localhost/WebApplication1) as it is and press OK. VS.NET may take few seconds to create a new web application for you. If your IIS is not properly configured, you may get an error. If the VS.NET fails to create a web application in the above step, read how to install IIS properly. If everything is configured correctly, VS.NET will perform the following tasks: 1. Create a new folder called "WebApplication1" (or, whatever name you select) 2. Convert the folder to a virtual directory. 3. Create couple of files for you. (If you use notepad, you will have to create each of these files manually and type the content. See how much time you saved by using VS.NET) 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 didnt 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. 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.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" %> Untitled Page
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 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: Untitled Page Change it to My First Web Site 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 tags. Add a welcome message as shown below, inside your BODY tags:
Welcome to my first web page!
Note that, in ASP.NET, you must place content inside
tags, within the 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! 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. 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 options 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 these tutorials. 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 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. Solution Explorer Solution Explorer is a window within the VS.NET editor, which allows you to manage various files part of the solution (web site). This windows displays all the files part of the web site. You may select any file and view properties, rename, delete or move to other folders through the solution explorer. By default, Solution Explorer is located on the top right corner of the VS.NET editor. This windows may be minimized on the top right bar. If for some reason, you cannot view the solution explorer, go to the menu and select "View > Solution Explorer". This will launch the solution explorer window. You may click on the tab to expand the solution explorer, as shown below. The solution explorer shows the list of files associated with the project. You may double click on any file to open it in the editor. Note the icons in the top of the solution explorer. These icons allow you to do certain things related to the project. Some of the icons will be active only when an aspx page is open in the editor. The first icon in the above image allows you to view the source code (code behind file) of an aspx page. The second icon allows you to view the aspx page itself. See the 5th icon. This allows you to view all files which are in the same directory as the web project but not included in the project. Click on this to view the files in the same folder which are not included in the project. Probably you may not have any files to see. Add some files manually to the project folder and then click on this icon. It will show you the files you copied manually. You can right click on any file and include in the project or exclude from the project. Click on the same icon again to hide non-included files. 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. 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. 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 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:      AssemblyInfo.vb Global.asax Styles.css Web.config WebForm1.aspx We will learn more about each of the above files later. Now let us go to the folder 'C:\Inetpub\wwwroot\WebApplication1'. You will see the physical files created. Here you can see more files than what you see in the solution explorer.         WebApplication1.vbproj AssemblyInfo.vb Global.asax Global.asax.resx Global.asax.vb Styles.css Web.config WebForm1.aspx   WebForm1.aspx.resx WebForm1.aspx.vb WebApplication1.vbproj is the project file. This file is not visible in solution explorer. The project file is just a list of other files included in the project. When you double click on a project file in windows explorer, Visual Studio will open the file and find out the list of files included in the project. Then it displays those files in solution explorer. If you like to see the contents of the project file, open WebApplication1.vbproj in notepad. If you can understand the format of the project file, you can even edit and make changes it in notepad. Remember that you alter the content of the project file, it may get corrupt and will become useless. So, edit the project file outside VS.NET only after you become an expert! The files shown in brown font are not visible in solution explorer. Why? Those are files depending on other files. The file Global.asax.vb and Global.asax.resx are related to Global.asax. Similarly, WebForm1.aspx.resx and WebForm1.aspx.vb are related to WebForm1.aspx. VS.NET hides such related files in the solution explorer so that they are better organized. If you want to see those hidden files in VS.NET, there are couple of ways. 1. Right click on Global.asax or WebForm1.aspx in solution explorer and select 'View Code'. The .vb file 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 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. 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 Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="WebApplication1.WebForm1"%> WebForm1
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" says that this file uses the vb file "WebForm1.aspx.vb". The next element Inherits="WebApplication1.WebForm1 says this aspx page is inherited from the class WebForm1 which is part of the namespace WebAppliaction1. (You can learn more about namespaces here.) So, the above statement binds the 2 files together - WebForm1.aspx and WebForm1.aspx.vb. This is how VS.NET understands that these files are related and thus hide the .vb file in solution explorer. WebForm1.aspx.vb is known as the 'Code behind File' for WebForm1.aspx. You will learn more about the code behind files in the next chapters. WebForm1 You must be already familiar with the HTML tags , , , <body> etc. They are mandatory tags for any html and aspx files. Withotu these tags, any web page is not a valid web page. <title>WebForm1 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. You will learn more about META TAGS later. The following tag is very important for any aspx page.
The
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
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.
hello World
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. 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 and one with the extension .vb (or .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.) 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. 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. ASP.NET web controls are the controls provided by the ASP.NET team to help you develop complex web pages. 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: 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 simply freeze up. In that case, click on the menu Tools > 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.  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: 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 its properties in the coming chapters. 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? 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. 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. 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 'monday' 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: 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. 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 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. 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 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. 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) 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 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 below: Response.Write("") Response.Write("") Response.Write("") Response.Write("") Response.Write("
") Response.Write("
") Response.Write("
") Response.Write("
") Response.Write(DateTime.Now.ToString()) Response.Write("
") 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. 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. 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". 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 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: The line timeout="20" represents the timeout value in minutes. You can change this value to any value you want. If you reduce timeout to a small number, the sessions will timeout faster and your users may experience automatic logout if they take few minutes to read a page. If you increase this number to a very big number, your server will remember each session for this long duration of time, even if the user close the browser and go home! This will be an overload for the server consuming lot of memory. For heavy traffic web servers, there will be some limitaion on the total sessions it can handle. 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. 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. n most of the web sites, when a user log In in the login page, they set few variables to session. if (bLoginSuccess Session("UserId") Session("Name") = else Response.Redirect end if = true) then = txtLoginName.Text GetUserNameFromDatabase(txtLoginName.Text) ("LoginError.aspx") 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 ". 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("Login") else Response.Write ("Welcome " & Session("Name") & ") 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 be valid only until the session expires. Also, this value will not be accessible for another user/session. 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.

Related docs
ASP-Dot-Net-20-Step-by-Step
Views: 220  |  Downloads: 25
ASP Dot Net Web Forms
Views: 463  |  Downloads: 32
asp-dot-net-programmer-resume 126
Views: 5  |  Downloads: 2
Dot-Net-Interview-Questions
Views: 445  |  Downloads: 58
ASP_DOT_NET_GOLD
Views: 223  |  Downloads: 46
.NET Framework
Views: 155  |  Downloads: 37
SAMS ASP Dot Net Kick Start
Views: 4  |  Downloads: 0
ASP Dot Net Data Web Controls Kick Start
Views: 25  |  Downloads: 0
DOT NET questions
Views: 401  |  Downloads: 31
asp-dot-net-developer-resume 134
Views: 556  |  Downloads: 3
Computer Notes
Views: 22  |  Downloads: 1
premium docs
Other docs by ARUN PRAKASH
Useful Computer Commands
Views: 177  |  Downloads: 1
Excel Tips
Views: 153  |  Downloads: 3