0% found this document useful (0 votes)
49 views

Web Site Project Type

ASP.NET is a web development platform that allows building robust web applications using compiled .NET code. It uses HTTP and runs on servers like IIS. There are different types of ASP.NET projects - file system projects do not require IIS, local IIS projects test on the local server, and remote IIS projects test on a live remote server. ASP.NET pages can use either a single file model with code in the .aspx file or a code behind model that separates the code into another file.

Uploaded by

om chavan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Web Site Project Type

ASP.NET is a web development platform that allows building robust web applications using compiled .NET code. It uses HTTP and runs on servers like IIS. There are different types of ASP.NET projects - file system projects do not require IIS, local IIS projects test on the local server, and remote IIS projects test on a live remote server. ASP.NET pages can use either a single file model with code in the .aspx file or a code behind model that separates the code into another file.

Uploaded by

om chavan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Chap-1 Introduction to ASP.

Net

Q.1) What is ASP.Net?


Ans: ASP.NET is a web development platform, which provides a programming model, a comprehensive software
infrastructure and various services required to build up robust web applications for PC, as well as mobile devices.
ASP.NET works on top of the HTTP protocol, and uses the HTTP commands and policies to set a browser-to-
server bilateral communication and cooperation.
ASP.NET is a part of Microsoft .Net platform. ASP.NET applications are compiled codes, written using the
extensible and reusable components or objects present in .Net framework. These codes can use the entire hierarchy
of classes in .Net framework.
The ASP.NET application codes can be written in any of the following languages:
• C#
• Visual Basic.Net
• Jscript
• J#
ASP.NET is used to produce interactive, data-driven web applications over the internet. It consists of a large
number of controls such as text boxes, buttons, and labels for assembling, configuring, and manipulating code to
create HTML pages.

Q.2) Difference Between ASP and ASP.net


Ans: ASP is interpreted whereas, ASP.NET is compiled. This implies that since ASP uses VBScript; therefore,
when an ASP page is executed, it is interpreted. On the other hand, ASP.NET uses .NET languages, such as C# and
VB.NET, which are compiled to Microsoft Intermediate Language (MSIL).

1. ASP is interpreted, ASP.NET is compiled.


2. Classic ASP uses a technology called ADO to connect and work with databases. ASP.NET uses the ADO.NET
technology
3. ASP has Mixed HTML and coding logic where in asp.net html and coding part are separated by code behind
files.
4. ASP.NET purely object oriented whereas ASP is partially object oriented.
5. For ASP No in-built support for XML whereas in ASP.NET full XML Support for easy data exchange.

Q.3) Different Type of WebSite in Visual Web Developer.


Ans:
Web site
project Summary
type

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.4) Asp.Net web page model


Ans: An ASP.NET Web Forms page consists of two parts:
• Visual elements, which include markup, server controls, and static text.
• Programming logic for the page, which includes event handlers and other code.
ASP.NET provides two models for managing the visual elements and code — the single-file page model and the
code-behind page model. The two models function the same, and you can use the same controls and code for both
models.
This topic explains how each model functions and provides suggestions for when to choose one model or the other.
The Single-File Page Model
In the single-file page model, a Web Forms page's markup and its programming code are in the same physical .aspx
file. The programming code is in a script block that contains the attribute runat="server" to mark it as code that
ASP.NET should execute.
The following code example shows a single-file page containing a Web Forms Button server control and
a Label server control. The highlighted portion shows the Click event handler for the Button control inside
a script block.
<%@ Page Language="C#" %>
<script runat="server">
void Button1_Click(Object sender, EventArgs e)
{
Label1.Text = "Clicked at " + DateTime.Now.ToString();
}
</script>
<html>
<head>
<title>Single-File Page Model</title>
</head>
<body>
<form runat="server">
<div>
<asp:Label id="Label1"
runat="server" Text="Label">
</asp:Label>
<br />
<asp:Button id="Button1"
runat="server"
onclick="Button1_Click"
Text="Button">
</asp:Button>
</div>
</form>
</body>
</html>
The scriptblock can contain as much code as the page requires. The code can consist of event handlers for controls
on the page (as in the example), methods, properties, and any other code that you would normally use in a class file.
At run time, a single-file page is treated as a class that derives from the Page class. The page does not contain an
explicit class declaration. Instead, the compiler generates a new class that contains the controls as members. (Not all
controls are exposed as page members; some are children of other controls.) The code in the page becomes part of
the class; for example, event handlers that you create become members of the derived Page class.

The Code-Behind Page Model


The code-behind page model for Web Forms allows you to keep the markup in one file—the .aspx file—and the
programming code in another file. The name of the code file varies according to what programming language you
are using.
For example, if you are working with a page named SamplePage, the markup is in the file SamplePage.aspx and the
code is in a file named SamplePage.aspx.vb (for Visual Basic) and SamplePage.aspx.cs (for C#).
In the code-behind model, the example used in the preceding section for the single-file page would be in two parts.
The markup would be in one file (in this example, SamplePage.aspx) and would be similar to the single-file page, as
shown in the following code example.

<%@ Page Language="C#" CodeFile="SamplePage.aspx.cs"


Inherits="SamplePage" AutoEventWireup="true" %>
<html>
<head runat="server" >
<title>Code-Behind Page Model</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label id="Label1"
runat="server" Text="Label" >
</asp:Label>
<br />
<asp:Button id="Button1"
runat="server"
onclick="Button1_Click"
Text="Button" >
</asp:Button>
</div>
</form>
</body>
</html>
There are two differences in the .aspx page between the single-file and the code-behind models. In the code-behind
model, there is no script block with the runat="server" attribute. (The page can contain script blocks without
the runat="server" attribute if you want to write client script in the page.) The second difference is that
the @ Page directive in the code-behind model contains attributes that reference an external file
(SamplePage.aspx.vb or SamplePage.aspx.cs) and a class. These attributes link the .aspx page to its code.
In the example, the attribute that identifies the code-behind file is CodeFile.
The following code example shows a code-behind file that contains the same Click event handler as the example for
the single-file page.
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class SamplePage : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Clicked at " + DateTime.Now.ToString();
}
}
The code-behind file contains the complete class declarations in the default namespace. However, the class is
declared with thepartial keyword, which indicates that the class is not contained entirely in one file. Instead, the
compiler reads the .aspx page and the file it references in the @ Page directive, and assembles them into a single
class.

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.

Q.2) Working with basic Web Form Controls.


Ans: Button Controls
ASP.NET provides three types of button control:
• Button : It displays text within a rectangular area.
• Link Button : It displays text that looks like a hyperlink.
• Image Button : It displays an image.
When a user clicks a button, two events are raised: Click and Command.
Basic syntax of button control:
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Click" / >
Common properties of the button control:
Property Description

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.

Text The text content of the text box.

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.

Checked Specifies whether it is selected or not, default is false.

GroupName Name of the group the control belongs to.


List Controls
ASP.NET provides the following controls
• Drop-down list,
• List box,
• Radio button list,
• Check box list,
• Bulleted list.
These control let a user choose from one or more items from the list. List boxes and drop-down lists contain one or
more list items. These lists can be loaded either by code or by the ListItemCollection editor.
Basic syntax of list box control:
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
</asp:ListBox>
Basic syntax of drop-down list control:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
Common properties of list box and drop-down Lists:
Property Description

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

Text The text displayed for the item.

Selected Indicates whether the item is selected.

Value A string value associated with the item.


It is important to notes that:
• To work with the items in a drop-down list or list box, you use the Items property of the control. This
property returns a ListItemCollection object which contains all the items of the list.
• The SelectedIndexChanged event is raised when the user selects a different item from a drop-down list or
list box.
The ListItemCollection
The ListItemCollection object is a collection of ListItem objects. Each ListItem object represents one item in the
list. Items in a ListItemCollection are numbered from 0.
When the items into a list box are loaded using strings like: lstcolor.Items.Add("Blue"), then both the Text and
Value properties of the list item are set to the string value you specify. To set it differently you must create a list
item object and then add that item to the collection.
The ListItemCollection Editor is used to add item to a drop-down list or list box. This is used to create a static list
of items. To display the collection editor, select edit item from the smart tag menu, or select the control and then
click the ellipsis button from the Item property in the properties window.
Common properties of ListItemCollection:
Property Description

Item(integer) A ListItem object that represents the item at the specified index.

Count The number of items in the collection.


Common methods of ListItemCollection:
Methods Description

Add(string) Adds a new item at the end of the collection and assigns the string parameter to the
Text property of the item.

Add(ListItem) Adds a new item at the end of the collection.

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.

Remove(ListItem) Removes the specified item.

RemoveAt(integer) Removes the item at the specified index as the integer.

Clear Removes all the items of the collection.


FindByValue(string) Returns the item whose value is same as the string.

FindByValue(Text) Returns the item whose text is same as the string.


Radio Button list and Check Box list
A radio button list presents a list of mutually exclusive options. A check box list presents a list of independent
options. These controls contain a collection of ListItem objects that could be referred to through the Items property
of the control.
Basic syntax of radio button list:
<asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
</asp:RadioButtonList>
Basic syntax of check box list:
<asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged">
</asp:CheckBoxList>
Common properties of check box and radio button lists:
Property Description

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

ImageUrl Path of the image to be displayed by the control.

NavigateUrl Target link URL.

Text The text to be displayed as the link.

Target The window or frame which loads the linked page.


Image Control
The image control is used for displaying images on the web page, or some alternative text, if the image is not
available.
Basic syntax for an image control:
<asp:Image ID="Image1" runat="server">
It has the following important properties:
Property Description

AlternateText Alternate text to be displayed in absence of the image.

ImageAlign Alignment options for the control.

ImageUrl Path of the image to be displayed by the control.

Q.3) HTML Server Controls.


Ans:
The HTML server controls are basically the standard HTML controls enhanced to enable server side processing.
The HTML controls such as the header tags, anchor tags, and input elements are not processed by the server but are
sent to the browser for display.
They are specifically converted to a server control by adding the attribute runat="server" and adding an id attribute
to make them available for server-side processing.
For example, consider the HTML input control:
<input type="text" size="40">
It could be converted to a server control, by adding the runat and id attribute:
<input type="text" id="testtext" size="40" runat="server">
Control Name HTML tag

HtmlHead <head>element

HtmlInputButton <input type=button|submit|reset>

HtmlInputCheckbox <input type=checkbox>

HtmlInputFile <input type = file>

HtmlInputHidden <input type = hidden>

HtmlInputImage <input type = image>

HtmlInputPassword <input type = password>

HtmlInputRadioButton <input type = radio>

HtmlInputReset <input type = reset>

HtmlText <input type = text|password>

HtmlImage <img> element

HtmlLink <link> element

HtmlAnchor <a> element

HtmlButton <button> element

HtmlButton <button> element

HtmlForm <form> element

HtmlTable <table> element

HtmlTableCell <td> and <th>

HtmlTableRow <tr> element

HtmlTitle <title> element

HtmlSelect <select&t; element

HtmlGenericControl All HTML controls not listed


Q.4) Control Event in ASP.Net
Ans:
ASP.NET event handlers generally take two parameters and return void. The first parameter represents the object
raising the event and the second parameter is event argument.
The general syntax of an event is:
private void EventName (object sender, EventArgs e);
Application and Session Events
The most important application events are:
• Application_Start - It is raised when the application/website is started.
• Application_End - It is raised when the application/website is stopped.
Similarly, the most used Session events are:
• Session_Start - It is raised when a user first requests a page from the application.
• Session_End - It is raised when the session ends.
Page and Control Events
Common page and control events are:
• DataBinding - It is raised when a control binds to a data source.
• Disposed - It is raised when the page or the control is released.
• Error - It is a page event, occurs when an unhandled exception is thrown.
• Init - It is raised when the page or the control is initialized.
• Load - It is raised when the page or a control is loaded.
• PreRender - It is raised when the page or the control is to be rendered.
• Unload - It is raised when the page or control is unloaded from memory.

Control Fire Event and Default events are :


Control Default Event

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

Q.5) Validation Controls:


Ans:ASP.NET validation controls validate the user input data to ensure that useless, unauthenticated, or
contradictory data don't get stored.
ASP.NET provides the following validation controls:
• RequiredFieldValidator
• RangeValidator
• CompareValidator
• RegularExpressionValidator
• CustomValidator
• ValidationSummary
RequiredFieldValidator Control
The RequiredFieldValidator control ensures that the required field is not empty. It is generally tied to a text box to
force input into the text box.
The syntax of the control is as given:
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">

</asp:RequiredFieldValidator>
RangeValidator Control
The RangeValidator control verifies that the input value falls within a predetermined range.
It has three specific properties:
Properties Description

Type It defines the type of the data. The available values


are: Currency, Date, Double, Integer, and String.

MinimumValue It specifies the minimum value of the range.

MaximumValue It specifies the maximum value of the range.


The syntax of the control is as given:
<asp:RangeValidator ID="rvclass" runat="server" ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
MinimumValue="6" Type="Integer">

</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

Type It specifies the data type.

ControlToCompare It specifies the value of the input control to compare


with.

ValueToCompare It specifies the constant value to compare with.

Operator It specifies the comparison operator, the available


values are: Equal, NotEqual, GreaterThan,
GreaterThanEqual, LessThan, LessThanEqual, and
DataTypeCheck.
The basic syntax of the control is as follows:
<asp:CompareValidator ID="CompareValidator1" runat="server"
ErrorMessage="CompareValidator">

</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:" />

Q.6) ADRotatot Control


Ans: The AdRotator control randomly selects banner graphics from a list, which is specified in an external XML
schedule file. This external XML schedule file is called the advertisement file.
The AdRotator control allows you to specify the advertisement file and the type of window that the link should
follow in the AdvertisementFile and the Target property respectively.
The basic syntax of adding an AdRotator is as follows:
<asp:AdRotator runat = "server" AdvertisementFile = "adfile.xml" Target = "_blank" />
Before going into the details of the AdRotator control and its properties, let us look into the construction of the
advertisement file.
The advertisement file is an XML file, which contains the information about the advertisements to be displayed.
Element Description

Advertisements Encloses the advertisement file.

Ad Delineates separate ad.

ImageUrl The path of image that will be displayed.

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.

Keyword Keyword identifying a group of advertisements. This is used for filtering.

Impressions The number indicating how often an advertisement will appear.

Height Height of the image to be displayed.

Width Width of the image to be displayed


for e.g:
<Advertisements>
<Ad>
<ImageUrl>rose1.jpg</ImageUrl>
<NavigateUrl>http://www.1800flowers.com</NavigateUrl>
<AlternateText>
Order flowers, roses, gifts and more
</AlternateText>
<Impressions>20</Impressions>
<Keyword>flowers</Keyword>
</Ad>

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

Q.7) Explain Intrensic Objects:


Ans:

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

MachineName Name of server computer

ScriptTimeOut Gets and sets the request time-out value in seconds.


The following table provides a list of some important methods:
Method Description

CreateObject(String) Creates an instance of the COM object identified by its ProgID (Programmatic ID).

CreateObject(Type) Creates an instance of the COM object identified by its Type.

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.

GetLastError Returns the previous exception.

GetType Gets the Type of the current instance.

ToString Returns a String that represents the current Object.

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.

Cookies Gets a collection of cookies sent by the client.

FilePath Gets the virtual path of the current request.

Files Gets the collection of files uploaded by the client, in multipart MIME format.

Form Gets a collection of form variables.

QueryString Gets the collection of HTTP query string variables.

Url Gets information about the URL of the current request.


The following table provides a list of some important methods:
Method Description

GetType Gets the Type of the current instance.

MapPath(String) Maps the specified virtual path to a physical path.

SaveAs Saves an HTTP request to disk.

ToString Returns a String that represents the current object.


Response Object
The Response object represents the server's response to the client request. It is an instance of the
System.Web.HttpResponse class.
In ASP.NET, the response object does not play any vital role in sending HTML text to the client, because the
server-side controls have nested, object oriented methods for rendering themselves.
However, the HttpResponse object still provides some important functionalities, like the cookie feature and the
Redirect() method. The Response.Redirect() method allows transferring the user to another page, inside as well as
outside the application. It requires a round trip.
Properties and Methods of the Response Object
The following table provides some noteworthy properties of the Response object:
Property Description

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.

Cookies Gets the response cookie collection.


The following table provides a list of some important methods:
Method Description

Close Closes the socket connection to a client.

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.

Flush Sends all currently buffered output to the client.


GetType Gets the Type of the current instance.

Pics Appends a HTTP PICS-Label header to the output stream.

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.

SetCookie Updates an existing cookie in the cookie collection.

ToString Returns a String that represents the current Object.

Write(Char) Writes a character to an HTTP response output stream.

Q.8) Managing States


Ans
Hyper Text Transfer Protocol (HTTP) is a stateless protocol. When the client disconnects from the server, the
ASP.NET engine discards the page objects. This way, each web application can scale up to serve numerous
requests simultaneously without running out of server memory.
However, there needs to be some technique to store the information between requests and to retrieve it when
required. This information i.e., the current value of all the controls and variables for the current user in the current
session is called the State.
ASP.NET manages four types of states:
• View State
• Control State
• Session State
• Application State
View State
The view state is the state of the page and all its controls. It is automatically maintained across posts by the
ASP.NET framework.
When a page is sent back to the client, the changes in the properties of the page and its controls are determined, and
stored in the value of a hidden input field named _VIEWSTATE. When the page is again posted back, the
_VIEWSTATE field is sent to the server with the HTTP request.
The view state could be enabled or disabled for:
• The entire application by setting the EnableViewState property in the <pages> section of web.config file.
• A page by setting the EnableViewState attribute of the Page directive, as <%@ Page Language="C#"
EnableViewState="false" %>
• A control by setting the Control.EnableViewState property.
It is implemented using a view state object defined by the StateBag class which defines a collection of view state
items. The state bag is a data structure containing attribute value pairs, stored as strings associated with objects.
The StateBag class has the following properties:
Properties Description

Item(name) The value of the view state item with the specified name. This is the default
property of the StateBag class.

Count The number of items in the view state collection.

Keys Collection of keys for all the items in the collection.

Values Collection of values for all the items in the collection.


The StateBag class has the following methods:
Methods Description

Add(name, value) Adds an item to the view state collection and existing item is updated.

Clear Removes all the items from the collection.

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.

GetType Gets the type of the current instance.

IsItemDirty Checks a StateItem object stored in the StateBag object to evaluate whether
it has been modified.

Remove(name) Removes the specified item.

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.

ToString Returns a string representing the state bag object.


Example
The following example demonstrates the concept of storing view state. Let us keep a counter, which is incremented
each time the page is posted back by clicking a button on the page. A label control shows the value in the counter.
The markup file code is as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="statedemo._Default" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>
Untitled Page
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>View State demo</h3>
Page Counter:
<asp:Label ID="lblCounter" runat="server" />
<asp:Button ID="btnIncrement" runat="server" Text="Add Count" onclick="btnIncrement_Click" />
</div>
</form>
</body>
</html>
The code behind file for the example is shown here:
public partial class _Default : System.Web.UI.Page
{
public int counter
{
get
{
if (ViewState["pcounter"] != null)
{
return ((int)ViewState["pcounter"]);
}
else
{
return 0;
}
}
set
{
ViewState["pcounter"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
lblCounter.Text = counter.ToString();
counter++;
}
}

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

SessionID The unique session identifier.

Item(name) The value of the session state item with the specified name. This is the
default property of the HttpSessionState class.

Count The number of items in the session state collection.

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

Add(name, value) Adds an item to the session state collection.

Clear Removes all the items from session state collection.

Remove(name) Removes the specified item from the session state collection.

RemoveAll Removes all keys and values from the session-state collection.

RemoveAt Deletes an item at a specified index from the session-state collection.


The session state object is a name-value pair to store and retrieve some information from the session state object.
You could use the following code for the same:
void StoreSessionInfo()
{
String fromuser = TextBox1.Text;
Session["fromuser"] = fromuser;
}

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.

Q. Global.asax File( Global Application File)


Ans:
Global.asax is an optional file which is used to handling higher level application events such as Application_Start,
Application_End, Session_Start, Session_End etc. It is also popularly known as ASP.NET Application File. This
file resides in the root directory of an ASP.NET-based application.
Global.asax contains a Class representing your application as a whole. At run time, this file is parsed and compiled
into a dynamically generated .NET Framework class derived from the HttpApplication base class. You can deploy
this file as an assembly in the \bin directory of an ASP.NET application. The Global.asax file itself is configured so
that if a user requests the file, the request is rejected. External users cannot download or view the code written
within it.
<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
</script>

Q.) Web. Config File in ASP.Net


Ans:
Configuration file is used to manage various settings that define a website. The settings are stored in XML files that
are separate from your application code. In this way you can configure settings independently from your code.
Generally a website contains a single Web.config file stored inside the application root directory. However there can
be many configuration files that manage settings at various levels within an application.

Usage of configuration file

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.

Benefits of XML-based Configuration files


• ASP.NET Configuration system is extensible and application specific information can be stored and
retrieved easily. It is human readable.
• You need not restart the web server when the settings are changed in configuration file. ASP.NET
automatically detects the changes and applies them to the running ASP.NET application.
• You can use any standard text editor or XML parser to create and edit ASP.NET configuration files.
What Web.config file contains?
There are number of important settings that can be stored in the configuration file. Some of the most frequently used
configurations, stored conveniently inside Web.config file are:
• Database connections
• Caching settings
• Session States
• Error Handling
• Security
Configuration file looks like this
1. <configuration>
2. <connectionStrings>
3. <add name="myCon" connectionString="server=MyServer;database=puran;uid=puranmehra;pwd=my
data1223" />
4. </connectionStrings>
5. </configuration/>

Q.Overview of ADO.net Object


Ans:
ADO.NET provides a bridge between the front end controls and the back end database. The ADO.NET objects
encapsulate all the data access operations and the controls interact with these objects to display data, thus hiding the
details of movement of data.
The following figure shows the ADO.NET objects at a glance:

The DataSet Class


The dataset represents a subset of the database. It does not have a continuous connection to the database. To update
the database a reconnection is required. The DataSet contains DataTable objects and DataRelation objects.
The DataTable Class
The DataTable class represents the tables in the database.
The DataRow Class
The DataRow object represents a row in a table.
The DataAdapter Object
The DataAdapter object acts as a mediator between the DataSet object and the database. This helps the Dataset to
contain data from multiple databases or other data source.
The DataReader Object
The DataReader object is an alternative to the DataSet and DataAdapter combination. This object provides a
connection oriented access to the data records in the database. These objects are suitable for read-only access, such
as populating a list and then breaking the connection.
DbCommand and DbConnection Objects
The DbConnection object represents a connection to the data source. The connection could be shared among
different command objects.
The DbCommand object represents the command or a stored procedure sent to the database from retrieving or
manipulating data.

You might also like