Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 311

Label server Control:

Is used to display the text int the browser. Bcoz this is the server control u can
dynamically alter the text from your server side code.
Vb: Label1.text=welcome to asp.net
C#: Label1.text=welcome to asp.net;
We can also assign the hot key to the control. This causes the page to focus on a
particular server control that u declaratively assign to a specific hot-keys.
When working with the hot keys, be aware that not all the letters are available to use
with the alt keys. IE already uses Alt + F,E,V,I,O,T,A,W and H.
<asp:Label ID="Label1" runat="server" AccessKey="n
AssociatedControlID="TextBox1 Text="user <u>N</u>ame"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" > </asp:TextBox>
Set the property for the label control in the property window as below:

Text Box server control:


The control provides a textboxbox on the form that enables the end user to input text.
We can map the textbox control to three different HTML elements used in the forms.
First, it can be used as a standard HTML textbox.
Second, the textbox can allow end user to input their passwords into a forms. The is
done by changing the textmode property to password.
Third , the textbox can be used as a multitline textbox. When working with multiline
be aware of the wrap property. When set to true the text is entered into text area
wraps to the next lline if needed. When set to false, the end user can type
continuously in a single line until she presses the enter key.

Focus () method:
The focus() method enables you to dynamicallty place the end users cursor in an
appointed form element.
protected void Page_Load(object sender, EventArgs e)
{
textbox1.focus();
}

Using AutoPostBack:
Asp.NET pages work in an event-driven way. When an action on a web page triggers as
event, server-side code is initiated. One of the more common events is an end user
clicking a button on the form.
Using AutoCompleteType:
One of the great capabilities for any web form is smart autocompletion. We have seen
this when we visited a site for the first time. As we start filling information in a form, a
drop down list appears below the textbox as we type, showing you a value that yo have
typed in a previous form.

The textbox is having the AUTOCOMPLETE property, which enables you to apply the
auto-completion feature to your own forms. You have to help the textboxes on your form
to recognize the type of information that they should be looking for.

The Button server control:


Buttons are generally used to submit forms.
PROPERTY:
CauseValidation Property: if you have more than one button on urweb page and you
are working with the validation server server controls, you may not want to fire the
validation for ech button on the form. Setting the causeValidation property to False is a
way to use a button that will not fire the validation process.

CommandName property: When you have multiple Button controls on a Web page,
use the CommandName property to specify or determine the command name
associated with each Button control. You can set the CommandName property with
any string that identifies the command to perform. You can then programmatically
determine the command name of the Button control and perform the appropriate
actions.

Design the web form with three buttons and set the property commandname for
button1 as b1, button2 as b2 and button3 as b3

<asp:Button ID="Button1" runat="server" CommandName="b1"


Text="Button1" OnCommand="Button_Command" />
<asp:Button ID="Button2" runat="server" CommandName="b2"
Text="Button 2" OnCommand="Button_Command" />
<asp:Button ID="Button3" runat="server" CommandName="b3"
Text="Button 3" OnCommand="Button_Command" />

protected void Button_Command(Object sender,


System.Web.UI.WebControls.CommandEventArgs e)
{
switch (e.CommandName)
{
case ("b1"):
Response.Write("button1 clicked");
break;
case ("b2"):
Response.Write("button 2 clicked ");
break;
case ("b3"):
Response.Write("button 3 clicked ");
break;
}
}

Link button server control


Use the LinkButton control to create a
hyperlink-style button on a Web Forms
page. Specify the text to display in the
LinkButton control by setting the Text
property.

In the following example we declare one LinkButton control in an .aspx


file.
Use the LinkButton control if you want to link to another Web page
when the control is clicked.

Hyperlink server control


Creates a link on the page that users can
click to move to another page.

Place Holders
This control is intended to be used as a
place holder when u add control to a web
form at runtime.they dont insert any
HTML into a web page themselves, but u
can add controls to them with their
Controls.Add method.

public partial class panel_placeholder : System.Web.UI.Page


{
TextBox t1=new TextBox() ;
TextBox t2 = new TextBox();
protected void Button1_Click(object sender, EventArgs e)
{
t1.Text = "textbox is in placeholder";
t2.Text = "textbox is in panel";
PlaceHolder1.Controls.Add(t1);
Panel1.Controls.Add(t2);
}
}

File Upload control


This control is intended to be used to upload the files
from the client-side to the server-side.
While working with the Fileupload class one should
always remember that it does not automatically save the
files on the server-side.
To save files on the server-side you need to use
saveas() method.
Before saving files with the saveAs() method, you must
ensure that ASP.NET has write permissions on the
specified directory, otherwise the operation will be failed.

Second example

protected void Button1_Click(object sender, EventArgs e)


{
if (FileUpload1.HasFile )
try
{
FileUpload1.SaveAs ("C:\\Uploads\\" + FileUpload1.FileName);
Label1.Text ="file name :" + FileUpload1.PostedFile.FileName + "<br>"+
FileUpload1.PostedFile.ContentLength +"kb <br>"+"Content type :" +
FileUpload1.PostedFile.ContentType ;
}
catch (Exception ex)
{
Label1.Text ="error--->" + ex.Message.ToString();
}
else
{
Label1.Text ="u have not specified file" ;
}
}

Image Control
They just display an image in a web
page. To associate an image with an
IMAGE control, u just assign the image
url to the image control. U can set the
image width and height with the witdth
and height property.
Image1.imageurl=~/imagename.gif;

IMAGE BUTTON
You can use image button controls to
display images that can also handle click
events. This is particularly useful if u want
to create image maps- those clickable
images that initiate various actions
depending on where you click them.

IMAGE MAPS
ImageMap control. This control enables you to create an
image that has individual regions that users can click;
these regions are referred to as hot spots. Each of these
hot spots can be a separate hyperlink or can raise a
postback event.

The following code example shows how to respond to a user click in


an ImageMap control. The page contains an ImageMap control with
four rectangular hot spots. Each hot spot's PostBackValue property
is set to a unique value. The code in the handler checks for each
value and displays an appropriate response

Drop down list server control:

The DropDownList Web server control allows users to select one or more
items from a predefined list. It differs from the ListBox Web server control in
that the list of items remains hidden until users click the drop-down button.
In addition, the DropDownList control differs from the ListBox control in
that it does not support multi-selection mode.
To work with items programmatically, you work with the Items collection of
the DropDownList control. Items is a standard collection, and you can add
item objects to it, delete items, clear the collection, and so on.
The currently selected item is available in the DropDownList control's
SelectedItem property.

DropDownList Events
The DropDownList control raises an event
SelectedIndexChanged when users select an item. By
default, this event does not cause the page to be posted to the
server, but you can cause the control to force an immediate
post by setting the AutoPostBack property to true.

Dynamically generating a dropdownlist control from an


array
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string[] cararr = new string[4] { "ford", "indica", "maruti", "BMW" };
string[] airarr = new string[3] { "deccan", "air india", "indigo" };
string[] trainarr = new string[4] { "satapdi", "congo", "ap", "rajdhni" };
if (DropDownList1.SelectedValue == "car")
{
ListBox1.DataSource = cararr;
}
else if(DropDownList1.SelectedValue == "airplane")
{
ListBox1.DataSource = airarr;
}
else
{
ListBox1.DataSource = trainarr;
}
ListBox1.DataBind ();
}
protected void Button4_Click(object sender, EventArgs e)
{
Response.Write("<br><br>u selected<b>" + DropDownList1.SelectedValue.ToString() + ":" +
ListBox1.SelectedValue.ToString() + "</b>");
}

ListBox
The ListBox Web server control displays a
list of items from which we can make a
selection. In this example we declare one
ListBox control, and one Label control in
an .aspx file. Then we create an event
handler for the SelectedIndexChanged
event which displays some text and the
selected item, in a Label control. We can
select one or more items from the list of
items displayed.

In this example we declare one ListBox control, and one Label


control in an .aspx file. Then we create an event handler for the
SelectedIndexChanged event which displays some text and the
selected item, in a Label control.

protected void ListBox1_SelectedIndexChanged(object sender,


EventArgs e)
{
//for single selection list
Label1.Text = ListBox1.SelectedItem.Text.ToString();
}
protected void ListBox2_SelectedIndexChanged(object sender,
EventArgs e)
{
int i;
for (i = 0; i <= ListBox2.Items.Count - 1; i++)
{
if (ListBox2.Items[i].Selected)
Label2.Text += ListBox2.Items[i].Text.ToString() + " ";
}
}

Calendar server control


The Calendar control presents users with
a calendar. It also offers date-picking
functionality. After you add a Calendar
control, it displays a month of dates at a
time. In addition, it shows the week
preceding and the week following the
month. Therefore, a total of six weeks
appears at once.

To set the selected date, use the


SelectedDate property in the Properties
window. By default, the SelectedDate
property is the date on the server. Use the
VisibleDate property to determine what
month appears on the calendar. The user
can move from month to month, changing
the visible date without affecting the
current date.

Selecting a single day in the calendar


control
protected void Calendar1_SelectionChanged(object sender,
EventArgs e)
{
Response.Write("u selected:" +
Calendar1.SelectedDate.ToShortDateString());
}

Day,week or month selections


By default, the calendar control enables
you to make single day selections. U can
use the selectionmode property to
change this behaviour to allow ur users to
make week or month selection.

Working with date ranges


protected void Calendar1_SelectionChanged(object sender,
EventArgs e)
{
Response.Write("u selected:" +
Calendar1.SelectedDate.ToShortDateString()+"<br><br>");
for (int i = 0; i < Calendar1.SelectedDates.Count; i++)
{
Label1.Text +=
Calendar1.SelectedDates[i].ToShortDateString() + "<br>";
}
}

The following sample demonstrates mode selection with a


Calendar control.
In this example we declare one Calendar control, and one DropDownList
control in an .aspx file. Then we create an event handler for the
SelectedIndexChanged event which displays SelectionMode Style in a
Calendar control.

You can make appointment-style calendars by adding content in the


OnDayRender event. Two of the arguments for OnDayRender are
the Day that is being rendered and its Cell object. Custom text can
be added to the cell for a particular day by adding it as a
LiteralControl to the Cell object's Controls collection, as shown in
the following example.

Changing style and behavior of


calendar
The calendar control includes an event
called dayRender that allows you to
control how a single date or all the dates
in the calendar are rendered.

protected void Calendar1_DayRender(object sender,


DayRenderEventArgs e)
{
e.Cell.VerticalAlign = VerticalAlign.Top ;
if (e.Day.DayNumberText == "1" &&

e.Day.IsSelected && e.Day


.Date.Month.ToString ()=="8")

{
e.Cell.Controls.Add(new LiteralControl("<p> user
grioup meeting</p>"));
e.Cell.BorderColor = System.Drawing.Color.Black;
e.Cell.BorderWidth = 1;
e.Cell.BorderStyle = BorderStyle.Solid;
e.Cell.BackColor = System.Drawing.Color.LightGray;
}
}

BulletedList
You can also determine the style used for displaying the Bulleted list. The Bulleted
List control can be constructed of any number of < asp:ListItem > controls or can be
data-bound to a data source of some kind andpopulated based upon the contents
retrieved. Below listing shows simple Bulleted list
In this example we declare one BulletedList control, and one DropDownList control in an .aspx
file. Then we create an event handler for the SelectedIndexChanged event which displays
Bullet Style in a BulletedList control.

Multiview and view server control


The MultiView control acts as a container for groups of
View controls. Each View control in turn contains child
controls such as buttons and text boxes. Your application
can programmatically display a specific View control to
the client based on criteria such as user identity, user
preferences, or information that is passed in a query
string parameter.
The multiview and view server control work together to
give you the capability to turn on/off sections of ASP.NET
page. Turning sections on and off , which means
activating and deactivating a series of view control with
multiview control

Example -1:Working with the


multiview and view control

This example shows three views expressed int the multiview control. Each view is
constructed with an <asp:view. Server control. A button is added to each of the first
two views of the multiview control.
Before either of the buttons can be clicked , the multiview controls ActiveViewIndex
attribute is assigned a value. By default the activeviesindex, which describes the view
that shoul be showing, is set to -1. this means that no view shows when the page is
generated.
To start on the first view when the page is drawn, set the activeviewindex property to
0, which is the first view becoz this is the zero-based index.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MultiView1.ActiveViewIndex = 0;
}
}

Each of the buttons in the multiview control triggers the nextview method. Nextview
simply adds one of the activeviewindex value,thereby showing the nexti in the series until
the last view is shown.
public void nextview(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex += 1;
}
The previousview method(UDF) substract one from the activeviewindex value, thereby
showing the previous view in the view series.
public void prevview(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex -= 1;
}

Another option is to spice up the multiview control by adding a step counter that
displays to a label control) which step in the series the end user is currently
performing. In the Page_PreRender event, we c an write the code for it.
protected void Page_PreRender(object sender, EventArgs e)
{
Label1.Text = "step :" + (MultiView1.ActiveViewIndex + 1).ToString() + "of " +
MultiView1.Views.Count.ToString();
}

Example 2

Wizard server control


The Wizard control enable you to build ASP.NET Web pages that present users with
multi-step procedures.

In this , three steps are defined with the <asp:WizardSteps> control.


The <asp:wizard> element itself contains a couple of important attributes. The first is
DisplaySideBar. It is set to true by default-meaning that a side navigation system in the
displayed control enables the end user to quickly navigate to other steps in the process.
The ActiveStepIndex attribute of the wizard control defines the first wizrd step, it is set to
-0

Examining the AllowReturn Attribute:


Another interesting attribute of the wizard control is the AllowRetun attribute. By setting
this attribute on one of the wizard steps to False , you can remove the capability for end
user to go back to this step after they have viewed it.
<asp:WizardStep runat="server" Title="Step 2" AllowReturn ="false" >this is
second step
</asp:WizardStep>

StepType Attribute:
Another interesting attribute is steptype. The steptype attribute defines the structure
of the buttons used on ther steps. By default , the wizard control places only a next
button on the first step. It understands that you donot need the previous button here. It
also knows to use a next and previous button on the middle step, and it uses previous
and finish buttons o the last step. By default the steptype attribute is set to Auto,
meaning that the wizard control determines the placement of buttons.

In addition to Auto, steptype value options include Start,step,finish and complete. Start
means that the step defined only NEXT button. A value of step means that wizard step
has NEXT and PREVIOUS buttons. Finish means that the step includes PREVIOUS and
FINISH button. Complete enables you to give some final message to the end user who is
working through the step of wizard control.
When you run this wizard control , u still see only the first three steps I the side
navigation because the last step has a steptype set to complete, it does not appear in
the side navigation list. When the user clicks the Finish button in step3, the last step-is
shown and no buttons appear with it

Utilizing wizard control events:


The wizard control event exposes events for each of the possible steps that an
end user might take when working with the control.

EVENT

DESCRIPTION

ActiveStepChanged :

The ActiveStepChanged event is raised when the


current step that is displayed in the Wizard control
changes.

protected void Wizard1_ActiveStepChanged(object sender, EventArgs e)


{ Wizard1.HeaderText = "You are currently on " +Wizard1.ActiveStep.Title; }

EVENT

DESCRIPTION

CancelButtonClick :The CancelButtonClick event is raised when the Cancel button on


the Wizard control is clicked.

protected void Wizard1_CancelButtonClick(object sender, EventArgs e)


{
Response.Redirect("default3.aspx");
}

FinishButtonClick :

The FinishButtonClick event is raised when the Finish button


the Wizard control is clicked.

protected void Wizard1_FinishButtonClick1(object sender, WizardNavigationEventArgs


e)
{

Response.Write("clicked finish");

EVENT

DESCRIPTION

NextButtonClick :

The NextButtonClick event is raised when the Next button on


the Wizard control is clicked.

protected void Wizard1_NextButtonClick(object sender, WizardNavigationEventArgs e)


{
// When the Next button is clicked, increase the Wizard1.BorderWidth by 5.
Wizard1.BorderWidth = Unit.Pixel((int)(Wizard1.BorderWidth.Value + 5));
}

PreviousButtonClick :

The PreviousButtonClick event is raised when the prervious


button on the Wizard control is clicked.

protected void Wizard1_PreviousButtonClick(object sender,


WizardNavigationEventArgs e)
{
// When the previous button is clicked, decrease the Wizard1.BorderWidth by 2.
Wizard1.BorderWidth = Unit.Pixel((int)(Wizard1.BorderWidth.Value + 2));
}

EVENT

DESCRIPTION

SideBarButtonClick:

The SideBarButtonClick event is raised when a button


on the sidebar area is clicked.

Using wizard control to show form elements:


Design the form like below:

<asp:Wizard ID="Wizard1" runat="server" ActiveStepIndex="2" Style="z-index: 100;


left: 72px; position: absolute; top: 95px" Height="193px" Width="485px"
CancelDestinationPageUrl="~/wiz1.aspx" DisplayCancelButton="True" >
<WizardSteps>
<asp:WizardStep runat="server" Title="personal information" ID="wizardstep1">
<asp:Label ID="Label1" runat="server" Text="First name" ></asp:Label>
<asp:Label ID="Label2" runat="server" Text="Last name"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server" ></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server" ></asp:TextBox>
<asp:Label ID="Label3" runat="server" Text="Email:"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
</asp:WizardStep>

<asp:WizardStep runat="server" Title="membership information" ID="wizardstep2">


<asp:Label ID="Label4" runat="server" Text="are you already a member of our
group?"></asp:Label>
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="r1" Text="yes" />
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="r1" Text="no" />
</asp:WizardStep>
<asp:WizardStep runat="server" Title="provided information" StepType ="Complete"
ID="wizardstep3" OnActivate ="wizardstep3_Activate" >
<asp:Label ID="Label5" runat="server" Text="Label"></asp:Label>
</asp:WizardStep>
</WizardSteps>
</asp:Wizard>

protected void wizardstep3_Activate(object sender, EventArgs e)


{
Label5.Text = "firstname:" + TextBox1.Text.ToString() + "<br>" + "last name:" +
TextBox2.Text.ToString() + "<br>" + "email:" + TextBox3.Text.ToString();
}

ASP.NET Validation Server


Controls:
An important aspect of creating ASP.NET Web pages for user input is to be able to
check that the information users enter is valid. ASP.NET provides a set of validation
controls that provide an easy-to-use but powerful way to check for errors and, if
necessary, display messages to the user.
Type of validation

Control to use

Description

Required entry

RequiredFieldValidator

Ensures that the user does not


skip an entry.

Comparison to a value

CompareValidatorCompares a user's entry


against a constant value,
against the value of another
control (using a comparison
operator such as less than,
equal, or greater than), or for a
specific data type.

Range checking

RangeValidator

Checks that a user's entry is


between specified lower and
upper boundaries. You can
check ranges within pairs of
numbers, alphabetic
characters, and dates.

Pattern matching

RegularExpression

Checks that the


entry matches a pattern
defined by a regular
expression. This type of
validation enables you to
check for predictable
sequences of characters,
such as those in e-mail
addresses, telephone
numbers, postal codes, and
so on.

User-defined

CustomValidator

Checks the user's entry using


validation logic that you write
yourself. This type of
validation enables you to
check for values derived at

run time. You can attach more


than one validation control to
an input control. For example,
you might specify that a
control is required and that it
also contains a specific range
of values.
A related control, the ValidationSummary control, does not perform validation, but is
often used in conjunction with other validation controls to display the error messages
from all the validation controls on the page together.

ControlToValidate :The programmatic ID of the input control that the validation control
will evaluate. If this is not a legitimate ID, an exception is thrown.
ErrorMessage:The error message to display in the ValidationSummary control if
validation fails. If the Text property of the validation control is not set, this text is also
displayed in the validation control when validation fails. The ErrorMessage property is
commonly used to provide different messages for the validation control and the
ValidationSummary control.
IsValid:Indicates whether the input control specified by the ControlToValidate property is
determined to be valid.
SetFocusOnError:Indicates whether focus is set to the control specified by the
ControlToValidate property when validation fails.
Text:When set, this message is displayed in the validation control when validation fails. If
this property is not set, the text specified in the ErrorMessage property is displayed in the
control.
ValidationGroup:Specifies the name of the validation group to which this validation
control belongs.

Login Controls
Login control: is used to create the logon
page for a web application.

LoginView control: provides a way of


altering the appearance of the page
whether the user is logged in or not.. The
loginview control has the built in
functionality to authenticate the current
users status and their roles. If found
authenticated it displays the appropriate
information to that user.

Login status control


This control provides the user with
feedback so that they know whether they
have remembered to log in to the site. It
can also display the login and logout
status as link button.

LoginName Control
Is responsible for displaying the name of
the presently authenticated user. It uses
page.user.identity to return the value for
the users name.

Password recovery
Is used to retrieve or reset the passwordof
the user.

Using Login Control


Place a login control the form. Now click the
glyph at the top right corner of the login control
to display its smart tag and select Administer
website option.
Click the Security tab and then click the use
the security setup wizard to set up the security
step by step link.
We want out website to authenticate users who
are trying to access it from internet. So select
from the internet radio button

The next step is to add user and their info


you want the user to be authenticated
against. If the user tries to access your site,
his username and password and othe info
will be matched against the users info you
had added here and.
-Add as many user as u want to add, but do
remember that the password you mention
for these users must have one numberic
character,one special character and rest of
the string must not be the username.

Now well create roles out of the user awe just


created and then assign the permissions to
those roles.
Click the next button to complete the process.
TIP: all the information regarding users and
permissions that u create using the wizard goes
into a database file called ASPNETDB.MDF,.
Which u can find in the App_Data folder
present under the application folder.

Place the login control on the form and name


this form as login.aspx and add another web
form called welcome.aspx to the project and
place a label control-LoginName control and
LoginStatus on this page
Set the DestinationPageUrl proeprty of the
LoginControl on login.aspx to welcome.aspx.
Set the LogoutAction property of the
LoginStatus control on the welcome.aspx to
RedirectToLoginPage.

Grid view
<asp:SqlDataSource ID="SqlDataSource1
UpdateCommand ="update studtable set snm=@snm where sid=@sid"
DeleteCommand="DELETE FROM [studtable] WHERE [sid] = @sid" >
<UpdateParameters >
<asp:Parameter Name ="snm" Type ="String" />
<asp:Parameter Name ="sid" Type ="Int32" />
</UpdateParameters>
<DeleteParameters >
<asp:Parameter Name ="sid" Type ="Int32" />
</DeleteParameters>
</asp:SqlDataSource>

Working with database


GridView Control: is a successor to the datagrid
control existing in the previous versions of
asp.net.
DetailsView Control: Displays the record of only
a single data row from the underlying
datasource. It can also be used for
editing,deleting and inserting the record. Its
often displayd in the master/client scenario
where u need to specify the details of any
sel3ected record from a DatagridView or any
similar bound control

Master/client example using


gridview and detailview
Place gridview and detail view control on
the form. Let assume that gridview
datasource is Sqldatasource1 and
detailview datasource is Sqldatasource2.
Switch to the source code and type the
following lines in place where the tags for
sqldatasource2(for detailview ) is there.

Master/client

Need to code in the default.aspx page


<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$
ConnectionStrings:ConnectionString3 %>"
ProviderName="<%$
ConnectionStrings:ConnectionString3.ProviderName %>"
SelectCommand='SELECT * FROM "EMP"'
FilterExpression ="empno='{0}'">
<FilterParameters >
<asp:ControlParameter Name ="empno"
ControlID ="gridview1" PropertyName
="selectedvalue" />
</FilterParameters>
</asp:SqlDataSource>

Binding Standard Control


Listbox,dropdownbox,checkedlistbox here
are used to demo binding standard
control. As we know that we can bind
these control with datasouce.
Place these control on the form.
Place sqldatasource1 control from the
data tab on to the form.

click the smart tag of listbox and select choose


datasource.from the wizard select the
sqldatasouce1 from select a datasource.
Select the datafield and datafield value to be
displayed for the listbox.
Follow the same steps for thedropdown and the
checked list box.

Using DataReader
You can use datareader to access data, not just
dataset. The ADO.NET DataReader can be used
to retrieve a read-only, and forward-only streams
of data. This can increase application
performance both by retrieving data as soon as
it is available, and (by default) storing only one
row at a time in memory, thus reducng system
overhead. As the query executes, the result are
returned, and stored in the netword buffer on the
client, until you request them using the read
method of the datareader.

Place a gridview control on the form.


Default.aspx.cs
using System.Data.OleDb;
public partial class datareader_gridvew : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
OleDbConnection cn;
cn = new OleDbConnection("provider=msdaora;data
source=oracie;user id=scott;password=tiger");
OleDbCommand cmd;
cmd = new OleDbCommand("select * from emp", cn);
cn.Open();
OleDbDataReader dr;
dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
dr.Close();
}
}

FormView Control
The formview control is a functionality
rich control that allows you to
edit,delete,and inser records with very little
or almost no code.it displays thesingle
record from the underlying data source
and allows users to specify the userdefined templates.

Place Formview control on the form. Set the


Defaultmode property to insert or edit as per
requirement. Below is the formview with
defaultmode-insert

Open the source code and add following lines of code for insertion
of new record.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ onnectionStrings:ConnectionString3
%>"
ProviderName="<%
$ConnectionStrings:ConnectionString3.ProviderName %>"
SelectCommand='SELECT * FROM "STUD"'
InsertCommand ='INSERT INTO STUD
VALUES(:NM,:BDT,:PHNO)'
OnInserted="SqlDataSource1_Inserted">
<InsertParameters >
<asp:Parameter Name ="NM" Type ="STRING" />
<asp:Parameter Name ="BDT" Type="DateTime" />
<asp:Parameter Name ="PHNO" Type ="DECIMAL" />
</InsertParameters>
</asp:SqlDataSource>

LINQ

Querying with LINQ


.NET 3.5 introduces a new technology called Language

Integrated

Query or LINQ. LINQ is designed to fill the gap that existes

between
traditional .NET languages, which offer strong typing and full object oriented
development, and query languages such as SQL, with syntax for query
operations.
With introduction of LINQ into .NET, query becomes a first class concept in
.NET, whether object ,XML or data queries.
LINQ includes three basic types of queries, LINQ to Objects, LINQ to XML(or
XLINQ) and LINQ TO SQL(or DLINQ)

LINQ to objetcs:
The first and most basic flavour of LINQ is LINQ to objects.
It enables you to perorm complex query opertions against
any enumerable object

Where

select

4
1

TRADITIONLA QUERY METHODS:


c#:
public class Movie
{
public string fnm
{
get;
set;
}
public string lnm
{
get;
set;
}
}

NOTE: class is generated under app_code folder

Keep the gridview control on the web fom and


write the code for default.aspx.cs
using System.Collections.Generic;

public partial class _Default : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
var movies = getmovies();
this.GridView1.DataSource = movies;
this.GridView1.DataBind();
}

public List<Movie> getmovies()


{
return new List<Movie>
{
new Movie {fnm ="nutan",lnm="gupta"},
new Movie {fnm ="shekhar",lnm="lad"},
new Movie {fnm ="anil",lnm="kapoor"},
new Movie {fnm ="rajesh",lnm="khanna"},
new Movie {fnm ="reena",lnm="roy"},
};
}

Replacing traditional queries


with LINQ
LINQ is an extension to .NET , and because of this , is isolated in its own set of
assemblies . The base LINQ functionality is located in the new System.core.dll
assembly.
Additionally, by default , projects in VS2008 include a reference to this assembly so
when starting new Asp.NET web projetcs, LINQ should be readily available to you.
protected void Page_Load(object sender, EventArgs e)
{
//creating query with LINQ
Var movies=getmovies();
var qry = from m in movies select m;
this.GridView2.DataSource = qry;
this.GridView2.DataBind();
}

If we deconstruct the code sample, there are three basic actions happening.
First , the code uses the GetMovies() method to obtain the generic
List<movie> collection.

Next , the code uses a very simple LINQ query to select all of the Movie
objects from the generic movies collection. Notice that this specific LINQ query
utilizes new language keyword like from and select in the query statement.

The query also defines a new variable m . This variable defines in two ways in
the query. First, by defining it in the from statement from m, we are telling
LINQ to make m represents the individual collection item, which in this case is
a movie object.
The second use of m in the query is in the select statement. Using m in the
select statement tells LINQ to output a projection that matches the structure of
m. in this case that means LINQ creates a projection that matches the movie
object structure.

Creating a custom projection


with LINQ

We can also create our own custom projection by explicitly


defining the fields we wanted return from the query using the
new keywod along with the select operator.
//creating custom projection with LINQ
Var movies=getmovies();
var qry1 = from m in movies
select new{m.fnm ,.,};
this.GridView3.DataSource = qry1;
this.GridView3.DataBind();
Note: will display only selected fields

Creating a custom projection


field names
We can also create our own custom projection by explicitly defining the fields we
wanted return from the query using the new keywod along with the select operator.
//creating custom projection with LINQ
Var movies=getmovies();
var qry1 = from m in movies
select new{FirstName=m.fnm };
this.GridView3.DataSource = qry1;
this.GridView3.DataBind();
Note: will display only selected fields with column name

Controlling data ordering using


LINQ
LINQ also includes the ability to order the results using the order by statement. As
with SQL, u can choose to order the results in either ascending or descending order.
Place gridview conntrol thhe form.
protected void Page_Load(object sender, EventArgs e)
{
//controlling data ordering using linq
var movies = getmovies();
var qry=from m in movies orderby m.lnm descending
select new{first_name=m.fnm ,last_name=m.lnm };
GridView1.DataSource =qry;
GridView1.DataBind();
}

public List<Movie> getmovies()


{
return new List<Movie>
{
new Movie {fnm ="anil",lnm ="lad"},
new Movie {fnm ="bhavna",lnm ="reddy"},
new Movie {fnm ="anu",lnm ="lad"},
new Movie {fnm ="chetan",lnm ="reddy"},
new Movie {fnm ="babita",lnm ="bhaskar"}
};
}

Query filters

LINQ also supports adding qury filters using a familiar SQL-Like WHERE syntax
Place grid view control on the form
protected void Page_Load(object sender, EventArgs e)
{
//adding a filter to the linq query
var movies = getmovies();
var qry=from m in movies where

m.lnm =="reddy" && m.fnm

=="chetan"

select m;
GridView1.DataSource =qry;
GridView1.DataBind();

}
public List<Movie> getmovies()
{
return new List<Movie>
{
new Movie {fnm ="anil",lnm ="lad"},
new Movie {fnm ="bhavna",lnm ="reddy"},
new Movie {fnm ="anu",lnm ="lad"},
new Movie {fnm ="chetan",lnm ="reddy"},
new Movie {fnm ="babita",lnm ="bhaskar"}

Data grouping

LINQ also greatly simplifies grouping data againusing SQL-LIKE group syntax.
protected void Page_Load(object sender, EventArgs e)
{
//grouping data usinglinq query
var emp = getemp();
var qry = from m in emp

group m by m.desg into g


select new { desg = g.Key, count = g.Count() };
GridView1.DataSource = qry;
GridView1.DataBind();
}
public List<emp> getemp()
{
return new List<emp>
{
new emp{nm ="blake",sal =5000,comm =56, desg ="mkt"},
new emp{nm ="smith",sal =4500,comm =100, desg ="clerk"},
new emp{nm ="john",sal =6000,comm =1056, desg ="sales"},
new emp{nm ="killer",sal =85000,comm =500, desg ="sales"},

LINQ to XML
The second flavour of linq is called LINQ to XML(or XLINQ). As the name implies,
LINQ to XML enaqbles you to use the same basic LINQ syntax to query XML
documents.
First thing to create a xml file

<?xml version="1.0" encoding="utf-8" ?>


<emp1>
<empdata>
<nm>smith</nm>
<sal>2345</sal>
<desig>clerk</desig>
</empdata>
<empdata>
<nm>blake</nm>
<sal>4500</sal>
<desig>mgr</desig>
</empdata>
<empdata>
<nm>killer</nm>
<sal>3500</sal>
<desig>mkt</desig>
</empdata>
</emp1>

protected void Page_Load(object sender, EventArgs e)


{
var qry = from m in
XElement.Load(MapPath("XMLFile.xml")).Elements("empdata")
select m;
GridView1.DataSource = qry;
GridView1.DataBind();
}
}
NOTE: notice that the fields included in the resultset of the query
dont really show the node data as u might have expected, with
each child node as a separate field in thhe gridview. This is becoz
query used in the listing returns a collection of generic Xelement
objects, not emp objects as u might have expected.

Mapping XML elements using


LINQ

protected void Page_Load(object sender, EventArgs e)


{
var qry = from m in XElement.Load(MapPath("XMLFile.xml")).Elements("empda
select new
{
nm = (string)m.Element("nm"),
sal = (int)m.Element("sal"),
desig = (string)m.Element("desig")
};
GridView1.DataSource = qry;
GridView1.DataBind();
}

LINQ TO SQL
LINQ to SQL is the last form of LINQ in the release of >NET . LINQ to SQL , as
the name implies, enables you to quickly and easily query SQL-BASED data
sources, such as SQL SERVER 2005.
LINQ TO SQL also includes a basic Object-Relation (O/R) mapper directly in
visual studio. The o/r mapper enables u to quicly map sql-based data sources to
CLR objects that u can then use LINQ to query. It is the easiest way to get the
linq-to SQL
The o/r mapper is used by adding the new linq to sql classes file to ur web
application. After clciking the add new item - select sql-to classok button to
add the file to ur project.
Once the file is open vs automatically opens its linq to sql design surface.

Querying data from linq to sql


protected void Page_Load(object sender,
EventArgs e)
{
empdataDataContext dc = new
empdataDataContext();
var qry = from m in dc.emptables select m;
GridView1.DataSource = qry;
GridView1.DataBind();
}
}

Grouping linq to sql data


empDataContext dc = new empDataContext();
var qry = from m in dc.Products group m
by m.SupplierID into g select new { id =
g.Key, count = g.Count() };
this.GridView1.DataSource = qry;
this.GridView1.DataBind();

HTML CONTROLS
CLIEND AND SERVER HTML
CONTROLS: there are two ways to work
with these control- to the client
browser(HTML CLIENT CONTROLS) and
in the server(HTML server controls).
In the client you must use a scripting
language, such as javascript.

You can make these control to run at


server and so handle them with visual
basic or c#code., but they only support
very limited events that can be handled on
the server-typically ,just an event named
ServerClick or ServerChange

<html>
<head>
<script language="javascript">
function showmsg()
{
alert("clicled");
}
</script>
</head>
<body>
<input type="button" value="Click me" onclick="showmsg()">
</body>
</html>

Master pages and themes


Need for master page and themes arise when u
want to create web pages that contain some
common elements and u want to customize the
properties of different controls like
buttons,textbox and labels.
For eg, when u want to create a web site for ur
company in which all the web pages have as
header stating the company name and all
buttons on the web page are of blue color. We
can create this web site by using master pages
and themes.

Suppose u want to include a navigation bar at a


common place in all the web pages of ur website. If
u are not using a master page, you will have to copy
and paste the code for the commmon navigation bar
on each page, which is obvious a tedious and time
consuming job.
Also if later we want to change the navigation bar
then the changes has to be made with all the web
pages.
So, however if we are using master pages , we just
need to include the navigation bar code in the
master page and all the web pages will inherit it.

To create master page for a website,


identity the controls that you want to
display on all the pages then add these
control to master page. Then create the
contentplaceholder for the master page to
plcae the content of the web pages. When
this web site is executed , then the layout
of the master pageand the content in
contentplaceholders are merged to display
the output web page.

Themes is also a new feature of ASP.NET 2.0


that helps maintain a common look and feel
across or several pages of your web site.
Themes are needed when u want to keep the
style and layout information file separate from
other web site files. Themes can include
images and skin files,the skin files set the
visual properties of ASP.NET controls

Working with master page


Right click the web application and select
add newitem. Select the master file option
from the template.
Design the master page with the control u
want .
Add new webpage and slect theuse mater
page option . It waill ask for u to select the
master page. So select ur master page
and say ok.

You can see that the default page acquires


the properties of master page.
MODIFYING CONTENT ON THE MASTER
PAGE FROM CONTENT PAGE:
U can update the content on the
masterpage by finding the control which
needs to be modified on the master page
from the content page.

Place calendar control on the master page.


Now add new page default.aspx and place textbox,label and button on the
form.
Write the following lines of code on button_click event
protected void Button1_Click(object sender, EventArgs e)
{
try
{
Calendar cal;
cal = (Calendar)Master.FindControl("Calendar1");
if (cal != null)
{
cal.VisibleDate = Convert.ToDateTime(TextBox1.Text);
cal.SelectedDate = Convert.ToDateTime(TextBox1.Text);
}
}
catch
{
Response.Write("invalid format");
}
}

Run the application. Enter date in


mm/dd/yy format in the text box and click
the update button.
U will c that the the calender date has
changed to the date provided with textbox.

Getting the labels text value in


the content page:

Creating themes
Applying built-in themes to web pages is
quite easy, as u just need to specify the
name of the theme with the theme
attributeof the page directive. However we
can also apply custom themes to web
pages. For that we need to create a theme
first.

steps
Right-click the web site name on the solution
explore and select add ASP.NET folder | theme
from the shortcut menuto add App_Theme
foleder. A subfolder named Theme1 is
automatically created inside the App_Theme
folder.
Right click the theme1 folder nd select Add new
item option from the menu to display add new
item dialog box.
Select the skin file template option and specify the
name of the skni as theme.skin and click add
button.

Now we have created a new skin file we will


define the style properties inside it. Add the
following line of code to the theme.skin file.
<asp:label runat="server" font-bold="true"
font-size="Large" Forecolor="red"
backcolor="blue"/>
<asp:button runat="server" Forecolor=green"
backcolor="blue"/>
<asp:text runat="server" font-bold="true" fontsize=medium" Forecolor=blue"
backcolor=silver"/>

Now to test this skin, we also need to add


these controls in the page.
Code in default.aspx page
<%@ Page Language="C#"
AutoEventWireup="true" Theme ="Theme1"
CodeFile="apptheme.aspx.cs"
Inherits="apptheme" %>

Applying theme to an entire


application
In addition to applying an asp.net theme to your asp.net pages using the theme
attribute within the page directive, u can also apply it an application level from the
WEB.CONFIG file.
<?xml version="1.0"?>
<configuration>
<system.web">
<pages theme ="theme1>
</pages>
</system.web">
</configuration>

If wespecify the theme in the web.congig file, you do not need to define the
theme again in the page directive of your asp.net pagesa. The theme is
applied automatically to each and every page with ur application

Including CSS files in your


themes
In addition to the server control definition that you can create from with a .skin file, you
can make further definitions using cascading style sheets (CSS). When using a .skin file,
that you could define only the styles associated with server controls and nothing else.
However , developers usually use quite a bit more than server controls in their ASP.NET
pages are routinely made up of HTML server control ,raw HTML, or even RAW text, at
present theme only has a skin file associated with it. Any other items have no style
whatsoever applied to them.

It is easy to create CSS files for ur themes when using VS2008. Right click the theme
folder and select new item. In the list of opetions, select the option style sheet and name
it summer.css. The summer.css should be sitting right next to ur .skin file. This creates
an empty .css file for ur theme. Code it as below.

body
{
font-size:x-small;
font-family :Verdana;
color :Blue ;
}
a:link
{
color :Blue ;
text-decoration : none;
}
a:visited
{
color:Green ;
text-decoration :none;
}
a:hover
{
color:Red ;
text-decoration :underline overline;
}

In the CSS file, four things are defined. First , you define text thst is found within the
<body> tage of the page(basically all text).

Applying themes at run time


Consider scenario where end user will
select the theme and apply at runtime..
We will create two themes, and place
them in theme1 and theme2 folder.

<asp:label runat="server" font-bold="true"


font-size="Large" Forecolor="red"
backcolor="blue"/>
<asp:button runat="server" Forecolor=green"
backcolor="blue"/>
<asp:text runat="server" font-bold="true" fontsize=medium" Forecolor=blue"
backcolor=silver"/>
Code for simple.skin

<asp:label runat="server" font-bold="true"


font-size="Large" Forecolor=blue"
backcolor=red"/>
<asp:button runat="server" Forecolor=blue"
backcolor=green"/>
<asp:text runat="server" font-bold="true"
font-size=medium" Forecolor=silver"
backcolor=blue"/>
Code for inverse.skin

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="runtimetheme.aspx.cs" Inherits="runtimetheme" %>

Here is the default.aspx file

<!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:Label ID="Label1" runat="server" Height="88px" Style="z-index: 100; left:
112px;
position: absolute; top: 120px" Text="applying theme at runtime"
Width="264px"></asp:Label>
select theme:<br />
<br />
<a href ="runtimetheme.aspx?theme=theme1" >simple</a>
<a href ="runtimetheme.aspx?Theme=Theme2" >inverse</a>
</div>
</form>
</body>
</html>

protected void Page_PreInit(object sender,


EventArgs e)
{
Page.Theme =
Request.QueryString["theme"];
}

STATE MANAGEMENT
Purpose
State management is the process by which you maintain state
and page information over multiple requests for the same or
different pages.
Types of State Management
There are 2 types State Management:
1. Client Side State Management
2. Server Side State Management

1. Client Side State Management


This stores information on the client's computer by
embedding the information into a Web page, a uniform
resource locator(url), or a cookie. The techniques
available to store the state information at the client end
are listed down below:
a. View State Asp.Net uses View State to track the
values in the Controls. You can add custom values to the
view state. It is used by the Asp.net page framework to
automatically save the values of the page and of each
control just prior to rendering to the page. When the
page is posted, one of the first tasks performed by page
processing is to restore view state

Design the page as below

Code for .aspx.cs page


Protected Sub Button1_Click(ByVal sender As
Object, ByVal e As System.EventArgs) Handles
Button1.Click
ViewState("name") = TextBox1.Text.ToString()
ViewState("city") = TextBox2.Text.ToString()
ViewState("color") = TextBox4.Text.ToString()
Label4.Text = "u data is saved in viewstate"
End Sub

Protected Sub Button2_Click(ByVal sender As Object,


ByVal e As System.EventArgs) Handles Button2.Click
Dim v_viewState As String
v_viewState = Request.Form("__VIEWSTATE")
Response.Write(v_viewState)
Dim nm, ct, cl As String
'TextBox1.Text = ViewState("name").ToString
'TextBox2.Text = ViewState("city").ToString
'TextBox4.Text = ViewState("color").ToString
nm = ViewState("name").ToString
ct = ViewState("city").ToString
cl = ViewState("color").ToString
Label4.Text = "ur name is" & nm & "city:" & ct &
"color" & cl
End Sub

b. Control State If you create a custom


control that requires view state to work
properly, you should use control state to
ensure other developers dont break your
control by disabling view state.
c. Hidden fields Like view state, hidden
fields store data in an HTML form without
displaying it in the user's browser. The data
is available only when the form is
processed.

Place textbox,button and hidden control on


the page. Set the value property for
hidden to sellglobally
Button_click()
{
TextBox1.Text = myid.Value;
}

d. Cookies Cookies store a value in the


user's browser that the browser sends
with every page request to the same
server. Cookies are the best way to store
state data that must be available for
multiple Web pages on a web site.

Place 2 textbox,label and button on


the page

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As


System.EventArgs) Handles Button1.Click
If TextBox1.Text = "orbit" And TextBox2.Text = "sell" Then
Response.Redirect("welcome.aspx")
Else
Dim obj As HttpCookie
obj = Request.Cookies("aaa12")
If obj Is Nothing Then
obj = New HttpCookie("aaa12")
obj.Value = 1
Else
obj.Value += 1
End If
Response.AppendCookie(obj)
Label1.Text = "No of Attempts: " & obj.Value
End If
End Sub

e. Query Strings - Query strings store values in the URL that are visible to the user. Use
query strings when you want a user to be able to e-mail or instant message state data with a
URL.

Page1 code:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim id As Integer
id = TextBox1.Text
Response.Redirect("Default.aspx?Id=" & id)
End Sub
Page2 code:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
If Request.QueryString IsNot Nothing Then
TextBox1.Text = Request.QueryString("id").ToString
Else
TextBox1.Text = ""
End If
End Sub

2. Server Side State


Management

a. Application State - Application State information is available to


all pages, regardless of which user requests a page.
Application State: ASP.NET allows you to save values using
application state, a global storage mechanism that is accessible
from all pages in the Web application. Application state is stored
in the Application key/value dictionary. Once you add your
application-specific information to application state, the server
manages it, and it is never exposed to the client. Application state
is a great place to store information that is not user-specific. By
storing it in the application state, all pages can access data from
a single location in memory, rather than keeping separate copies
of the data. Data stored in the Application object is not permanent
and is lost any time the application is restarted.

ASP.NET provides three events that enable you to initialize


Application variables (free resources when the application
shuts down) and respond to Application errors:
a. Application_Start: Raised when the application starts. This
is the perfect place to initialize Application variables.
b. Application_End: Raised when an application shuts down.
Use this to free application resources and perform logging.
c. Application_Error: Raised when an unhandled error
occurs. Use this to perform error logging.

Global.asax
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
Application["x"] = 0;
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Application["x"] = int.Parse(Application["x"].ToString()) + 1;

Default.aspx.cs
public partial class globaldemo : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write(Application["x"]);
}
}

b. Session State Session State information is


available to all pages opened by a user during a
single visit.

Both application state and session state


information is lost when the application restarts.
To persist user data between application restarts,
you can store it using profile properties.

You can define the session by using


session("valueName") = value
And You can retrieve the value in label (for
Example) By
Label1.text = session("valueName")

webform1.aspx.cs
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Session("msg") = txtuid.Text
Response.Redirect("webform2.aspx")
End Sub

webform2.aspx.cs
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Label1.Text = "Welcome to " & Session("msg")
End Sub

Security
Authentication and authorization:
Authentication is a process that determines
the identity of a user. After a user has
been authenticated, a developer can
determine if the identified user has
authorization to proceed. It is impossible
to give an entity authorization if no
authentication process has been applied

Authorization
Authorization is the process of determining whether an authenticated user is
permitted access to any part of an application, access to specif points of an
application, or access to specified datasets that the application provides.

The <authentication> node:


You can use the <authentication> node in the applications web.config file
to set the type of authentication ur Asp.NET application requires.
<system.web>
<authentication mode=windows|Forms|passport|none"/>
<authorization>
<deny users="?"/>
</authorization>
</system.web>

Provider
Windows

Forms

Passport

description
windows authentication is used
together with IIS authentication. This is
default setting.
request that are not authenticated are
redirected to an html form using HTTP clientside redirection. The user provide his login
information and submits the form.
a centeralized authentication service
provided by Microsoft that offers single
login and core profile services for member
site .

Windows-based authentication
Windows based authentication is handled between the
windows server where

Form based authentication


Is a popular mode of authenticating users to access an entire application or
specific resources with in an application. Using it enable u to put the login form
directly in the application so thet athe end used simply enters his unm/pwd into
an HTML form contained with the browser itself.
<system.web>
<authentication mode=Forms ">
<forms name=wrox loginurl=login.aspx path=/ />
</authentication>
<authorization>
<deny users="?"/>
</authorization>
</system.web>

U must apply this tructure to the web.config file. First using the
<authorization> elementg ,u r denying access to the applicxation to all
anonymous users. Only authenticated uer are allowed to access anty
page contained with the application.
If the requestoir is not autrhenticated, what is defines in the
<authentication> element is pt into action. The value of the mode
attribute is set to forms to employ form-based authentication/. . The
next attribute specified is the loginURL, which points to the page that
containg the application login form. The final attribute is path. It simply
specifies the location in which to save the cookie used to persisit the
authorized users access token.
Name : name is assignes to the cookie saved in order to remember the
user from request to request. The default value is .ASPXAUTH.

protected void Button1_Click(object sender, EventArgs e)


{
if (TextBox1.Text == "scott" && TextBox2.Text == "tiger")
FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, false);
else
Response.Write("invalid uername/password");
}
Note:RedirectFromLoginPage takes two arguments. First is the name of the
user, used for cookie authentication purposes. The second
argumentspecifies whether a durable cookie should be issued. If set to true,
the end user does not need to log in again to the application from one
browser session to the next.
Web.config file
<system.web>
<authentication mode=Forms "/>
<authorization>
<deny users="?"/>
</authorization>
</system.web>

Authenticating against values


contained in the web.config file
Previous eg is not the best approach fpr dealing
with unm and pwd offered for authentication. It is
never good idea to hardcode these things
directly into ur application.
The <form>element in web.config that u worked
can also take sub-element . The sub-element
<credentials> allows you to specify unm and
pwd combination directly in the web.config file.

Modify web.config file to add


unm/pwd values
<authentication mode="Forms">
<forms name ="wrox" loginUrl ="login.aspx"
path ="/" >
<credentials passwordFormat ="MD5">
<user name ="scott" password =tiger"/>
</credentials>
</forms >
</authentication >
<authorization>
<deny users="?"/>
</authorization>

The <credentials> elemebnt has been included to add unm and pwd to the
configuration file. It takes single attribute-passwordFormat . The possible
values of passwordFormat are clear,MD5,SHA1.

Clear: password are stored in clear text. The user password is compared
directly to this value without further tranformation.

MD5 : password are stored using a message Digest 5(MD5) hash digest.
When credentials are validated, the user passworsd is hashed using the
MD5 algorithm and compared equality with this value. Clear text password
are never is never stored or compared.

SHA1 : passwords are stored using SHA1 hash digest. When credentials
are validated, the user password is hashed using the SHA1 algorithm and
compared equality with this value. Clear text password are never is never
stored or compared.

Changing login.aspx page to work


with web.config file
if (FormsAuthentication.Authenticate(TextBox1.Text,
TextBox2.Text))
{
FormsAuthentication.RedirectFromLoginPage(Text
Box1.Text, true);
}
else
{
Response.Write("invalid user");
}

Web services
A Web Service (XML Web Service) is a unit of code that
can be activated using HTTP requests. Stated another
way, a Web Service is an application component that can
be remotely callable using standard Internet Protocols
such as HTTP and XML. One more definition can be, a
Web Service is a programmable URL. Web Services
came into existence to deliver distributed computing over
the Internet. A major advantage of the Web services
architecture is, it allows programs written in different
languages on different platforms to communicate with
each other in a standards-based way. Simply said, a
Web service is a software service exposed on the Web
through SOAP, described with a WSDL file and
registered in UDDI.

Why XML Web Services?


Today, available technologies like Component Object Model
(COM), Remote Method Invocation (RMI), Common Object
Request Broker Architecture (CORBA) and Internet Inter-ORB
Protocol (IIOP) are used to package application logic into
reusable components and are called remotely across multiple
platforms. The Internet today consists of tremendous number of
heterogeneous systems and a key limitation of all the above
said technologies is they are not easily interoperable with these
different systems and that limits their effectiveness as a
standard method for programming the Web. This is because of
the dependencies of these technologies on a particular
language or a particular Operating System or Object-model
specific protocols. Web Services on the other hand are very
different when compared to the said technologies as they are
built upon widely accepted standards that can interoperate
easily on the Internet. A key to the success of Web Services is
that they use a text-based messaging model to communicate
which allows them to operate effectively on different platforms.

SOAP
We hear a lot about SOAP these days.
Simple Object Access Protocol (SOAP) is
a lightweight protocol for exchange of
information in a decentralized, distributed
environment.

UDDI
Universal Discovery Description and
Integration is like the "Yellow Pages" of
Web services.

User profiles
User profile: you can make web-site more
friendly by customizing the web site
according to the preferences of the users
visiting the web-site.. For e.h you can
customize a shopping web site to display a
shopping cart consisting of the item
frequently purchased by a user, when the
user visits site. For this we need to collecte
the information of the user , visiting the
web site.

A user profile is a collection of various


properties. A property specifies the user
information that is to be gathered, when the
user visits the site. For e.g. we can deifne
first name,last name and the page visits
properties in a user profile to store the
detaild of the user and information about
web site usage.
The advantage of using user profile to store
the user information permanently. So the
information stored in the profile of user is
not lost when the user leaves the web site.

Anonymous profiles:
There could be a situation where a
number of users would like to explore your
website for free before actually registering
to it. We need to provide attractive user
profile to thesesurf for free user to make
them registered users. These surf for free
users are called anonymous users as they
do not have valid username and
password.

Note: by default the cookie gets expires


after a time period of 70 days. This time
period renewed every time a user visits
the web site.

Authenticated user
When surf-for free user of website become
registered user, you need to display different
data to them.
The authenticated profiles are displayed to the
authenticated users when they log on to the site
using valid UNM and PWD. By default all the
users are authenticated profiles because the
enabled attribute of the
<anonymousIdentification> element is false by
default.

Defining profiles:
To define the user profiles, you need to
define the properties for the user profile in
either the machine.config file .or
web.config configuration.a property is
defined with the <add> element, which is
available in the <property> element.

Web.config
(working with the single
profile[authenticated])
<profile>
<properties>
<add name="fnm"/>
<add name="snm"/>
<add name="state" default
value=hyd />
</properties>
</profile>

Defining multiple profiles


Weve used only a single type of profile
that is common for all users of an
application. It is also possible to define
multiple types of profiles for the end
users.. These multiple profiles exhibits
different types of users, such as anony.
And authenticated.

Web.config
<anonymousIdentification enabled ="true"/>
<profile>
<properties>
<add name="fnm"/>
<add name="snm"/>
<add name="state"
allowAnonymous="true "/>
</properties>
</profile>

protected void b1_Click(object sender, EventArgs e)


{
if (Page.User.Identity.IsAuthenticated)
{
Profile.fnm = t1.Text;
Profile.snm = T2.Text;
l1.Text = Profile.fnm;
L2.Text = Profile.snm;
}
Profile.state = T3.Text;
L3.Text = Profile.state;
}
}

caching
Caching is a technique to store data temporaily
in momory. For. Eg. Application needs to query a
databse which contain I million records after
every 4 sec for the same kind of result. Ur DB
will get updated in a time interval of say, an hour.
So, the dat retrieved from the DB will remain the
same for approx. 50 min. , as the DB will be
updated only after one hour. So querying the
same DB after every 4 seconds will increase the
network traffic and the load on the DB server.

Lets if we uses caching to store the results we


get after running the query on the DB. So we
cache the data for a fixed period of time say 50
min., then once the first qry is executed, the
results will be stored in cache. In the nxt 50
min. the same type of req. for the data will get
the data from the cache itself without running
the qry again on 1 million of record.

ASP.NET provides 3 kinds of


caching techniques
Output caching(page level caching)
Partial caching
Data caching
Output caching: in output caching the
complete HTML output of a rendered
ASP.NET page is stored in the cache and
the subsequent requests for the same
page is sent from the cache itself.

We can easily implement output caching by


just adding the @outputcache directive in
the web page as follows:
<%@ outputcache duration=10
varybyparam=none%>
Duration is in seconds.
Create application and add a label on the
default.aspx page.
Code for the code-behind file:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToString();
}

Using output caching with


varybyparam
The varybyparam attribute is used to
cache different copies of the same page
when they are generated dynamically
based on the parameters received.
Create a page with label,textbox and
button.

Code for default.aspx.cs


protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
name.Visible = false;
Label1.Visible = false;
Button1.Visible = false;
Label2.Visible = true;
Label2.Text = "output of this page was cached for " +
name.Text + ".the current time is :" +
DateTime.Now.ToString();
}
}

Write the lines in the source code.


<%@ OutputCache Duration ="10"
VaryByParam ="Name" %>

Partial-page caching

Its not always that you require the cache for the
complete page. This is also called partial-page or
fragment caching.Generally used for caching the
user control.
Design the user control by keeping the label.
Label1.text=control time is: +
datetime.now.tostring();
With source code (user control page)-- <%@ outputcache duration=10
varybyparam=none %>
Desing the new web page and drag the user control
on the page and also one label.
Label1.text=base time is: +
datetime.now.tostring();

Data caching

Data caching is useful when u need to cache


your own custom data into cache. For e.g. ,
you need to cache a dataset which can be
used later somewhere in ur application.
There are 3 main tasks for data caching:

1. Adding items to cache: cache(myvalue)=value


2. Retrieving data from cache:value=cache(myvalue)
3. Deleteing items from cache:
cache.remove(mydata1)

Using data caching:


In this example we will populate the
dataset from the XML file and store this
dataset in cache using the file based
dependency. So whenever our original
XML file changes, the cached dataset will
populate again.
Keep the gridview control and label on the
page.

Code for default.aspx.cs

DataSet ds = new DataSet();


protected void Page_Load(object sender, EventArgs e)
{
if (Cache["mycache"] == null)
{
ds.ReadXml(Server.MapPath("data1.xml"));
Cache.Insert("mycache", ds, new
System.Web.Caching.CacheDependency(Server.MapPath("data1.xml
")));
Label1.Text = "cache generated";
}
else
{
Label1.Text = "using pregenerated cache";
}
GridView1.DataSource = Cache["mycache"];
GridView1.DataBind();
}

State management
By using states with web application we
can preserve the state of the web
application both at the server and at the
client side.
The state of the web application actually
stores the changes that has been made to
the web application. .
If u are not using states then these
changes gets discarded.

Storing states is optional. But under certain


circumstances, it becomes quite imperative
to use states with your applications. For e.g.
it is necessary to store states for web
applications, such as e-commerce shopping
site or an intranet site of a company to keep
track of the user requests, such as the items
chosen by the user on a shopping site.
The various state types include
application,session, and view.

Application state
It is used to store the data corresponding to the
global variables of an ASP.NET web application.
The data in the application-state is stored once
and read many times. The application-state uses
the HttpApplicationstate class to store and share
the data throughout the application. The data
stored in the application state is accessible to all
pages of an ASP.NET web application and the
data is same for all the users accessing the web
applications.

Session - state
Each client accessing a web application maintains a
distinct session with the web server, and theres also
specific information associated with each of these
sessions. Session-state is used to store this information.
The session-state is defined in the <sessionstate>
section of the web.config file and stores the data specific
to a user session in session variables. Different session
variables are created for each user sessions. Also, the
session variables can be accessed from any page of the
web application. When a user access the web page a
session ID for the user is created. The session ID is
transferred between the server and the client over the
HTTP protocol using cookies.

View state
The view-information stores the page
specific information, when a page is
posted back to the server. When the page
is processed, the current state of the web
page and control is hashed into string and
saved as a hidden field. Such a state of
the web page s called view-state and is
defined as a hidden field on a web page.

Global.asax
The global.asax file resides in the root
directory of an ASP.NET web application
and is called ASP.NET application file. T
contains the code that is executed when
the certain events, such as start of an
application or error in an application are
raised by the web application.

ASP.NET AJAX
AJAX is an acronym for Asynchronous JavaScript and XML and in web application
development, it signifies the capability to build applications that make use of
XMLHttpRequest object.

Understanding the need for AJAX:


Today, if you are going to build an application, you have the option of creating a thickclient or a thin-client application.
A thick-client applications is typically a compiled executable that end user can run in the
confines of their own environment.. Generally, the technology to build this type of
application is the windows Forms technology.
A thin-client application is typically one that has its processing and rendering controlled
at a single point and the results of the view are sent down as HTML to a browser to be
viewed by a client. To work, this type of technology generally requires that the end-user
be connected to the internet or intranet of some kind.

Each type of application has its pros and cons. The thick-client style of
applications is touted as more fluid and more responsive to an end users
actions. In a web based application, the complaint has been for many years
that every action by an end user takes numerous seconds and results in a
jerky page refresh. In trun, the problem with the thick client style of
application has always been that the application sits on the end users
machine and any patches or updates to the application require you to
somehow upgrade each and every machine upon which the applications
sits..
ASP.NET AJAX in particular is further removing any of the negatives that
would have stopped you from building an application on the web.
ASP.NET AJAX makes your web applications some more fluid that ever
before. AJAX enabled applications are responsive and give the end user
immediate feedback and direction through the workflows that you provide.

Before AJAX
Windows Server
Asp.NET Processing
engine

request

response

End users internet


browser

End users client computer

So, what AJAX doing to ur web application? First off, lets take a look at what a web
page does when it does not use AJAX.
Figure shows a typical request and response activity for a web application.
In this case, an end user makes a request from his browser to the application that is
stored on your web server. The server processes the request and the Asp.NET
renders a page, which is then sent to the requestor as a response. The response,
once received by the end user, is displayed with the end users browser.
From here , many events that take place within the application instance as it sits
within the end users browser causes the complete request and response process to
reoccur. For instance, he end user might click the radio button, a check box, a button,
a calendar or anything else and this causes the entire web page to be refreshed or a
new page to be provided.

AFTER AJAX
Windows Server
Asp.NET Processing
engine

request

response

Asynchronous
request

End users internet browser


ASP.NET AJAX Library
End users client computer

Asynchronous
response

On the other hand, an AJAX-enabled web page includes a javascript library on


the client that takes care of issuing the calls to the web server. It does this
when it is possible to send a request and get response for just part of the
page and using script; the client library updates that part of the page
without updating the entire page. By just processing part of the page, the end
user experiences what some people term fluidity in a page,which makes the page
more responsive. The amount of code required to update just a portion of a page
is less and produces the responsiveness the end user expects.
Figure demonstartes that the first thing that happens is the entire page is delivered
in the initial request and response. From here, any partial updates required by the
page are done using the client script library.
This library can make asynchronous page requets and updates just the portion of
the page that needs updating.
One major advantage to this is that a minimal amount of data is transferred for the
update to occur.
Updating a partial page is better than recalling the entire page for what is just a
small change to the page

AJAX is dependent upon a few technologies in order for it to work. The first is the
XMLHttpRequest object. This object allows the browser to communicate to a abck-end
server and has been available in the Microsoft world since internet explorer 5 through
MSXM ActiveX component.
The other major component is JavaScript . This technology provides client-side
initiation to communication with the backend services and take care of packaging a
message to send to any server-side services.
Another aspect of AJAX is support for DHTML and DOM(Document Object Model).
These are the pieces that will change the page when the asynchronous response is
received from the server.
Finally the last piece is the data that is being transferred from the client to the server.
This is done in XML or, more important JSON(JavaScript Object Notation)

Building a simple Asp.NET3.5


page with AJAX
Design the page where two of the controls to add are typically Asp.NET server
control-label and button server control.
In addition to these controls, you are going to have to add some Asp.NET AJAX
controls.
From AJAX extension, add script manager server control to the top of the page and
include the second label and button control inside the updatepanel control.
Updatepanel control is a template server control and allows you to include any
number of items with in it.
The page will look like this:

Add the lines of code:


protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToString();
Label2.Text = DateTime.Now.ToString();
}
Note: when u will click button2(ajax button) the time with label2 will change
and not with label1 as the label1 is outside the updatepanel.

The ScriptManager control


The ScriptManager control is central to AJAX functionality in ASP.NET. The control
manages all ASP.NET AJAX resources on a page. This includes downloading
Microsoft AJAX Library scripts to the browser and coordinating partial-page
updates that are enabled by using UpdatePanel controls
The scriptmanager control takes acre of managing the JavaScript libraries that are
utilized on your page as well as marshalling te massage back and forth between the
server and the client for the partial page rendering process.
The marshalling of the messages can be done using either SOAP or JSON through
the script manager control.

UpdatePanel control
By using UpdatePanel controls, you can refresh selected parts of the page
instead of refreshing the whole page with a postback.
This is referred to as performing a partial-page update.
An ASP.NET Web page that contains a ScriptManager control and one or more
UpdatePanel controls can automatically participate in partial-page updates,
without custom client script.
When you use an UpdatePanel control, the page behavior is browser
independent and can potentially reduce the amount of data that is transferred
between client and server.

The following examples show different scenarios for using


the ScriptManager control.

Enabling Partial-Page Updates


The following example shows how to use the
ScriptManager control to enable partial-page updates. In
this example, a Calendar and a DropDownList control
are inside an UpdatePanel control. By default, the value
of the UpdateMode property is Always, and the value of
the ChildrenAsTriggers property is true. Therefore, child
controls of the panel cause an asynchronous postback

public partial class Default2 : System.Web.UI.Page


{
public void DropDownSelection_Change(Object sender, EventArgs e)
{
Calendar1.DayStyle.BackColor =
System.Drawing.Color.FromName(DropDownList1.SelectedItem.Value);
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
Label1.Text = Calendar1.SelectedDate.ToString();
Label2.Text = Calendar1.SelectedDate.ToString();
}
}

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


<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Calendar ID="Calendar1" runat="server"
onselectionchanged="Calendar1_SelectionChanged"></asp:Calendar>
<br />
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownSelection_Change">
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Green</asp:ListItem>
<asp:ListItem>Blue</asp:ListItem>
<asp:ListItem>Yellow</asp:ListItem>
<asp:ListItem>Silver</asp:ListItem>
</asp:DropDownList>

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


</ContentTemplate>
</asp:UpdatePanel>
</div>
<p>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
</p>
</form>
</body>

Updatepanel control..contd..
The <ContentTemplate> Element
There are a couple of ways to deal with the controls on the page that initiates the
asynchronous page pastbacks.
e.g.: putting the trigger inside of the UpdatePanel control
Put the label and the button control inside the updatepanel control
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Button" />
</ContentTemplate>
</asp:UpdatePanel>

</div> </form>

protected void Button1_Click(object sender, EventArgs e)


{
Label1.Text = "this button was clicked on :" + DateTime.Now.ToString();
}
In this case ,label and button server controls are contained within the updatepanel
server control. The <asp:updatepanel> element has two possible subelements:<ContentTemplate> and the <T riggers>element. Any content that needs to
be changed with the asynchronous page postbacks should be contained within the
<ContentTemplate> section of the updatepanel control.
By default, any type of control trigger(normally page postback ) that is contained
within the <ContentTemplate>section instead causes the asynchronous page
postback.. That mans, the button on the page will trigger an asynchronous page
postback instead of a full page postback. Each click on the button changes the time
displayed in the label control.

The <Trigger> element


Previous example demonstrates one of the big issues with this model: when the
synchronous poastback occurs, you are not only sending date/time value for the label
control, but you are also sending back the entire code for the button that is on the
page.
The code that is sent back to the client via asynchronous postback shows that the
entire section contained within the updatepanel control is reissued. You can slim down
your web pages by including only portions of the page that are actually updating.
If you take the button outside of the <contenttemplate> section of the updatepanel
control, then you have to include a <triggers> section within the control.

Using trigger to cause


asynchronous page postback
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="click to initiate esync request" />
</form>

C#:
protected void Button2_Click(object sender, EventArgs e)
{
Label2.Text = "this button was clicked on :" +
DateTime.Now.ToString();
}

Timer control
The ASP.NET AJAX Timer control performs postbacks at defined intervals. If you
use the Timer control with an UpdatePanel control, you can enable partial-page
updates at a defined interval. You can also use the Timer control to post the
whole page.
You use the Timer control when you want to do the following:
Periodically update the contents of one or more UpdatePanel controls without
refreshing the whole Web page.
Run code on the server every time that a Timer control causes a postback.
Synchronously post the whole Web page to the Web server at defined intervals.
When a postback was initiated by the Timer control, the Timer control raises the
Tick event on the server. You can create an event handler for the Tick event to
perform actions when the page is posted to the server.
Set the Interval property to specify how often postbacks will occur, and set the
Enabled property to turn the Timer on or off. The Interval property is defined in
milliseconds and has a default value of 60,000 milliseconds, or 60 seconds.

Design the page with label and timer control with the updatepanel control:

protected void Page_Load(object sender, EventArgs e)


{
if (!Page.IsPostBack)
{

Label1.Text = DateTime.Now.ToString();

}
protected void Timer1_Tick(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToString();
}

Updateprogress control
UpdateProgress controls is used to display the progress of partial-page updates.
If a page contains UpdatePanel controls, you can also include
UpdateProgress controls to keep users informed about the status of partialpage updates. You can use one UpdateProgress control to represent the
progress of partial-page updates for the whole page. Alternatively, you can
include an UpdateProgress control for every UpdatePanel control.
Using a Single UpdateProgress Control
You will begin by using a single UpdateProgress control to show the progress for
all partial-page updates on the page.
To use a single UpdateProgress control for the whole page
1. Create a new page and switch to Design view.
2. In the AJAX Extensions tab of the toolbox, double-click the ScriptManager
control to add it to the page.
3. Double click the UpdatePanel control to add it to the page.

4. Double-click the UpdateProgress control to add it to the page.


5. Inside the UpdateProgress control, add the text Processing.
6. Inside the UpdatePanel control add a Label control and a Button control.
7. Set the Text property of the Label control to Initial Page Rendered.

8. Double click the Button control to add a handler for the button's Click event.
9. Add the following code to the Click handler, which artificially creates a threesecond delay and then displays the current time.

protected void Button1_Click(object sender, EventArgs e)


{ // Introducing delay for demonstration.
System.Threading.Thread.Sleep(3000); Label1.Text = "Page refreshed
at " + DateTime.Now.ToString();
}

Using Multiple UpdateProgress Controls


One UpdateProgress control on the page can show a progress message for all
UpdatePanel controls on the page. Asynchronous postbacks originating
inside an UpdatePanel control cause the UpdateProgress control to display
its message. Postbacks from controls that are triggers for the panel also
display the message.
You can associate the UpdateProgress control with a single UpdatePanel control
by setting the progress control's AssociatedUpdatePanelID property. In that
case, the UpdateProgress control displays a message only when a postback
originates inside the associated UpdatePanel control.
In the next procedure, two UpdateProgress controls are added to a page, each
associated with a different UpdatePanel control.
To use multiple UpdateProgress controls on a page
1. Create a new page and switch to Design view.
2. In the AJAX Extensions tab of the toolbox, double-click the ScriptManager
control to add it to the page.
3. Double-click the UpdatePanel control two times to add two instances of the
control to the page.

4. In each UpdatePanel control, add a Label control and a Button control.


5. Set the Text property of both Label controls to Panel Initially Rendered.

6. Double-click each Button control to add a handler for each button's Click event.
7. Add the following code to each Click handler, which artificially creates a threesecond delay and then displays the current time.

protected void Button1_Click(object sender, EventArgs e)


{
// Introducing delay for demonstration.
System.Threading.Thread.Sleep(3000); Label1.Text = "Page
refreshed at " + DateTime.Now.ToString();
}
protected void Button2_Click(object sender, EventArgs e)
{ // Introducing delay for demonstration.
System.Threading.Thread.Sleep(3000); Label2.Text = "Page
refreshed at " + DateTime.Now.ToString();
}

8. Switch to Design view.


9. Click inside the first UpdatePanel control and add an UpdateProgress control.
10. Inside the UpdateProgress control, add the text Panel1 Updating.
11. This sets the ProgressTemplate property.
12. Select the UpdateProgress control, and in the Properties window, set the
AssociatedUpdatePanelID property to UpdatePanel1.

12. Click inside the second UpdatePanel control and add a second
UpdateProgress control.
13. Set the text of the UpdateProgress control to Panel2 Updating and set
its AssociatedUpdatePanelID property to UpdatePanel2.

14. Save your changes, and then press CTRL+F5 to view the page in a browser.
15. Click the button in the first panel.
After a short delay, the progress message associated with the first panel is
displayed. The other UpdateProgress control is not displayed.
16. Click the button in the second panel.
The progress message associated with the second panel is displayed

ASP.NET application folder


When we create ASP.NET application,asp.net 3.5 uses a file
based approach. When working with asp.net, we can add as
many files and folders as we want within our application
without recompiling each and every time a new file is added
to the overall solution. Asp.net includesthe capability to
automatically precompile your asp.net application
dynamically.

\App_Code Folder
The \app_code folder is manet to store classes,.wsdl
files , and a typed datasets. Any of these items store in
this folder are than automatically available to all the
pages with in your solution. The nice thing about this
folder is that when you palce something inside this
folder, vs 2008 automatically detects this and
compiles it if it is a class(.vb or .cs), automatically
creates your XML web servie proxey class(from the
.wsdl file) or automatically creates a typed Dataset for
you from your .xsd files. Ater the files are automatically
compildded , these items are then instantaneously
available to any of your Asp.Net PAGES THAT are in
the same solution .

First create a \app_code folder. To do this


right click the solution and choose add
as.nnet folder app_code.

ASP.NET Globalization and


Localization
Globalization is the process of designing
and developing applications that function
for multiple cultures. Localization is the
process of customizing your application
for a given culture and locale

Localization
The world is made up of a multitude of
cultures, each of which has a language
and a set of defined ways in which it views
and consumes numbers,currencies,sorts
alphabetically and so on. The .NET
framework deffines cultures and regions
using the request for comments 1766
standard definitionn that specifies a
language and region using two letter
codes separated by a dash.

Culture code description


EnUS English lang, united states
En-GB enf lang., united kingdom (great
britian)
En-AU eng lang.,Australia
Note: to c more go to msdn library and
search for culture info class which containg
culture code and its description.

Asp.Net threads
When the end user requests an asp.net
page, this web page is executed on a
thread from the thread pool. The thread
has a culture associated with it. You can
get information about the culture of the
thread programmatically and then check
for particular details about that culture. For
e.g.

Page_load ()
{
CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
Response.Write("current culture name:" + ci.Name.ToString()+"<br>");
Response.Write(" culture parent name:" + ci.Parent .Name.ToString()
+"<br>");
Response.Write(" culture display name:" + ci.DisplayName.ToString() +
"<br>");
Response.Write(" culture english name:" + ci.EnglishName.ToString() +
"<br>");
Response.Write(" culture native name:" + ci.NativeName.ToString() +
"<br>");
Response.Write(" calender type:" + ci.Calendar.ToString() + "<br>");
}

Changing the culture of the thread


using the cultureinfo object

System.threading.thread.currentthread.currentculture=new cultureinfo(thTH);
CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
Response.Write("current culture name:" + ci.Name.ToString()+"<br>");
Response.Write(" culture parent name:" + ci.Parent .Name.ToString()
+"<br>");
Response.Write(" culture display name:" + ci.DisplayName.ToString()
+ "<br>");
Response.Write(" culture english name:" + ci.EnglishName.ToString()
+ "<br>");
Response.Write(" culture native name:" + ci.NativeName.ToString() +
"<br>");
Response.Write(" calender type:" + ci.Calendar.ToString() + "<br>");

Defining the <globalization> section


in the web.config file
<configuration>
<system.web>
<globalization culture=ru-RU
uiCulture=ru-RU/>
</system.web>
</configuration>

Defining the culture at the page


level @page using directive
<%@page language =. Uiculture=ruRU culture=ru-RU %>

ASP.NET 3.5 Resource files


When we work with ASP.NET 3.5 all
resources are handled by a resource file.
A resource file is an XML-based file that
has a .resx extension. In our ASP.NET 3.5
applications, you store resource files as
either local resource or global resource

Using Resources for


Localization with ASP.NET
An effective way to create localized Web pages is to use
resources for your page's text and controls based on the
user's language and culture. By using properties placed
in resource objects, ASP.NET can select the correct
property at run time according to the user's language
and culture. The process is straightforward:
A resource file (.resx) stores values.
In your page, you indicate that controls should use
resources for their property values.
At run time, the controls' property values are derived
from the resource file.

Implicit Localization with ASP.NET


In implicit localization, you specify that control
properties should automatically be read from a
resource file, but you do not need to explicitly specify
which properties are localized. Then, you create a
resource file with localized values for specific
properties. At run time, ASP.NET examines the
controls on the page. If the control is marked to use
implicit localization, ASP.NET looks through the
resource file for the page. If it finds property settings
for the marked control, ASP.NET substitutes the
values in the resource file for those in the control.

In this example of implicit localization, you use a


combination of the designer and the Resource
Editor to generate a default resource file that you
will use as a starting point for localization in two
languages. Visual Web Developer will generate a
resource file based only on the controls on your
page. For this reason, it is a good idea to generate
the resource file after you have completed your
page's control layout, including simple controls
such as buttons, labels, and text boxes.

To place controls on a page


In Solution Explorer, right-click Default.aspx, click
Rename, and then type Sample.aspx.
Doing this will help avoid confusion in the rest of the
walkthrough with regard to default resource files
because implicit resource file names use page names.
Open Sample.aspx, and then switch to Design view.
In the Toolbox, from the Standard section, drag a Button,
a Label, and a TextBox control onto the page.
For each control, set Text to English Button, English
Label, and English TextBox, respectively.
After creating the page and adding the controls, you can use a Visual Web Developer
command to generate a local resource file for this page. The local resource file will
contain the resource strings for the controls on the page. Visual Web Developer
generates a resource string for each property that is designated internally in the control
as localizable. Each control can have different properties designated as localizable,
although most text-based properties are marked that way.

To automatically generate a
resource file

Click the designer surface or a control.


On the Tools menu, click Generate Local Resource.
Visual Web Developer creates a new folder named
App_LocalResources, and within the App_LocalResources folder, a
new file named Sample.aspx.resx. If you named your page something
other than Sample.aspx, the .resx file will reflect whatever name you
chose. When using implicit localization, resource file names are
based on individual page names.
Switch to Source view to see the changes to your control
declarations.
Visual Web Developer has added an attribute to your controls to
retrieve their values from your newly created resource file. For
example, the Button control's markup has a new meta:resourcekey
attribute.

The resource file is used as the default resource file for all requests. (It is
the resource file for the fallback culture.) If no culture is specified by the
browser, or if the browser request includes a language or culture that you
do not support, resource values are pulled from this default file.
Now that the resource file is created, you can place localized text within it
by using the Resource Editor.
To edit the resource file by using the Resource Editor
In Solution Explorer, open Sample.aspx.resx.
In the Resource Editor, under Value, are the Text properties for each of
the controls that you placed onto your page. Changing the value here will
change the value for the default culture.
Set ButtonResource1.Text to Edited English Text.
Save the file.
Now you can test the page.

To test the page


Press CTRL+F5 to run the page.
The text you provided in the Resource Editor is shown as the label for Button1. When
using implicit localization, syntax properties in resource files will override properties
specified in the page itself.

Adding Other Cultures


To create a culturally neutral French language file
In Solution Explorer, right-click the Sample.aspx.resx file, and then click
Copy.
Right-click the App_LocalResourcesfolder, and then click Paste.
Visual Web Developer creates a file named Copy of Sample.aspx.resx.
Right-click the Copy of Sample.aspx.resx file, click Rename, and then
type Sample.aspx.fr.resx.
Sample.aspx.fr.resx indicates a file for culturally neutral French
language text.
Open Sample.aspx.fr.resx.
For the Button, Label, and TextBox controls, set Text to French Button,
French Label, and French TextBox, respectively.
Save the file.

Testing with an Alternate Language Setting


Before you can see if this new resource file is used by ASP.NET, you must alter
your browser settings to request the desired culture.

To change your browser's language settings


In Microsoft Internet Explorer, on the Tools menu, click Internet Options.
Click Languages.
In the Language Preference dialog box, click Add.
In the Add Language dialog box, under Languages, click French (France) [fr], and
then click OK.
Click Add and add Spanish (Mexico) [es-mx] to the list of languages.
Click Add and add Arabic (Egypt) [ar-eg] to the list of languages.
You will use Spanish and Arabic for testing later in this walkthrough.
In the Language Preference dialog box, under Language, click French (France)
[fr], click Move Up, and then click OK.

To test the page


In Visual Web Developer, press CTRL+F5
to run the page.
The page is refreshed with values from the
localized French language file instead of
the English version.

Explicit Localization with ASP.NET


However, at times you want to have more direct
control over how properties are set. For this, instead
of using implicit localization, you can use explicit
localization. With explicit localization, you set the
value of a property by using an expression pointing
to a resource file. When the page runs, the
expression is evaluated, the value is read from the
specified resource file, and then the value is used to
set the property.

Explicit localization is useful when you have large


bodies of text or custom messages you want to
localize, in addition to controls and labels. For
example, you could develop a series of localized
welcome and thank you messages for an ecommerce site, and use explicit declarative
expressions to place this text on your pages.
Additionally, explicit localization allows you to
maintain a single set of localized resource files
rather than maintaining a separate set of files for
each page.

To create a resource file

In Solution Explorer, right-click the root of your Web site, click Add
ASP.NET Folder, and then click App_GlobalResources.
Right-click the App_GlobalResources folder, and then click Add New
Item.
Under Visual Studio installed templates, click Resource File.
In the Name box, type LocalizedText.resx, and then click Add.
The LocalizedText.resx file will act as the resource for the fallback
culture.
Create a second .resx file and name it LocalizedText.fr.resx.
The string "fr" identifies the file as the resource to use if the browser's
language is set to French (regardless of culture).
Create a third .resx file and name it LocalizedText.es-mx.resx.
The string "es-mx" identifies the file as file as the resource to use if the
browser's language is set to Spanish (Mexico).

Open the LocalizedText.resx file.


In the first row under the Name column type Msg1.
In the first row under the Value column, type Hello.
Save the file and close it.
Open the LocalizedText.fr.resx, create a resource string
named Msg1, assign it the value Bon jour. When you
are finished, save and close the file.
Open the LocalizedText.es-mx.resx, create a resource
string named Msg1, assign it the value Buenos das.
When you are finished, save and close the file.
You have created three values for the resource named Msg1.
ASP.NET will read the value out of the appropriate resource file
based on what language the browser is set to.

Now that your resource file is created, you can return to the page and add
controls that will reference the resource.

To add a Label control to the page


Switch to Sample.aspx, and then switch to Design view.
Drag another Label control onto the page.
Right-click the Label control, click Properties, and then click the ellipsis ()
button in the Expressions box.
The Expressions dialog box appears.
In the Bindable Properties list, click Text.
In the Expression Type list, select Resources.
Under Expression Properties, set ClassKey to LocalizedText and
ResourceKey to Msg1.
Click OK.
Switch to Source view.
Your label's text attribute now has an explicit expression stating the base file
from which to retrieve the resource and the key to select.

With the resource file completed, and the declarative expression added, you can test the page. After the last
test, your browser was set to report French as its language preference. During the testing, you will change
the browser's language several times.

To test the page


Press CTRL+F5 to run the page.
The French-language version of the text you provided in the Resource Editor is shown as the text for the
Label control.
In Microsoft Internet Explorer, on the Tools menu, click Internet Options.
Click Languages.
In the Language Preference dialog box, move Spanish (Mexico) [es-mx] to the top of the list of languages.
When you are finished, click OK and close the Internet Options dialog box.
Press F5 to refresh the browser.
The Spanish version of the text is displayed.
Change the language to Arabic and then press F5 to refresh the page again.
This time, the text is displayed in the language you used in the fallback resource file. Because you did not
create a file LocalizedText.ar-eg.resx, ASP.NET was not able to locate text that matched the language and
culture reported by the browser, so it used the fallback resource file.
When you are finished testing the page, set the language back to the language your preferred language

You might also like