Web Site Project Type
Web Site Project Type
Net
File-system Use a file-system Web site project when you want to create Web pages on your local computer or on a
Web site shared drive and you do not have IIS installed. You can create a file-system Web site and later create
project an IIS virtual directory that points to the folder containing your pages.
Advantages
• The site can be accessed only from the local computer, which reduces security
vulnerabilities.
• You do not need to have IIS installed on your computer.
• You do not need administrative rights to create or debug a local file-system Web site.
• If the computer is configured to allow remote desktop connections, multiple users can create
and debug local file-system Web sites at the same time.
Disadvantages
• You cannot test a file-system Web site with IIS features, such as HTTP-based authentication,
application pooling, and ISAPI filters. There are also some differences between the way the
Visual Studio Development Server works and the way IIS works. Therefore, you should test
your project by running it with IIS before deploying it to production.
Local IIS Use when you want to create Web pages on your local computer and you have IIS installed.
Web site Advantages
project • The site can be accessed from other computers if IIS is configured to make it available to
them.
• You can test with IIS features, such as HTTP-based authentication, application pooling, and
ISAPI filters. You should test with IIS before you deploy to production anyway due to
differences between the Visual Web Development Server and IIS. Therefore, testing in
Visual Studio more accurately represents how the site will behave in production (except that
security is likely to be different in test and production.)
Disadvantages
• You must have administrative rights to create or debug an IIS Web site project.
• Only one user on the computer can debug an IIS Web site project at one time.
• By default, remote access is enabled for a local IIS Web site project.
Remote IIS Use when you want to create a Web site by using IIS running on a remote computer. The remote
Web site computer must be configured with FrontPage Server Extensions.
project Advantages
• You can test the Web site project on the server where it will be deployed.
• Multiple developers can work with the same remote Web site project at the same time.
Disadvantages
• Configuration for debugging a remote Web site project is complex.
• Only one developer can debug the remote Web site project at one time. All other requests are
suspended while the developer is stepping through code.
FTP Web Use an FTP Web site project when your site already exists on a remote computer that has been
site project configured as an FTP server. (For example, your Internet service provider (ISP) has provided space on
a server.)
Advantages
• You can test the FTP Web site project on the server where it will be deployed.
Disadvantages
• You do not have local copies of the FTP Web site project files unless you copy them
yourself.
• You cannot create an FTP Web site project — you can only open one.
• Typical file editing operations, such as opening and saving files, might be slow.
• Because you are editing a live site, it is easier than with other Web project types to introduce
an error that users can see.
Q.5) Advantage of Single page model and Code behind page mode.
Ans: Advantages of Single-File Pages
As a rule, the single-file model is suitable for pages in which the code consists primarily of event handlers for the
controls on the page.
Advantages of the single-file page model include the following:
• In pages where there is not very much code, the convenience of keeping the code and markup in the same
file can outweigh other advantages of the code-behind model. For example, it can be easier to study a
single-file page because you can see the code and the markup in one place.
• Pages written using the single-file model are slightly easier to deploy or to send to another programmer
because there is only one file.
• Because there is no dependency between files, a single-file page is easier to rename if you are using tools
other than Visual Studio. (If you use Visual Studio to rename a file, Visual Studio automatically renames
both files.)
• Managing files in a source code control system is slightly easier, because the page is self-contained in a
single file.
Advantages of Code-Behind Pages
Code-behind pages offer advantages that make them suitable for Web applications with significant code or in which
multiple developers are creating a Web site.
Advantages of the code-behind model include the following:
• Code-behind pages offer a clean separation of the markup (user interface) and code. It is practical to have a
designer working on the markup while a programmer writes code.
• Code is not exposed to page designers or others who are working only with the page markup.
• Code can be reused for multiple pages.
Chap- 2: Objects and Controls
Q.1) ASP.NET Life Cycle.
Ans: The ASP.NET life cycle could be divided into two groups:
• Application Life Cycle
• Page Life Cycle
ASP.NET Application Life Cycle
The application life cycle has the following stages:
• User makes a request for accessing application resource, a page. Browser sends this request to the web
server.
• A unified pipeline receives the first request and the following events take place:
o An object of the class ApplicationManager is created.
o An object of the class HostingEnvironment is created to provide information regarding the
resources.
o Top level items in the application are compiled.
• Response objects are created. The application objects such as HttpContext, HttpRequest and HttpResponse
are created and initialized.
• An instance of the HttpApplication object is created and assigned to the request.
• The request is processed by the HttpApplication class. Different events are raised by this class for
processing the request.
ASP.NET Page Life Cycle
When a page is requested, it is loaded into the server memory, processed, and sent to the browser. Then it is
unloaded from the memory. At each of these steps, methods and events are available, which could be overridden
according to the need of the application. In other words, you can write your own code to override the default code.
The Page class creates a hierarchical tree of all the controls on the page. All the components on the page, except the
directives, are part of this control tree. You can see the control tree by adding trace= "true" to the page directive.
We will cover page directives and tracing under 'directives' and 'event handling'.
The page life cycle phases are:
• Initialization
• Instantiation of the controls on the page
• Restoration and maintenance of the state
• Execution of the event handler codes
• Page rendering
Understanding the page cycle helps in writing codes for making some specific thing happen at any stage of the
page life cycle. It also helps in writing custom controls and initializing them at right time, populate their properties
with view-state data and run control behavior code.
Following are the different stages of an ASP.NET page:
• Page request - When ASP.NET gets a page request, it decides whether to parse and compile the page, or
there would be a cached version of the page; accordingly the response is sent.
• Starting of page life cycle - At this stage, the Request and Response objects are set. If the request is an old
request or post back, the IsPostBack property of the page is set to true. The UICulture property of the page
is also set.
• Page initialization - At this stage, the controls on the page are assigned unique ID by setting the UniqueID
property and the themes are applied. For a new request, postback data is loaded and the control properties
are restored to the view-state values.
• Page load - At this stage, control properties are set using the view state and control state values.
• Validation - Validate method of the validation control is called and on its successful execution, the
IsValid property of the page is set to true.
• Postback event handling - If the request is a postback (old request), the related event handler is invoked.
• Page rendering - At this stage, view state for the page and all controls are saved. The page calls the
Render method for each control and the output of rendering is written to the OutputStream class of the
Response property of page.
• Unload - The rendered page is sent to the client and page properties, such as Response and Request, are
unloaded and all cleanup done.
ASP.NET Page Life Cycle Events
At each stage of the page life cycle, the page raises some events, which could be coded. An event handler is
basically a function or subroutine, bound to the event, using declarative attributes such as Onclick or handle.
Following are the page life cycle events:
• PreInit - PreInit is the first event in page life cycle. It checks the IsPostBack property and determines
whether the page is a postback. It sets the themes and master pages, creates dynamic controls, and gets
and sets profile property values. This event can be handled by overloading the OnPreInit method or
creating a Page_PreInit handler.
• Init - Init event initializes the control property and the control tree is built. This event can be handled by
overloading the OnInit method or creating a Page_Init handler.
• InitComplete - InitComplete event allows tracking of view state. All the controls turn on view-state
tracking.
• LoadViewState - LoadViewState event allows loading view state information into the controls.
• LoadPostData - During this phase, the contents of all the input fields are defined with the <form> tag are
processed.
• PreLoad - PreLoad occurs before the post back data is loaded in the controls. This event can be handled
by overloading the OnPreLoad method or creating a Page_PreLoad handler.
• Load - The Load event is raised for the page first and then recursively for all child controls. The controls
in the control tree are created. This event can be handled by overloading the OnLoad method or creating a
Page_Load handler.
• LoadComplete - The loading process is completed, control event handlers are run, and page validation
takes place. This event can be handled by overloading the OnLoadComplete method or creating a
Page_LoadComplete handler
• PreRender - The PreRender event occurs just before the output is rendered. By handling this event, pages
and controls can perform any updates before the output is rendered.
• PreRenderComplete - As the PreRender event is recursively fired for all child controls, this event ensures
the completion of the pre-rendering phase.
• SaveStateComplete - State of control on the page is saved. Personalization, control state and view state
information is saved. The HTML markup is generated. This stage can be handled by overriding the
Render method or creating a Page_Render handler.
• UnLoad - The UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all
controls recursively and lastly for the page itself. Final cleanup is done and all resources and references,
such as database connections, are freed. This event can be handled by modifying the OnUnLoad method
or creating a Page_UnLoad handler.
Text The text displayed on the button. This is for button and link button controls only.
ImageUrl For image button control only. The image to be displayed for the button.
AlternateText For image button control only. The text to be displayed if the browser cannot display the
image.
CausesValidation Determines whether page validation occurs when a user clicks the button. The default is
true.
CommandName A string value that is passed to the command event when a user clicks the button.
CommandArgument A string value that is passed to the command event when a user clicks the button.
PostBackUrl The URL of the page that is requested when the user clicks the button.
Text Boxes and Labels
Text box controls are typically used to accept input from the user. A text box control can accept one or more lines
of text depending upon the settings of the TextMode attribute.
Label controls provide an easy way to display text which can be changed from one execution of a page to the next.
If you want to display text that does not change, you use the literal text.
Basic syntax of text control:
<asp:TextBox ID="txtstate" runat="server" ></asp:TextBox>
Common Properties of the Text Box and Labels:
Property Description
TextMode Specifies the type of text box. SingleLine creates a standard text box, MultiLIne creates a
text box that accepts more than one line of text and the Password causes the characters that
are entered to be masked. The default is SingleLine.
MaxLength The maximum number of characters that can be entered into the text box.
Wrap It determines whether or not text wraps automatically for multi-line text box; default is
true.
ReadOnly Determines whether the user can change the text in the box; default is false, i.e., the user
can not change the text.
Columns The width of the text box in characters. The actual width is determined based on the font
that is used for the text entry.
Rows The height of a multi-line text box in lines. The default value is 0, means a single line text
box.
The mostly used attribute for a label control is 'Text', which implies the text displayed on the label.
Check Boxes and Radio Buttons
A check box displays a single option that the user can either check or uncheck and radio buttons present a group of
options from which the user can select just one option.
To create a group of radio buttons, you specify the same name for the GroupName attribute of each radio button in
the group. If more than one group is required in a single form, then specify a different group name for each group.
If you want check box or radio button to be selected when the form is initially displayed, set its Checked attribute
to true. If the Checked attribute is set to true for multiple radio buttons in a group, then only the last one is
considered as true.
Basic syntax of check box:
<asp:CheckBox ID= "chkoption" runat= "Server">
</asp:CheckBox>
Basic syntax of radio button:
<asp:RadioButton ID= "rdboption" runat= "Server">
</asp: RadioButton>
Common properties of check boxes and radio buttons:
Property Description
Text The text displayed next to the check box or radio button.
Items The collection of ListItem objects that represents the items in the control. This property
returns an object of type ListItemCollection.
Rows Specifies the number of items displayed in the box. If actual list contains more rows than
displayed then a scroll bar is added.
SelectedIndex The index of the currently selected item. If more than one item is selected, then the index
of the first selected item. If no item is selected, the value of this property is -1.
SelectedValue The value of the currently selected item. If more than one item is selected, then the value of
the first selected item. If no item is selected, the value of this property is an empty string
("").
SelectionMode Indicates whether a list box allows single selections or multiple selections.
Common properties of each list item objects:
Property Description
Item(integer) A ListItem object that represents the item at the specified index.
Add(string) Adds a new item at the end of the collection and assigns the string parameter to the
Text property of the item.
Insert(integer, string) Inserts an item at the specified index location in the collection, and assigns string
parameter to the text property of the item.
Insert(integer, ListItem) Inserts the item at the specified index location in the collection.
Remove(string) Removes the item with the text value same as the string.
RepeatLayout This attribute specifies whether the table tags or the normal html flow to use while
formatting the list when it is rendered. The default is Table.
RepeatDirection It specifies the direction in which the controls to be repeated. The values available are
Horizontal and Vertical. Default is Vertical.
RepeatColumns It specifies the number of columns to use when repeating the controls; default is 0.
Bulleted lists and Numbered lists
The bulleted list control creates bulleted lists or numbered lists. These controls contain a collection of ListItem
objects that could be referred to through the Items property of the control.
Basic syntax of a bulleted list:
<asp:BulletedList ID="BulletedList1" runat="server">
</asp:BulletedList>
Common properties of the bulleted list:
Property Description
BulletStyle This property specifies the style and looks of the bullets, or numbers.
RepeatDirection It specifies the direction in which the controls to be repeated. The values available are
Horizontal and Vertical. Default is Vertical.
RepeatColumns It specifies the number of columns to use when repeating the controls; default is 0.
HyperLink Control
The HyperLink control is like the HTML <a> element.
Basic syntax for a hyperlink control:
<asp:HyperLink ID="HyperLink1" runat="server">
HyperLink
</asp:HyperLink>
It has the following important properties:
Property Description
HtmlHead <head>element
AdRotator AdCreated
BulletedList Click
Button Click
Calender SelectionChanged
CheckBox CheckedChanged
CheckBoxList SelectedIndexChanged
DataGrid SelectedIndexChanged
DataList SelectedIndexChanged
DropDownList SelectedIndexChanged
HyperLink Click
ImageButton Click
ImageMap Click
LinkButton Click
ListBox SelectedIndexChanged
Menu MenuItemClick
RadioButton CheckedChanged
RadioButtonList SelectedIndexChanged
</asp:RequiredFieldValidator>
RangeValidator Control
The RangeValidator control verifies that the input value falls within a predetermined range.
It has three specific properties:
Properties Description
</asp:RangeValidator>
CompareValidator Control
The CompareValidator control compares a value in one control with a fixed value or a value in another control.
It has the following specific properties:
Properties Description
</asp:CompareValidator>
RegularExpressionValidator
The RegularExpressionValidator allows validating the input text by matching against a pattern of a regular
expression. The regular expression is set in the ValidationExpression property.
The syntax of the control is as given:
<asp:RegularExpressionValidator ID="string" runat="server" ErrorMessage="string"
ValidationExpression="string" ValidationGroup="string">
</asp:RegularExpressionValidator>
CustomValidator
The CustomValidator control allows writing application specific custom validation routines for both the client side
and the server side validation.
The client side validation is accomplished through the ClientValidationFunction property. The client side
validation routine should be written in a scripting language, such as JavaScript or VBScript, which the browser can
understand.
The server side validation routine must be called from the control's ServerValidate event handler. The server side
validation routine should be written in any .Net language, like C# or VB.Net.
The basic syntax for the control is as given:
<asp:CustomValidator ID="CustomValidator1" runat="server"
ClientValidationFunction=.cvf_func. ErrorMessage="CustomValidator">
</asp:CustomValidator>
ValidationSummary
The ValidationSummary control does not perform any validation but shows a summary of all errors in the page.
The summary displays the values of the ErrorMessage property of all validation controls that failed validation.
The following two mutually inclusive properties list out the error message:
• ShowSummary : shows the error messages in specified format.
• ShowMessageBox : shows the error messages in a separate window.
The syntax for the control is as given:
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
DisplayMode = "BulletList" ShowSummary = "true" HeaderText="Errors:" />
NavigateUrl The link that will be followed when the user clicks the ad.
AlternateText The text that will be displayed instead of the picture if it cannot be displayed.
<Ad>
<ImageUrl>rose2.jpg</ImageUrl>
<NavigateUrl>http://www.babybouquets.com.au</NavigateUrl>
<AlternateText>Order roses and flowers</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>
</Advertisements>
We have studied the page life cycle and how a page contains various controls. The page itself is instantiated as a
control object. All web forms are basically instances of the ASP.NET Page class. The page class has the following
extremely useful properties that correspond to intrinsic objects:
• Session
• Application
• Cache
• Request
• Response
• Server
• User
• Trace
We will discuss each of these objects in due time. In this tutorial we will explore the Server object, the Request
object, and the Response object.
Server Object
The Server object in Asp.NET is an instance of the System.Web.HttpServerUtility class. The HttpServerUtility
class provides numerous properties and methods to perform various jobs.
Properties and Methods of the Server object
The methods and properties of the HttpServerUtility class are exposed through the intrinsic Server object provided
by ASP.NET.
The following table provides a list of the properties:
Property Description
CreateObject(String) Creates an instance of the COM object identified by its ProgID (Programmatic ID).
Equals(Object) Determines whether the specified Object is equal to the current Object.
Execute(String) Executes the handler for the specified virtual path in the context of the current
request.
Transfer(String) For the current request, terminates execution of the current page and starts execution
of a new page by using the specified URL path of the page.
Request Object
The request object is an instance of the System.Web.HttpRequest class. It represents the values and properties of
the HTTP request that makes the page loading into the browser.
The information presented by this object is wrapped by the higher level abstractions (the web control model).
However, this object helps in checking some information such as the client browser and cookies.
Properties and Methods of the Request Object
The following table provides some noteworthy properties of the Request object:
Property Description
ApplicationPath Gets the ASP.NET application's virtual application root path on the server.
Browser Gets or sets information about the requesting client's browser capabilities.
ContentType Gets or sets the MIME content type of the incoming request.
Files Gets the collection of files uploaded by the client, in multipart MIME format.
Buffer Gets or sets a value indicating whether to buffer the output and send it after the
complete response is finished processing.
BufferOutput Gets or sets a value indicating whether to buffer the output and send it after the
complete page is finished processing.
Charset Gets or sets the HTTP character set of the output stream.
ContentEncoding Gets or sets the HTTP character set of the output stream.
ContentType Gets or sets the HTTP MIME type of the output stream.
End Sends all currently buffered output to the client, stops execution of the page, and
raises the EndRequest event.
Equals(Object) Determines whether the specified object is equal to the current object.
Redirect(String) Redirects a request to a new URL and specifies the new URL.
Redirect(String, Boolean) Redirects a client to a new URL. Specifies the new URL and whether execution of
the current page should terminate.
Item(name) The value of the view state item with the specified name. This is the default
property of the StateBag class.
Add(name, value) Adds an item to the view state collection and existing item is updated.
Equals(Object) Determines whether the specified object is equal to the current object.
Finalize Allows it to free resources and perform other cleanup operations.
GetEnumerator Returns an enumerator that iterates over all the key/value pairs of the
StateItem objects stored in the StateBag object.
IsItemDirty Checks a StateItem object stored in the StateBag object to evaluate whether
it has been modified.
SetDirty Sets the state of the StateBag object as well as the Dirty property of each of
the StateItem objects contained by it.
SetItemDirty Sets the Dirty property for the specified StateItem object in the StateBag
object.
Control State
Control state cannot be modified, accessed directly, or disabled.
Session State
When a user connects to an ASP.NET website, a new session object is created. When session state is turned on, a
new session state object is created for each new request. This session state object becomes part of the context and it
is available through the page.
Session state is generally used for storing application data such as inventory, supplier list, customer record, or
shopping cart. It can also keep information about the user and his preferences, and keep the track of pending
operations.
Sessions are identified and tracked with a 120-bit SessionID, which is passed from client to server and back as
cookie or a modified URL. The SessionID is globally unique and random.
The session state object is created from the HttpSessionState class, which defines a collection of session state
items.
The HttpSessionState class has the following properties:
Properties Description
Item(name) The value of the session state item with the specified name. This is the
default property of the HttpSessionState class.
TimeOut Gets and sets the amount of time, in minutes, allowed between requests
before the session-state provider terminates the session.
The HttpSessionState class has the following methods:
Methods Description
Remove(name) Removes the specified item from the session state collection.
RemoveAll Removes all keys and values from the session-state collection.
void RetrieveSessionInfo()
{
String fromuser = Session["fromuser"];
Label1.Text = fromuser;
}
The above code stores only strings in the Session dictionary object, however, it can store all the primitive data
types and arrays composed of primitive data types, as well as the DataSet, DataTable, HashTable, and Image
objects, as well as any user-defined class that inherits from the ISerializable object.
ASP.NET Configuration system is used to describe the properties and behaviors of various aspects of ASP.NET
applications. Configuration files help you to manage the many settings related to your website. Each file is an XML
file (with the extension .config) that contains a set of configuration elements. Configuration information is stored in
XML-based text files.