Professional Documents
Culture Documents
ASP Dot Net Presentation
ASP Dot Net Presentation
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:
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.
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
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.
Second example
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 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.
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.
{
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.
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
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
EVENT
DESCRIPTION
ActiveStepChanged :
EVENT
DESCRIPTION
FinishButtonClick :
Response.Write("clicked finish");
EVENT
DESCRIPTION
NextButtonClick :
PreviousButtonClick :
EVENT
DESCRIPTION
SideBarButtonClick:
Control to use
Description
Required entry
RequiredFieldValidator
Comparison to a value
Range checking
RangeValidator
Pattern matching
RegularExpression
User-defined
CustomValidator
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.
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.
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>
Master/client
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.
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.
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
Integrated
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
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.
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
=="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
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
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.
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.
<html>
<head>
<script language="javascript">
function showmsg()
{
alert("clicled");
}
</script>
</head>
<body>
<input type="button" value="Click me" onclick="showmsg()">
</body>
</html>
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.
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
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).
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
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
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"]);
}
}
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.
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
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.
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.
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.
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.
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.
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>
Web.config
<anonymousIdentification enabled ="true"/>
<profile>
<properties>
<add name="fnm"/>
<add name="snm"/>
<add name="state"
allowAnonymous="true "/>
</properties>
</profile>
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.
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
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.
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.
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
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
Asynchronous
response
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)
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.
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>
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:
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.
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.
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.
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
\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 .
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.
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>");
}
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>");
To automatically generate a
resource file
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.
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).
Now that your resource file is created, you can return to the page and add
controls that will reference the resource.
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.