You are on page 1of 39

ASP.NET is a web framework designed and developed by Microsoft.

It is used to develop websites, web


applications and web services. It provides fantastic integration of HTML, CSS and JavaScript. It was first
released in January 2002. It is built on the Common Language Runtime (CLR) and allows programmers to
write code using any supported .NET language.

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.

ASP.NET Web Forms Model

ASP.NET web forms extend the event-driven model of interaction to the web applications. The browser
submits a web form to the web server and the server returns a full markup page or HTML page in
response.

All client side user activities are forwarded to the server for stateful processing. The server processes the
output of the client actions and triggers the reactions.

Now, HTTP is a stateless protocol. ASP.NET framework helps in storing the information regarding the
state of the application, which consists of:

● Page state

● Session state

The page state is the state of the client, i.e., the content of various input fields in the web form. The
session state is the collective information obtained from various pages the user visited and worked with,
i.e., the overall session state. To clear the concept, let us take an example of a shopping cart.

User adds items to a shopping cart. Items are selected from a page, say the items page, and the total
collected items and price are shown on a different page, say the cart page. Only HTTP cannot keep track
of all the information coming from various pages. ASP.NET session state and server side infrastructure
keeps track of the information collected globally over a session.

The ASP.NET runtime carries the page state to and from the server across page requests while
generating ASP.NET runtime codes, and incorporates the state of the server side components in hidden
fields.

This way, the server becomes aware of the overall application state and operates in a two-tiered
connected way

The ASP.NET Component Model

The ASP.NET component model provides various building blocks of ASP.NET pages. Basically it is an
object model, which describes:

●Server side counterparts of almost all HTML elements or tags, such as <form> and <input>.

●Server controls, which help in developing complex user-interface. For example, the Calendar control or
the Gridview control.

ASP.NET is a technology, which works on the .Net framework that contains all web-related
functionalities. The .Net framework is made of an object-oriented hierarchy. An ASP.NET web
application is made of pages. When a user requests an ASP.NET page, the IIS delegates the processing of
the page to the ASP.NET runtime system.

The ASP.NET runtime transforms the .aspx page into an instance of a class, which inherits from the base
class page of the .Net framework. Therefore, each ASP.NET page is an object and all its components i.e.,
the server-side controls are also objects.

ASP.NET provides an abstraction layer on top of HTTP on which the web applications are built. It
provides high-level entities such as classes and components within an object-oriented paradigm.

Visual Studio is an integrated development environment for writing, compiling, and debugging the code.
It provides a complete set of development tools for building ASP.NET web applications, web services,
desktop applications, and mobile applications.

When you start a new web site, ASP.NET provides the starting folders and files for the site, including two
files for the first web form of the site.

The file named Default.aspx contains the HTML and asp code that defines the form, and the file named
Default.aspx.cs (for C# coding) or the file named Default.aspx.vb (for VB coding) contains the code in the
language you have chosen and this code is responsible for the actions performed on a form.

The primary window in the Visual Studio IDE is the Web Forms Designer window. Other supporting
windows are the Toolbox, the Solution Explorer, and the Properties window. You use the designer to
design a web form, to add code to the control on the form so that the form works according to your
need, you use the code editor.

Working with Views and Windows

You can work with windows in the following ways:


● To change the Web Forms Designer from one view to another, click on the Design or source
button.

● To close a window, click on the close button on the upper right corner and to redisplay, select it
from the View menu.

● To hide a window, click on its Auto Hide button. The window then changes into a tab. To display
again, click the Auto Hide button again.

● To change the size of a window, just drag it.

Adding Folders and Files to your Website

When a new web form is created, Visual Studio automatically generates the starting HTML for the form
and displays it in Source view of the web forms designer. The Solution Explorer is used to add any other
files, folders or any existing item on the web site.

●To add a standard folder, right-click on the project or folder under which you are going to add the
folder in the Solution Explorer and choose New Folder.

●To add an ASP.NET folder, right-click on the project in the Solution Explorer and select the folder from
the list.

●To add an existing item to the site, right-click on the project or folder under which you are going to add
the item in the Solution Explorer and select from the dialog box.

Projects and Solutions

A typical ASP.NET application consists of many items: the web content files (.aspx), source files (.cs files),
assemblies (.dll and .exe files), data source files (.mdb files), references, icons, user controls and
miscellaneous other files and folders.

Solutions may contain one or more projects. A project contains content files, source files, and other files
like data sources and image files. Generally, the contents of a project are compiled into an assembly as
an executable file (.exe) or a dynamic link library (.dll) file.

Typically a project contains the following content files:

● Page file (.aspx)

● User control (.ascx)

● Web service (.asmx)

● Master page (.master)

● Site map (.sitemap)

● Website configuration file (.config)

ASP.NET Page Lifecycle


In ASP.NET, a web page has execution lifecycle that includes various phases. These phases include
initialization, instantiation, restoring and maintaining state etc. it is required to understand the page
lifecycle so that we can put custom code at any stage to perform our business logic.

Page Lifecycle stages

The following table contains the lifecycle stages of ASP.NET web page.
ASP.NET Web Forms Features

ASP.NET is full of features and provides an awesome platform to create and develop web application.
Here, we are discussing these features of Web Forms.
Server Controls,Master Pages,Working with data,Membership,Client Script and Client
Frameworks,Routing,State Management,Security,Performance,Error Handling

Server Controls

Web Forms provides rich set of server controls. These controls are objects that run when the page is
requested and render markup to the browser. Some Web server controls are similar to familiar HTML
elements, such as buttons and text boxes. It also provides controls that we can use to connect to data
sources and display data.

Master Pages

It allows us to create a consistent layout for the pages in our application. This page defines the look and
feel and standard behavior that we want for all of the pages in our application. When users request the
content pages, they merge with the master page to produce output that combines the layout of the
master page with the content from the content page.

Working with Data

In an ASP.NET Web Forms application, we use data-bound controls to automate the presentation or
input of data in web page UI elements such as tables and text boxes and drop-down lists.

Membership

Project's Account folder contains the files that implement the various parts of membership: registering,
logging in, changing a password, and authorizing access. Additionally, ASP.NET Web Forms supports
OAuth and OpenID. These authentication enhancements allow users to log into your site using existing
credentials, from such accounts as Facebook, Twitter and Google.

Client Script and Client Frameworks

We can enhance the server-based features of ASP.NET by including client-script functionality in ASP.NET
Web Form pages. We can use client script to provide a richer, more responsive user interface to the
users. We can also use client script to make asynchronous calls to the Web server while a page is
running in the browser.

Routing

We can configure URL routing of our application. A request URL is simply the URL a user enters into their
browser to find a page on our web site. We use routing to define URLs that are semantically meaningful
to users and that can help with search-engine optimization (SEO).

State Management

ASP.NET Web Forms includes several options that help you preserve data on both a per-page basis and
an application-wide basis.

Security
Developing a secure application is most important aspect of software development process. ASP.NET
Web Forms allow us to add extensibility points and configuration options that enable us to customize
various security behaviors in the application.

Performance

Web Forms provides good performance and allows us to modify performance related to page and server
control processing, state management, data access, application configuration and loading, and efficient
coding practices.

Debugging and Error Handling

We can diagnose problems that occur in our Web Forms application. Debugging and error handling are
well supported within ASP.NET Web Forms so that our applications compile and run effectively.

An ASP.NET page is also a server side file saved with the .aspx extension. It is modular in nature and can
be divided into the following core sections:

Page Directives

The page directives set up the environment for the page to run. The @Page directive defines page-
specific attributes used by ASP.NET page parser and compiler. Page directives specify how the page
should be processed, and which assumptions need to be taken about the page.

It allows importing namespaces, loading assemblies, and registering new controls with custom tag
names and namespace prefixes.

Code Section

The code section provides the handlers for the page and control events along with other functions
required. We mentioned that, ASP.NET follows an object model. Now, these objects raise events when
some events take place on the user interface, like a user clicks a button or moves the cursor. The kind of
response these events need to reciprocate is coded in the event handler functions. The event handlers
are nothing but functions bound to the controls.

The code section or the code behind file provides all these event handler routines, and other functions
used by the developer. The page code could be precompiled and deployed in the form of a binary
assembly.

Page Layout

The page layout provides the interface of the page. It contains the server controls, text, inline JavaScript,
and HTML tags.

The following code snippet provides a sample ASP.NET page explaining Page directives, code section and
page layout written in VB.net:

<% @Page Language=" VB.net " %>

<!-- code section -->

<script runat="server">
private void convertoupper(object sender, EventArgs e){

string str = mytext.Value;

changed_text.InnerHtml = str.ToUpper();

</script>

<html>

<head>

<title> Change to Upper Case </title>

</head>

<body>

<h3> Conversion to Upper Case </h3>

<form runat="server">

<input runat="server" id="mytext" type="text" />

<input runat="server" id="button1" type="submit" value="Enter..."


OnServerClick="convertoupper"/>

<hr />

<h3> Results: </h3>

<span runat="server" id="changed_text" />

</form>

</body>

</html>

Using Visual Studio IDE

The content file is automatically developed. All you need to add is the Button1_Click routine, which is as
follows:

protected void Button1_Click(object sender, EventArgs e)

string buf = TextBox1.Text;

changed_text.InnerHtml = buf.ToUpper();

}
The content file code is as given:

<%@ Page Language="vb.net" AutoEventWireup="true" CodeBehind="Default.aspx.vb"

Inherits="firstexample._Default" %>

<!DOCTYPE html PUBLIC "-//SDC//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>

Untitled Page

</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:TextBox ID="TextBox1" runat="server" style="width:224px">

</asp:TextBox>

<br />

<br />

<asp:Button ID="Button1" runat="server" Text="Enter..." style="width:85px"


onclick="Button1_Click" />

<hr />

<h3> Results: </h3>

<span runat="server" id="changed_text" />

</div>

</form>

</body>

</html>

Controls
Controls are small building blocks of the graphical user interface, which include text boxes, buttons,
check boxes, list boxes, labels, and numerous other tools. Using these tools, the users can enter data,
make selections and indicate their preferences.

Controls are also used for structural jobs, like validation, data access, security, creating master pages,
and data manipulation. ASP.NET uses five types of web controls, which are:

Server controls

HTML controls

ASP.NET Server controls

ASP.NET Ajax Server controls

User controls and custom controls

ASP.NET server controls are the primary controls used in ASP.NET. These controls can be grouped into
the following categories:

●Validation controls - These are used to validate user input and they work by running client-side script.

● Data source controls - These controls provides data binding to different data sources.

● Data view controls - These are various lists and tables, which can bind to data from data sources for
displaying.

● Personalization controls - These are used for personalization of a page according to the user
preferences, based on user information.

● Login and security controls - These controls provide user authentication.

● Master pages - These controls provide consistent layout and interface throughout the application.

● Navigation controls - These controls help in navigation. For example, menus, tree view etc.

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.

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.

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


width: 103px;

.auto-style3 {

width: 165px;

.auto-style4{

width: 143px;

</style></head>

<body>

<form id="form1" runat="server">

<table style="width: 76%;">

<tr>

<td class="auto-style1">

<asp:Label ID="Label1" runat="server" Text="Label">EmployeeName</asp:Label>


</td>

<td class="auto-style4">

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

</td>

<td class="auto-style3"> </td></tr>

<tr>

<td class="auto-style1">

<asp:Label ID="Label2" runat="server" Text="Label">Password</asp:Label>

</td>

<td class="auto-style4">

<asp:TextBox ID="TextBox2" runat="server" TextMode="Password"> </asp:TextBox>

</td>

<td class="auto-style3"> </td> </tr>

<tr>

<td class="auto-style1">

<asp:Label ID="Label3" runat="server" Text="Label">Address</asp:Label> </td>

<td class="auto-style4">

<asp:TextBox ID="TextBox3" runat="server" Height="54px" TextMode="MultiLine"


Width="211px"></asp:TextBox> </td>

<td class="auto-style3"> </td> </tr>

<tr>

<td class="auto-style1">

<asp:Button ID="Button1" runat="server" Text="Button" /></td>

<td class="auto-style4">

<asp:LinkButton ID="LinkButton1" runat="server">Submit</asp:LinkButton></td>

<td class="auto-style3">

<asp:ImageButton ID="ImageButton1" runat="server" AlternateText="This is Image Button"


ImageUrl="~/logo.gif" BorderColor="Blue" BorderStyle="Solid" BorderWidth="2px"
PostBackUrl="~/Default2.aspx" />

</td></tr>
</table> </form>

</body></html>

Example

<!DOCTYPE html>

<html>

<body>

@if (IsPost)

Dim companyname = Request("CompanyName")

Dim contactname = Request("ContactName")

@<p>You entered: <br><br>

Company Name: @companyname <br>

Contact Name: @contactname </p>

else

@<form method="post" action="">


Company Name:<br>

<input type="text" name="CompanyName" value=""><br>

Contact Name:<br>

<input type="text" name="ContactName" value=""><br><br>

<input type="submit" value="Submit" class="submit">

</form>

end if

Application State In ASP. NET Using VB.NET

Application state is a global storage mechanism that is stored on the server and shared for all users.
Does not expire. Thus, application state is useful for storing information that needs to be maintained
between server round trips and between requests for pages. Unlike session state, which is specific to a
single user session, application state applies to all users and sessions. Application state is based on the
System.Web.HttpApplicationState class, which is provided in all web pages through the built-in
Application object. Application object will not have any default expiration period.

Advantages of application state:

● Application object memory released when we removed.

● Multiuser can able to access application variable.

● To avoid deadlock or conflict we should use Lock and Unlock when we use write or update in the
application object.
● Other application can't access this application values.

Disadvantages of application state:

● Application variable will exists until exit our application.

● If we do not have Lock() and Unlock, deadlock will occur.

● Its global variable so anyone can access within this application.

Example: We can count how many times a given page has been requested by various clients. Using an
application state.

Now drag and drop a label control on the form. Now double click on the form and add the following
code.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Application.Lock()

Dim count As Integer = 0

If Application("Pagecount") IsNot Nothing Then

count = CInt(Application("Pagecount"))

End If

count += 1

Application("Pagecount") = count

Application.UnLock()

Label1.Text = "Total Page Visited: " & count.ToString() & "Times"

End Sub

Themes and Skins

When you build a Web application, it usually has a similar look and feel across all its pages. Not too
many applications are designed with each page dramatically different from the next. Generally, for your
applications you use similar fonts, colors, and server control styles across all the pages.

You can apply these common styles individually to each and every server control or object on each page,
or you can use a new capability provided by ASP.NET 2.0 to centrally specify these styles. All pages or
parts of pages in the application can then access them.

Applying a theme to a single ASP.NET page

In order to see how to use one of these themes, create a basic page, which includes text, a text box, a
button, and a calendar. This is shown in Listing 7-1.

Listing 7-1: An ASP.NET page that does not use themes


<%@Page Language="VB" %>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>INETA</title></head>

<body>

<form id="form1" runat="server">

<h1>International .NET Association (INETA)</h1><br />

<asp:Textbox ID="TextBox1" Runat="server" /><br />

<br />

<asp:Calendar ID="Calendar1" Runat="server" /><br />

<asp:Button ID="Button1" Runat="server" Text="Button" /></form></body></html>

Master Pages

One common characteristic of user-friendly websites is that they have a consistent, site-wide page
layout and navigation scheme. ASP.NET 2.0 introduces two new features that greatly simplify
implementing both a site-wide page layout and navigation scheme: master pages and site navigation.
Master pages allow for developers to create a site-wide template with designated editable regions. This
template can then be applied to ASP.NET pages in the site. Such ASP.NET pages need only provide
content for the master page's specified editable regions all other markup in the master page is identical
across all ASP.NET pages that use the master page. This model allows developers to define and
centralize a site-wide page layout, thereby making it easier to create a consistent look and feel across all
pages that can easily be updated.

To create a master page, right-click on the project name in the Solution Explorer and choose Add New
Item. Then select the Master Page type from the list of templates and name it Site.master
Add a New Master Page to the Website Define the site-wide page layout here in the master page. You
can use the Design view and add whatever Layout or Web controls you need, or you can manually add
the markup by hand in the Source view. In my master page I use cascading style sheets for positioning
and styles with the CSS settings defined in the external file Style.css. While you cannot tell from the
markup shown below, the CSS rules are defined such that the navigation <div>'s content is absolutely
positioned so that it appears on the left and has a fixed width of 200 pixels.

Site.master

<%@ Master Language="VB" AutoEventWireup="true"

CodeFile="Site.master.vb" Inherits="Site" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Working with Data Tutorials</title>

<link href="Styles.css" rel="stylesheet" type="text/css" /></head>

<body><div id="wrapper">

<form id="form1" runat="server">

<div id="header">

<span class="title">Working with Data Tutorials</span>

<span class="breadcrumb">

TODO: Breadcrumb will go here...</span></div>


<div id="content">

<asp:contentplaceholder id="MainContent"

runat="server">

<!-- Page-specific content will go here... -->

</asp:contentplaceholder> </div>

<div id="navigation">

TODO: Menu will go here...

</div></form></div></body></html>

A master page defines both the static page layout and the regions that can be edited by the ASP.NET
pages that use the master page. These content editable regions are indicated by the ContentPlaceHolder
control, which can be seen within the content <div>. Our master page has a single ContentPlaceHolder
(MainContent), but master page's may have multiple ContentPlaceHolders.

With the markup entered above, switching to the Design view shows the master page's layout. Any
ASP.NET pages that use this master page will have this uniform layout, with the ability to specify the
markup for the MainContent region.

Binding to Databases using Controls

Data binding plays a central role in ASP.NET Web Forms model. As you’ve seen in previous chapters,
ASP.NET Web Forms are based on the notion of server controls. Server controls are objects placed on
the page and programmed to offer a result. You can write specific code to intercept events and develop
your pages using an event-driven methodology.

Data binding is essential in the ASP.NET ecosystem because web pages are often a gateway to display
data coming from different sources, like a database, web service, or object. Data binding offers a simple
way to implement the action to bind the data to the form and display the visual results easily.

Data binding itself hasn’t changed in the last few versions of ASP.NET, but server controls and data
access strategies have. As you learned in chapters 2 and 3, the past few years have seen the adoption of
strongly typed collections versus the initial DataSet approach. New trends, like service-oriented
applications and cloud computing, have amplified the notion of data and changed the way we think
about storage. Plus, AJAX techniques are considered standard today. The initial concept of data binding
has evolved because the environment has also evolved.

Data binding uses a special syntax:

<%# %>

The <%#, which instructs ASP.NET to evaluate the expression. The difference between a data binding
tags and a regular code insertion tags <% and %> becomes apparent when the expression is evaluated.
Expressions within the data binding tags are evaluated only when the DataBind method in the Page
objects or Web control is called.

Data Bind Control can display data in connected and disconnected model.

Following are data bind controls in ASP.NET:

● Repeater Control

● DataGrid Control

● DataList Control

● GridView Control

● DetailsView

● FormView

● DropDownList

● ListBox

● RadioButtonList

● CheckBoxList

● BulletList

Creating a Site Navigation Hierarchy

Websites always need to display navigation data to guide users through a site.

its features include;

Sitemaps – These ‘maps' are used to describe how your site looks like or in other words, the structure of
your site. As your site grows, you can modify the sitemaps and add or remove pages. This is helpful since
you won’t need to modify hyperlinks for all your WebPages.

ASP.NET Controls – The controls come in handy whenever you want to display navigation menus for
your site.

Site Navigation
Using site navigation, you describe the structure of your site as a hierarchy. You start by defining the
hierarchy of your website in an XML file. You can choose to use the SiteMapPath, TreeView or Dynamic
Menu control to display a navigation path (also called a breadcrumb or eyebrow). The breadcrumb
shows the current page and also displays links as a path that leads back to the homepage.

Rules For Creating A Sitemap File

The XML file should have a <sitemap> tag surrounding the content.

The <sitemap> tag should only have one child node (<siteMapNode>) in the homepage section.Each
node (<siteMapNode>) can have several child nodes or web pages.Each node should have attributes
defining the web page title and the URL.

For example, a SiteMapPath may look something like the following;

Home > Services > Training

As for the TreeView control, it would display a tree-like structure which shows links to different pages on
your site. It uses nodes which can be expanded or collapsed when clicked.

An example of its code is;

<asp:SiteMapDataSource id="nav1" runat="server" />

<form runat="server">

<asp:TreeView runat="server" DataSourceId="nav1" />

</form>

The <asp:SiteMapDataSource> connects to the Web.sitemap file.

Finally, the Dynamic Menu control shows an expandable menu that users can use to get to different
areas in your site. Just, like the TreeView control it uses nodes, but in this case, when the cursor hovers
over the menu item, the nodes are expanded. An example of a dynamic menu code is;

<asp:SiteMapDataSource id="nav1" runat="server" />

<form runat="server">

<asp:Menu runat="server" DataSourceId="nav1" />

</form>

The <asp:SiteMapDataSource> connects to the Web.sitemap file.

Navigation controls:

ASP.NET 2.0 has three new Navigation controls.

● SiteMapPath

● Menu

● TreeView
Navigation controls are given below:

SiteMapPath:

Use of this control is very simple. You can add this control to your page then view your page in browser.
The SiteMapPath control displays the navigation path of the current page. The path acts as clickable
links to previous pages.

The SiteMapPath control uses the web.sitemap file by default.

Code of SiteMapPath:

<asp:SiteMapPath ID="SiteMapPath1" runat="server"></asp:SiteMapPath>

SiteMapPath representation:

Example: In this Example you will see the source code of the SiteMapPath with some properties.

<html >

<head runat="server">

<title>SiteMapPath</title></head><body>

<form id="form1" runat="server"><div>

<asp:SiteMapPath ID="SiteMapPath1" runat="server" Font-Names="Verdana" Font-Size="0.8em"


PathSeparator=" : " BackColor="#C0FFFF" BorderColor="Aqua" BorderStyle="Inset" Height="40px"
Width="400px">

<PathSeparatorStyle Font-Bold="True" ForeColor="#990000" />

<CurrentNodeStyle ForeColor="#333333" />

<NodeStyle Font-Bold="True" ForeColor="#990000" />

<RootNodeStyle Font-Bold="True" ForeColor="#FF8000" />

</asp:SiteMapPath></div> </form></body></html>

Menu Control

It was the very difficult task to maintain the menu of a large website and time consuming. It is used to
display the Menus. You can use it as easy as other Navigation controls. Menu can be stored in a file to
make it easier to maintain. This file is normally called web.sitemap, and is stored in the root directory of
the web.

Example: In the following example you will see how the Menu controls create.

Step 1: Open the new website.

Step 2: Open ASP.NET Website.


Step 3: Drop the Menu control on the web form from the toolbox.

Step 4: Now right click on the Menu control and select edit menu item after that we edit menu items.

Step 5: Now right click on Menu control and select edit template then we add item template as static
and dynamic item template as follows:

Step 6: Write the code on menu itemClick().

Step 7: At last Debug the code.

Source code of the Menu Control:

<%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Untitled Page</title></head>

<body>

<form id="form1" runat="server">

<div>

<asp:Menu ID="Menu1" runat="server">

<DynamicItemTemplateAudio songs<br />Video songs<br />

</DynamicItemTemplate>

<StaticItemTemplate>Songs<br /></StaticItemTemplate>

<Items>

<asp:MenuItem Text="Songs" Value="Songs">

<asp:MenuItem Text="New Item" Value="New Item"> </asp:MenuItem>

</asp:MenuItem> </Items> </asp:Menu></form></body></html>

Output of the above source code is as follows:

Now we click on songs then we get following output.

div>
<asp:TreeView ID="TreeView1" runat="server" BackColor="#FFFF80"
BorderColor="DarkCyan"BorderStyle="Outset" ImageSet="BulletedList4" ShowExpandCollapse="False"
Width="192px">

<ParentNodeStyle Font-Bold="False" />

<HoverNodeStyle Font-Underline="True" ForeColor="#5555DD" />

<SelectedNodeStyle Font-Underline="True" ForeColor="#5555DD"


HorizontalPadding="0px"VerticalPadding="0px" />

<Nodes>

<asp:TreeNode Text="Employee" Value="Employee">

<asp:TreeNode Text="Emp_Name" Value="Emp_Name">

<asp:TreeNode Text="First Name" Value="First Name"> </asp:TreeNode>

<asp:TreeNode Text="Last Name" Value="Last Name"> </asp:TreeNode>

</asp:TreeNode>

<asp:TreeNode Text="Emp_Address" Value="Emp_Address">

<asp:TreeNode Text="Local" Value="Local"></asp:TreeNode>

<asp:TreeNode Text="Permanent" Value="Permanent">


</asp:TreeNode></asp:TreeNode>

<asp:TreeNode Text="Emp_Contact no" Value="Emp_Contact no">

<asp:TreeNode Text="Home" Value="Home"></asp:TreeNode>

<asp:TreeNode Text="Office" Value="Office"></asp:TreeNode>

</asp:TreeNode></asp:TreeNode></Nodes>

<NodeStyle Font-Names="Tahoma" Font-Size="10pt" ForeColor="Black“


HorizontalPadding="5px"NodeSpacing="0px" VerticalPadding="0px" /></asp:TreeView></div>

ASP.NET 2.0 provides built in controls to manage Membership in Web Applications. All these controls
use ASP.NET providers that are loaded via web.config file. Membership provider and Role provider allow
a complete system to maintain users information, authenticate and authorize the users. This article
demonstrates how to use and configure the default Member ship and Role provider.

Implementing the Membership and Role Provider

Initially by using the Visual Studio 2005/2008/2010, create an ASP.NET website/web application. If you
are using Visual Studio 2010, login and registration pages are available by default in the application.
Create Registration page and then drag the Create User Wizard control from the Login controls section
of the Toolbox. Now to store the user information, we need to create the database in the SQL Server.
Follow the steps given below to use built in user store schema for maintaining the user information.
Go to Visual Studio, Visual Studio tools and then open the Visual Studio Command Prompt.

Use the aspnet_regsql.exe command to run the ASP.NET SQL Server Setup Wizard.

Check the option “Configure SQL Server for application services”.

Select the Server Instance and the database name for the application, if the database name is not
provided, default aspnetdb database is created.

Click the confirm settings and finish button to create the database store.
Preparing to build the security system for use in application, we need to configure the membership
provider in web.config file. The following settings for Forms Authentication, Membership and Role
provider are applied in the web.config file.

Forms Authentication Settings

The authentication mode under system.web tag is set to “Forms” and the elements included in are
loginUrl, defaultUrl, timeout, cookieless and protection which specifies the login page URL, default page
URL, cookie expiration time and protection level respectively. The settings in web.config file would look
similar to the code shown below:

XML Code

<authentication mode="Forms">

<forms cookieless="UseCookies" defaultUrl="HomePage.aspx"

loginUrl="UnAuthorized.aspx" protection="All" timeout="30">

</forms>

</authentication>

Membership Provider Settings

Some of the important elements to be considered in the Membership provider are name – name of the
provider, type – namespace of the provider, connectionStringName – name of the connectionstring and
the most important password format. The password format is available in three formats, Hashed,
Encrypted and Clear. Hashed format provides one way of storing password in encrypted format which
cannot be brought back to original state, whereas Encrypted format provides both to encrypt and
decrypt the password.

XML Code

<membership defaultProvider="Demo_MemberShipProvider">

providers>
<add name="Demo_MemberShipProvider"

type="System.Web.Security.SqlMembershipProvider"

connectionStringName="cnn"

enablePasswordRetrieval="false"

enablePasswordReset="true"

requiresQuestionAndAnswer="true"

applicationName="/"

requiresUniqueEmail="false"

passwordFormat="Hashed"

maxInvalidPasswordAttempts="5"

minRequiredPasswordLength="5"

minRequiredNonalphanumericCharacters="0"

passwordAttemptWindow="10" passwordStrengthRegularExpression="">

</providers>

</membership>

Role Provider Settings

The similar way is to specify the settings for default Provider under system.web tag of the web.config file
as shown below. The settings are simple and self explanatory.

XML Code

<roleManager enabled="true" cacheRolesInCookie="true"

cookieName="TBHROLES" defaultProvider="Demo_RoleProvider">

<providers>

<add connectionStringName="dld_connectionstring"

applicationName="/" name="Demo_RoleProvider"

type="System.Web.Security.SqlRoleProvider, System.Web,

Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>

</providers>

</roleManager>
In the login.aspx and Registration.aspx pages, we need to use the providers to complete the
membership system for the application

Registration page for the users can be easily created by using the available create user wizard and the
following event handlers:

Vb.net Code

protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)

MembershipCreateStatus p = MembershipCreateStatus.Success;

Membership.CreateUser(CreateUserWizard1.UserName,

CreateUserWizard1.Password, CreateUserWizard1.Email,

CreateUserWizard1.Question, CreateUserWizard1.Answer, true, out p);

protected void CreateUserWizard1_ContinueButtonClick(object sender, EventArgs e)

Response.Redirect("login.aspx");

Authenticate the Users


The users can be authenticated by using the
login_Authenticate event of the Login control. The code to authenticate users goes here:

Vb.net Code

protected void Login1_Authenticate(object sender,AuthenticateEventArgs e)

if (Membership.ValidateUser(Login1.UserName, Login1.Password) == true)

Login1.Visible = true;

Session["user"] = User.Identity.Name;

FormsAuthentication.RedirectFromLoginPage(Login1.UserName, true);

else

Response.Write("Invalid Login");

} }

Login Controls

The ASP.NET login controls provide a robust login solution for ASP.NET Web applications without
requiring programming. By default, login controls integrate with ASP.NET membership and forms
authentication to help automate user authentication for a Web site. It provides you with a ready-to-use
user interface that queries the user name and password from the user and offers a Log In button for
login. It validate user credentials against the membership API and encapsulating the basic form
authentication functionality like redirecting back to the original requested page in a restricted area of
you application after the successful login.

The Login control displays a user interface for user authentication. The Login control contains text boxes
for the user name and password and a check box that allows users to indicate whether they want the
server to store their identity using ASP.NET membership and automatically be authenticated the next
time they visit the site.

The Login control has properties for customized display, for customized messages, and for links to other
pages where users can change their password or recover a forgotten password. The Login control can be
used as a standalone control on a main or home page, or you can use it on a dedicated login page. If you
use the Login control with ASP.NET membership, you do not need to write code to perform
authentication. However, if you want to create your own authentication logic, you can handle the Login
control's Authenticate event and add custom authentication code

Note - Login controls might not function correctly if the Method of the ASP.NET Web page is changed
from POST (the default) to GET.

● Start Microsoft Visual Studio 2008

● Create a new ASP.NET Website using Visual Basic, Like this:

Securing Applications

Security is an important aspect of any application that spans physical, technological, and policy decisions
and requires a high degree of planning and domain knowledge.

Authentication, authorization, user accounts, and roles are four terms that will be used very often within
the context of web security. In a client-server model, such as the Internet, there are many scenarios in
which the server needs to identify the client making the request. Authentication is the process of
ascertaining the client's identity. A client who has been successfully identified is said to be
authenticated. An unidentified client is said to be unauthenticated or anonymous.

 
Secure authentication systems involve at least one of the following three facets: something you know,
something you have, or something you are. Most web applications rely on something the client knows,
such as a password or a PIN. The information used to identify a user - her username and password, for
example - are referred to as credentials.

In addition to identifying clients, a server may need to limit what resources or functionalities are
accessible depending on the client making the request. Authorization is the process of determining
whether a particular user has the authority to access a specific resource or functionality.

Implementing security after the fact has a steep cost associated with it. Fixing software defects after the
application goes into production might cost up to 15 times more than during development. Lax security
also has some other indirect costs, such as damaging a company’s reputation and losing customers.

While securing an ASP.NET web application can be complex, it needs to be done on a continuous basis.
The .NET framework, and ASP.NET in particular, offers great features to make it easier to properly
secure your web application.

Authentication

Although ASP.NET supports several authentication methods, form authentication is the most commonly
used by web applications. Unfortunately, this approach is not a particularly secure approach as it sends
user’s credentials to the server in clear text. Depending on requirements, you might want to consider
using SSL throughout the site or at least on the login page.

But since SSL might be impractical for many commercial web applications, one new & unique approach
that you can consider is using Silverlight. Silverlight can be embedded on any sensitive page and provide
encryption of any submitted data.

A web application’s authentication can be further enhanced with the following:

- Password Policy

Enforce a password policy including strong passwords, password expiration, and possibly locking user
accounts after a few unsuccessful login attempts.

- Guessing Credentials – Brute Force Attacks

In addition to the above, you might want to introduce a random delay of a few seconds upon
unsuccessful user login. This would make brute force attacks impractical to execute (use Thread.Sleep
for this scenario.)

- Password Hashing

If you manage your authentication store, make sure to hash all user passwords.

Caching For Performance


Caching is a technique of storing frequently used data/information in memory, so that, when the same
data/information is needed next time, it could be directly retrieved from the memory instead of being
generated by the application.

Caching is extremely important for performance boosting in ASP.NET, as the pages and controls are
dynamically generated here. It is especially important for data related transactions, as these are
expensive in terms of response time.

Caching places frequently used data in quickly accessed media such as the random access memory of
the computer. The ASP.NET runtime includes a key-value map of CLR objects called cache. This resides
with the application and is available via the HttpContext and System.Web.UI.Page.

In some respect, caching is similar to storing the state objects. However, the storing information in state
objects is deterministic, i.e., you can count on the data being stored there, and caching of data is
nondeterministic.

The data will not be available in the following cases:

● If its lifetime expires,

● If the application releases its memory,

● If caching does not take place for some reason.

You can access items in the cache using an indexer and may control the lifetime of objects in the cache
and set up links between the cached objects and their physical sources.

Working with XML

The Extensible Markup Language (XML) is a markup language much like HTML or SGML. This is
recommended by the World Wide Web Consortium and available as an open standard.

The System.Xml namespace in the .Net Framework contains classes for processing XML documents.
Following are some of the commonly used classes in the System.Xml namespace

Sr.No. Class & Description

1 XmlAttribute : Represents an attribute. Valid and default values for the attribute
are defined in a document type definition (DTD) or schema.

2 XmlCDataSection: Represents a CDATA section.

3 XmlCharacterData: Provides text manipulation methods that are used by several


classes.

4 XmlComment: Represents the content of an XML comment.


5 XmlConvert: Encodes and decodes XML names and provides methods for
converting between common language runtime types and XML Schema definition
language (XSD) types. When converting data types, the values returned are locale
independent.

6 XmlDeclaration: Represents the XML declaration node <?xml version='1.0'...?>.

7 XmlDictionary: Implements a dictionary used to optimize Windows Communication


Foundation (WCF)'s XML reader/writer implementations.

8 XmlDictionaryReader: An abstract class that the Windows Communication


Foundation (WCF) derives from XmlReader to do serialization and deserialization.

XmlDictionaryWriter

Represents an abstract class that Windows Communication Foundation (WCF) derives from XmlWriter
to do serialization and deserialization.

XmlDocument

Represents an XML document.

XmlDocumentFragment

Represents a lightweight object that is useful for tree insert operations.

XmlDocumentType

Represents the document type declaration.

XmlElement

Represents an element.

XmlEntity: Represents an entity declaration, such as <!ENTITY... >.

XmlEntityReference : Represents an entity reference node.

XmlException: Returns detailed information about the last exception.


XmlImplementation: Defines the context for a set of XmlDocument objects.

XmlLinkedNode: Gets the node immediately preceding or following this node.

XmlNode: Represents a single node in the XML document.

XmlNodeReader: Represents a reader that provides fast, non-cached forward only access to XML data in
an XmlNode.

XmlNotation: Represents a notation declaration, such as <!NOTATION... >.

XmlParserContext: Provides all the context information required by the XmlReader to parse an XML
fragment.

XmlProcessingInstruction: Represents a processing instruction, which XML defines to keep processor-


specific information in the text of the document.

XmlQualifiedName: Represents an XML qualified name.

XmlReader: Represents a reader that provides fast, noncached, forward-only access to XML data.

XmlResolver: Resolves external XML resources named by a Uniform Resource Identifier (URI).

XmlSecureResolver: Helps to secure another implementation of XmlResolver by wrapping the


XmlResolver object and restricting the resources that the underlying XmlResolver has access to.

XmlSignificantWhitespace: Represents white space between markup in a mixed content node or white
space within an xml:space= 'preserve' scope. This is also referred to as significant white space.

XmlText: Represents the text content of an element or attribute.

XmlTextReader: Represents a reader that provides fast, non-cached, forward-only access to XML data.

XmlTextWriter: Represents a writer that provides a fast, non-cached, forward-only way of generating
streams or files containing XML data that conforms to the W3C Extensible Markup Language (XML) 1.0
and the Namespaces in XML recommendations.

XmlUrlResolver: Resolves external XML resources named by a Uniform Resource Identifier (URI).

XmlWhitespace: Represents white space in element content.


XmlWriter: a writer that provides a fast, non-cached, forward-only means of generating streams or files
containing XML data.

Using Crystal Reports in Web Forms

Crystal Reports .NET is a very powerful report writer. It offers a very well defined object model that
provides flexibility when integrating reports into Windows and Web applications. It also comes with a
highly customizable viewer component that gives developers control on how their reports are presented
to users.

New Features in Crystal Reports .NET

Integrated into .NET IDE

Crystal Reports .NET has been completely re-written from the ground-up in C#. It is tightly integrated
into the Visual Studio .NET IDE. Developers no longer have to switch to a different application to create
and edit reports.

Crystal Reports Viewer

Crystal Reports .NET provides developers with two different report viewing components. The first can be
used for displaying reports in Windows forms. The other is a component that can be used to display
reports in a Web environment. The beauty of these viewers is in their simplicity. Viewing a report is as
simple as setting the ReportSource property of the respective viewer.

Developers can give users the ability to interact with their reports object via a programmable API.
ADO.NET Integration

ADO.NET is now the lingua-franca of data interchange in the .NET world. Crystal Reports .NET provides
the ability to use ADO.NET datasets as the data source for reports.

Expose Reports as Web Services

Reports can be exposed as Web services. This adds additional power to Web service applications.
Exposing reports as Web services enables developers to offer real-time information (in the form of a
report) as opposed to real-time data!

You might also like