-
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.
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
-
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 controlUse 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.
-
3
-
Hyperlink server controlCreates a link on the page that users
can click to move to another page.
-
Place HoldersThis 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 controlThis 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.
-
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 + ""+
FileUpload1.PostedFile.ContentLength +"kb "+"Content type :" +
FileUpload1.PostedFile.ContentType ; }
catch (Exception ex) { Label1.Text ="error--->" +
ex.Message.ToString(); } else { Label1.Text ="u have not specified
file" ; }
}Second example
-
Image ControlThey 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 BUTTONYou 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 MAPSImageMap 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 EventsThe 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
arrayprotected 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("u
selected" + DropDownList1.SelectedValue.ToString() + ":" +
ListBox1.SelectedValue.ToString() + ""); }
-
ListBoxThe 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
-
Calendar server controlThe 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 selectionsBy 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()+""); for (int i = 0; i
< Calendar1.SelectedDates.Count; i++) { Label1.Text +=
Calendar1.SelectedDates[i].ToShortDateString() + ""; } }
-
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 calendarThe 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(" user grioup meeting"));
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 BulletedList control can be
constructed of any number of < asp:ListItem > controls or can
bedata-bound to a data source of some kind andpopulated based upon
the contentsretrieved. Below listing shows simple Bulleted list
In this example we declare one BulletedList control, and one
DropDownList control in an .aspxfile. Then we create an event
handler for the SelectedIndexChanged event which displaysBullet
Style in a BulletedList control.
-
Multiview and view server controlThe 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
-
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 control.The 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.
this is second step
-
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.
EVENTDESCRIPTIONActiveStepChanged : 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; }
-
EVENTDESCRIPTION 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"); }
-
EVENTDESCRIPTION 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)); }
-
EVENTDESCRIPTION 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:
-
protected void wizardstep3_Activate(object sender, EventArgs e)
{ Label5.Text = "firstname:" + TextBox1.Text.ToString() + "" +
"last name:" + TextBox2.Text.ToString() + "" + "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 validationControl to
useDescriptionRequired entryRequiredFieldValidatorEnsures that the
user does not skip an entry. Comparison to a
valueCompareValidatorCompares 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 checkingRangeValidatorChecks 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
matchingRegularExpressionChecks 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-definedCustomValidatorChecks 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 ControlsLogin 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 controlThis 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 ControlIs responsible for displaying the name of the
presently authenticated user. It uses page.user.identity to return
the value for the users name.
-
Password recoveryIs used to retrieve or reset the passwordof the
user.
-
Using Login ControlPlace 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
-
Working with databaseGridView 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 detailviewPlace
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
-
Binding Standard ControlListbox,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 DataReaderYou 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 ControlThe 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 user-defined
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.
-
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 getmovies() { return new List { 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 LINQLINQ 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 LINQVar 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 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 LINQWe 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 LINQVar 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 namesWe 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 LINQVar 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 LINQLINQ 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 getmovies() { return new List { 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 filtersLINQ also supports adding qury filters using a
familiar SQL-Like WHERE syntaxPlace 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
getmovies() { return new List { 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 groupingLINQ 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 getemp() { return new List { 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"}, new emp{nm ="michel",sal =32000,comm =620, desg ="mkt"}
}; }
-
LINQ to XMLThe 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
-
smith 2345 clerk
blake 4500 mgr
killer 3500 mkt
-
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 LINQprotected void Page_Load(object
sender, EventArgs e) { var qry = from m in
XElement.Load(MapPath("XMLFile.xml")).Elements("empdata") select
new { nm = (string)m.Element("nm"), sal = (int)m.Element("sal"),
desig = (string)m.Element("desig") }; GridView1.DataSource = qry;
GridView1.DataBind(); }
-
LINQ TO SQLLINQ 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 sqlprotected 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 CONTROLSCLIEND 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
-
function showmsg(){alert("clicled");}
-
Master pages and themesNeed 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 pageRight 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 themesApplying 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.
-
stepsRight-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.
-
Now to test this skin, we also need to add these controls in the
page.
Code in default.aspx page
-
Applying theme to an entire applicationIn 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.
-
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 themesIn 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 tage of the page(basically all
text).
-
Applying themes at run timeConsider 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.
-
Code for simple.skin
-
Here is the default.aspx file
Untitled Page
select theme: simple inverse
-
protected void Page_PreInit(object sender, EventArgs e) {
Page.Theme = Request.QueryString["theme"]; }
-
STATE MANAGEMENTPurpose 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 pageProtected 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.cspublic 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") =
valueAnd 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.csPrivate Sub Page_Load(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Label1.Text = "Welcome to " & Session("msg") End Sub
-
SecurityAuthentication 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 node:You
can use the node in the applications web.config file to set the
type of authentication ur Asp.NET application requires.
-
ProviderdescriptionWindowswindows authentication is used
together with IIS authentication. This is default
setting.Formsrequest that are not authenticated are redirected to
an html form using HTTP client-side redirection. The user provide
his login information and submits the form.Passporta centeralized
authentication service provided by Microsoft that offers single
login and core profile services for member site.
-
Windows-based authenticationWindows based authentication is
handled between the windows server where
-
Form based authenticationIs 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.
-
U must apply this tructure to the web.config file. First using
the 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 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
-
Authenticating against values contained in the web.config
filePrevious 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 element in web.config
that u worked can also take sub-element . The sub-element allows
you to specify unm and pwd combination directly in the web.config
file.
-
Modify web.config file to add unm/pwd values
-
The 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(TextBox1.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.
-
UDDIUniversal Discovery Description and Integration is like the
"Yellow Pages" of Web services.
-
User profilesUser 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 userWhen 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 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 element, which is available in the element.
-
Web.config(working with the single profile[authenticated])
-
Defining multiple profilesWeve 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
-
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; }}
-
cachingCaching 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 techniquesOutput
caching(page level caching)Partial cachingData 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:
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 varybyparamThe 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.csprotected 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.
-
Partial-page cachingIts 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)---
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 cachingData 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:Adding items to cache:
cache(myvalue)=valueRetrieving data from
cache:value=cache(myvalue)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 managementBy 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 stateIt 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 - stateEach 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 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 stateThe 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.asaxThe 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 AJAXAJAX 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
thick-client 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 AJAXEnd 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 AJAXWindows ServerAsp.NET ProcessingengineEnd users
internet browserrequestresponseASP.NET AJAX
LibraryAsynchronousrequestAsynchronousresponseEnd users client
computer
-
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 AJAXDesign 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 controlThe 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
Libraryscripts to the browser and coordinating partial-page
updatesthat are enabled by using UpdatePanel controlsThe
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 controlBy 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();}}
-
Red Green Blue Yellow Silver
-
Updatepanel control..contd..The ElementThere 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 controlPut the label and the button control inside the
updatepanel control
-
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
element has two possible sub-elements: and the element. Any content
that needs to be changed with the asynchronous page postbacks
should be contained within the section of the updatepanel
control.By default, any type of control trigger(normally page
postback ) that is contained within the 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 elementPrevious 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 section of the
updatepanel control, then you have to include a section within the
control.
-
Using trigger to cause asynchronous page postback
-
C#: protected void Button2_Click(object sender, EventArgs e) {
Label2.Text = "this button was clicked on :" +
DateTime.Now.ToString(); }
-
Timer controlThe 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 controlUpdateProgress 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 partial-page 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 ControlYou 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 pageCreate a new page and switch to Design
view.In the AJAX Extensions tab of the toolbox, double-click the
ScriptManager control to add it to the page. Double click the
UpdatePanel control to add it to the page.
-
Double-click the UpdateProgress control to add it to the page.
Inside the UpdateProgress control, add the text Processing.Inside
the UpdatePanel control add a Label control and a Button control.
Set the Text property of the Label control to Initial Page
Rendered.
-
Double click the Button control to add a handler for the
button's Click event.Add the following code to the Click handler,
which artificially creates a three-second 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 ControlsOne 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 pageCreate a new page and switch to
Design view.In the AJAX Extensions tab of the toolbox, double-click
the ScriptManager control to add it to the page. Double-click the
UpdatePanel control two times to add two instances of the control
to the page.
-
In each UpdatePanel control, add a Label control and a Button
control. Set the Text property of both Label controls to Panel
Initially Rendered.
-
Double-click each Button control to add a handler for each
button's Click event.Add the following code to each Click handler,
which artificially creates a three-second 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(); }
-
Switch to Design view. Click inside the first UpdatePanel
control and add an UpdateProgress control.Inside the UpdateProgress
control, add the text Panel1 Updating.This sets the
ProgressTemplate property.Select the UpdateProgress control, and in
the Properties window, set the AssociatedUpdatePanelID property to
UpdatePanel1.
-
Click inside the second UpdatePanel control and add a second
UpdateProgress control.Set the text of the UpdateProgress control
to Panel2 Updating and set its AssociatedUpdatePanelID property to
UpdatePanel2.
-
Save your changes, and then press CTRL+F5 to view the page in a
browser.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 folderWhen 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 FolderThe \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 LocalizationGlobalization 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 codedescriptionEn-USEnglish lang, united statesEn-GBenf
lang., united kingdom (great britian)En-AUeng lang.,AustraliaNote:
to c more go to msdn library and search for culture info class
which containg culture code and its description.
-
Asp.Net threadsWhen 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()+"");
Response.Write(" culture parent name:" + ci.Parent
.Name.ToString()+""); Response.Write(" culture display name:" +
ci.DisplayName.ToString() + ""); Response.Write(" culture english
name:" + ci.EnglishName.ToString() + ""); Response.Write(" culture
native name:" + ci.NativeName.ToString() + ""); Response.Write("
calender type:" + ci.Calendar.ToString() + "");
}
-
Changing the culture of the thread using the cultureinfo
objectSystem.threading.thread.currentthread.currentculture=new
cultureinfo(th-TH);CultureInfo ci =
System.Threading.Thread.CurrentThread.CurrentCulture;
Response.Write("current culture name:" + ci.Name.ToString()+"");
Response.Write(" culture parent name:" + ci.Parent
.Name.ToString()+""); Response.Write(" culture display name:" +
ci.DisplayName.ToString() + ""); Response.Write(" culture english
name:" + ci.EnglishName.ToString() + ""); Response.Write(" culture
native name:" + ci.NativeName.ToString() + "");
Response.Write(" calender type:" + ci.Calendar.ToString() +
"");
-
Defining the section in the web.config file
-
Defining the culture at the page level @page using directive
-
ASP.NET 3.5 Resource filesWhen 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.NETAn 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.NETIn 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 Edi