ASP.NET
ASP.NET is
a technology for building powerful, dynamic Web applications and is part of the
.NET Framework.
.NET is
language independent, which means you can use any .NET supported language to
make .NET applications. The most common languages for writing ASP.NET
applications are C# and VB.NET. you can do all the same things, no matter if
you're using C# or VB.NET.
What is Classic ASP?
Microsoft's previous server side scripting technology ASP
(Active Server Pages) is now often called classic ASP.
ASP 3.0 was the last version of classic ASP.
ASP.NET is
the next generation ASP, but it's not an upgraded version of ASP.
ASP.NET is an entirely new technology for server-side
scripting. It was written from the ground up and is not backward compatible
with classic ASP.
In
Classic ASP we could only write Inline Code but in ASP.NET we can write both
Inline code and Code behind.
ASP.NET is
an event-driven way of making web applications. With Classic ASP, you have one
file, which is executed line after line, from start to end. However, ASP.NET is
very different. Here we have events, which are either activated by the user in
one way or another. Ex: the Page_Load method. Actually, this is an event, which
the Page class calls when the page is loaded.
What
is ASP.NET?
ASP.NET is a server side scripting technology that enables
scripts (embedded in web pages) to be executed by an Internet server.
·
ASP.NET is a Microsoft Technology
·
ASP stands for Active Server Pages
·
ASP.NET is a program that runs inside IIS
·
IIS (Internet Information Services) is
Microsoft's Internet server
·
IIS comes as a free component with Windows
servers
·
An
ASP.NET file is just the same as an HTML file
·
An ASP.NET file can contain HTML, XML, and
scripts
·
Scripts in an ASP.NET file are executed on the
server
·
An ASP.NET file has the file extension
".aspx"
The .NET Framework is the infrastructure for the Microsoft
.NET platform.
The .NET Framework is an environment for building,
deploying, and running Web applications and Web Services.
The .NET Framework
consists of 3 main parts:
Programming languages:
·
C# (Pronounced C sharp)
·
Visual Basic (VB .NET)
·
J# (Pronounced J sharp)
Server technologies and client technologies:
·
ASP .NET (Active Server Pages)
·
Windows Forms (Windows desktop solutions)
·
Compact Framework (PDA / Mobile solutions)
Development environments:
·
Visual Studio .NET (VS .NET)
·
Visual Web Developer
ASP.NET Features
ASP.NET
has better language support, a large set of new controls, XML-based components,
and better user authentication.
ASP.NET provides increased performance by running compiled
code.
ASP.NET code is not fully backward compatible with ASP
ASP.NET
uses ADO.NET.
ASP.NET supports full Visual Basic, not VBScript.
ASP.NET supports C# (C sharp) and C++.
ASP.NET supports JScript.
First Web Site
NewFile.aspx
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
>
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat ="server">
<div>
<asp:Label runat="server"
id="lblHelloWorld"></asp:Label>
</div>
</form>
</body>
</html>
using System;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
public partial class NewFile : System.Web.UI.Page
{
protected void Page_Load(object
sender, EventArgs e)
{
lblHelloWorld.Text = "Hello world!";
}
}
The name of this class is "NewFile",
and the : (colon) tells us that this class inherits from the Page class in the
System.Web.UI namespace. This means that our page can already do a bunch of
things, without any programming, because it inherits methods and properties from
another class. All ASP.NET pages inherits from the Page class, or another class
which inherits from the Page class.
ASP.NET is an event-driven way of making
web applications. With Classic ASP, you
have one file, which is executed line after line, from start to end. However,
ASP.NET is very different. Here we have events, which are either activated by
the user in one way or another. In the previous example, we used the Page_Load
method. Actually, this is an event, which the Page class calls when the page is
loaded.
<form id="form1" runat="server">
<div>
<asp:Label runat="server"
id="HelloWorldLabel"></asp:Label>
<br></br>
<asp:TextBox runat="server" id="TextInput" />
<asp:Button runat="server" id="GreetButton" text="Say Hello!" />
</div>
</form>
protected void Page_Load(object sender, EventArgs
e)
{
HelloWorldLabel.Text = "Hello, " + TextInput.Text;
}
ASP.NET - Server Controls
Server controls are tags that are understood by the
server.
There are three kinds of server controls:
·
HTML Server Controls - Traditional HTML tags
·
Web Server Controls - New ASP.NET tags
·
Validation Server Controls - For input
validation
HTML Server Controls
HTML server controls are HTML tags understood by the
server.
HTML elements in ASP.NET files are, by default, treated as
text. To make these elements programmable, add a runat="server"
attribute to the HTML element. This attribute indicates that the element should
be treated as a server control. The id attribute is added to identify the
server control. The id reference can be used to manipulate the server control
at run time.
Note: All HTML
server controls must be within a <form> tag with the
runat="server" attribute. The runat="server" attribute
indicates that the form should be processed on the server. It also indicates
that the enclosed controls can be accessed by server scripts.
Example:
<a id="link1"
runat="server">Hello World!</a>
<Button id=”link1" runat="server"
Text=”Button1” />
Web Server Controls
Web server controls are special ASP.NET tags understood by
the server.
Like HTML server controls, Web server controls are also
created on the server and they require a runat="server" attribute to
work. However, Web server controls do not necessarily map to any existing HTML
elements and they may represent more complex elements.
The syntax for creating a Web server control is:
<asp:control_name
id="some_id" runat="server" />
|
In the following example we declare a Button server control
in an .aspx file. Then we create an event handler for the Click event which
changes the text on the button:
<script runat="server">
Sub submit(Source As Object, e As EventArgs) button1.Text="You clicked me!" End Sub </script> <html> <body> <form runat="server"> <asp:Button id="button1" Text="Click me!" runat="server" OnClick="submit"/> </form></body></html> |
Validation Controls
Validation server controls are used to validate
user-input. If the user-input does not pass validation, it will display an
error message to the user.
Each validation control performs a specific type of
validation (like validating against a specific value or a range of values).
By default, page validation is performed when a Button,
ImageButton, or LinkButton control is clicked. You can prevent validation when
a button control is clicked by setting the CausesValidation property to false.
The syntax for creating a Validation server control is:
<asp:control_name
id="some_id" runat="server" />
The different types of Validation Controls are
Compares the value of one input control to the value
of another input control or to a fixed value
|
In the following example we declare one TextBox control,
one Button control, and one RangeValidator control in an .aspx file. If
validation fails, the text "The value must be from 1 to 100!" will be
displayed in the RangeValidator control
Example:
<html>
<body>
<form runat="server">
<p>Enter a number from 1 to 100:
<asp:TextBox id="tbox1" runat="server" />
<br /><br />
<asp:Button Text="Submit" runat="server" />
</p>
<p>
<asp:RangeValidator
ControlToValidate="tbox1"
MinimumValue="1"
MaximumValue="100"
Type="Integer"
Text="The value must be from 1 to 100!"
runat="server" />
</p>
</form>
</body>
</html>
<body>
<form runat="server">
<p>Enter a number from 1 to 100:
<asp:TextBox id="tbox1" runat="server" />
<br /><br />
<asp:Button Text="Submit" runat="server" />
</p>
<p>
<asp:RangeValidator
ControlToValidate="tbox1"
MinimumValue="1"
MaximumValue="100"
Type="Integer"
Text="The value must be from 1 to 100!"
runat="server" />
</p>
</form>
</body>
</html>
Compares the value of one input control to
the value of another input control or to a fixed value
Small number:
<br />
<asp:TextBox runat="server" id="txtSmallNumber"
/>
<br
/><br />
Big number:
<br />
<asp:TextBox runat="server" id="txtBigNumber"
/><br />
<asp:CompareValidator runat="server" id="Numbers"
controltovalidate="txtSmallNumber"
controltocompare="txtBigNumber"
operator="LessThan" type="Integer"
errormessage="The first number should be smaller than the second
number!" /><br />
Ensures that the value of an input control matches a
specified pattern 4 digit number:
<asp:TextBox runat="server" id="txtNumber"
/>
<asp:RegularExpressionValidator runat="server"
id="rexNumber"
controltovalidate="txtNumber" validationexpression="^[0-9]{4}$"
errormessage="Please enter a 4 digit
number!" />
<br />
Allows you to write a method to
handle the validation of the value entered
Custom
text:
<br />
<asp:TextBox runat="server" id="txtNumber"
/>
<asp:CustomValidator runat="server" id="cusCustom"
controltovalidate="txtCustom" onservervalidate="cusCustom_ServerValidate"
errormessage="The text must be exactly 8 characters long!"
/>
<br />
The only unknown property is the onservervalidate event.
It's used to reference a method from CodeBehind which will handle the
validation. Switch to our CodeBehind file and add the following method:
protected void
cusCustom_ServerValidate(object sender,
ServerValidateEventArgs e)
{
if(e.Value.Length == 8)
e.IsValid = true;
else
e.IsValid = false;
}
Makes an input control a required
field
<td>id</td>
<td><asp:textbox id="atid" runat="server"
/>
<asp:RequiredFieldValidator
runat="server" id="vldid"
ControlToValidate="atid" ErrorMessage="id is required" display="Static">
This Required Field!</asp:RequiredFieldValidator></td>
Displays a report of all validation
errors occurred in a Web page
Validation Summary can be displayed as:
·
BulletList
·
List
·
SingleParagraph
<asp:ValidationSummary
HeaderText="You must enter a value in the following fields:"
DisplayMode="BulletList"
EnableClientScript="true"
runat="server"/>
Asp.Net 2.0 Page Directives
Asp.Net Page directives are
something that is a part of every asp.net pages. Page directives are
instructions, inserted at the top of an ASP.NET page, to control the behavior
of the asp.net pages.
<%@ Page Language="C#"
AutoEventWireup="true" CodeFile="Sample.aspx.cs"
Inherits="Sample" Title="Sample Page Title" %>
Totally there are 11 types of Pages directives in Asp.Net
2.0. Some directives are very important without which we cannot develop any web
applications in Asp.Net. Some directives are used occasionally according to its
necessity. When used, directives can be located anywhere in an .aspx or .ascx
file, though standard practice is to include them at the beginning of the file.
Asp.Net web form page framework supports the following
directives
1. @Page
2. @Master
3. @Control
4. @Register
5. @Reference
6. @PreviousPageType
7. @OutputCache
8. @Import
9. @Implements
10. @Assembly
11. @MasterType
1. @Page
2. @Master
3. @Control
4. @Register
5. @Reference
6. @PreviousPageType
7. @OutputCache
8. @Import
9. @Implements
10. @Assembly
11. @MasterType
@Page Directive
The @Page directive enables you to specify attributes and values for an Asp.Net Page to be used when the page is parsed and compiled. Every .aspx files should include this @Page directive to execute.
The @Page directive enables you to specify attributes and values for an Asp.Net Page to be used when the page is parsed and compiled. Every .aspx files should include this @Page directive to execute.
Language:
This attribute tells the compiler about the language being used in the
code-behind. Values can represent any .NET-supported language, including Visual
Basic, C#, or JScript .NET.
AutoEventWireup: For every page there is an automatic way to bind the events to methods in the same .aspx file or in code behind. The default value is true.
CodeFile: Specifies the code-behid file with which the page is associated.
AutoEventWireup: For every page there is an automatic way to bind the events to methods in the same .aspx file or in code behind. The default value is true.
CodeFile: Specifies the code-behid file with which the page is associated.
Title:
To set the page title other than what is specified in the master page.
Culture: Specifies the culture setting of the page. If you set to auto, enables the page to automatically detect the culture required for the page.
Culture: Specifies the culture setting of the page. If you set to auto, enables the page to automatically detect the culture required for the page.
MasterPageFile:
Specify the location of the MasterPage file to be used with the current Asp.Net
page.
EnableViewState: Indicates whether view state is maintained across page requests. true if view state is maintained; otherwise, false. The default is true.
ErrorPage: Specifies a target URL for redirection if an unhandled page exception occurs.
EnableViewState: Indicates whether view state is maintained across page requests. true if view state is maintained; otherwise, false. The default is true.
ErrorPage: Specifies a target URL for redirection if an unhandled page exception occurs.
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Sample.aspx.cs" Inherits="Sample"
Title="Sample Page Title" %>
@Master Directive
The @Master directive is quite similar to the @Page directive. The @Master directive belongs to Master Pages that is .master files. The master page will be used in conjunction of any number of content pages. So the content pages can the inherits the attributes of the master page.
<%@ Master Language="C#"
AutoEventWireup="true" CodeFile="WebMaster.master.cs"
Inherits="WebMaster" %>
@Register Directive
The @Register directive associates aliases with namespaces and class names for notation in custom server control syntax. When you drag and drop a user control onto your .aspx pages, the Visual Studio 2005 automatically creates an @Register directive at the top of the page.
<%@ Register Src="Yourusercontrol.ascx"
TagName=" Yourusercontrol " TagPrefix="uc1"
Src="~\usercontrol\usercontrol1.ascx" %>
Caching
One of the really cool features of ASP.NET is the caching.
With other technologies, caching usually requires some extra software or at
least complicated code, but with ASP.NET 2.0, it's easier than ever before. You
can use two different kinds of caching - output caching and standard caching.
Ex:
<%@
Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head runat="server">
<title>Caching</title>
</head>
<body>
<form id="form1" runat="server">
<%= DateTime.Now.ToString() %>
</form>
</body>
</html>
Try running the project and reload the page
a couple of times. As you will see, the time is refreshed on each reload. Now,
add the following line as line number 2 to our example:
<%@
OutputCache duration="10" varybyparam="None" %>
Run our project again, and reload the page
a number of times. As you will see, the time is only refreshed every 10
seconds. Duration parameter tells the page how many seconds to cache the
content. Each time the page is requested, ASP.NET checks if the page is in the
cache, and if it is, whether or not it has expired. It's served from the cache
if it isn't expired - if it is, the page is removed from the cache and the page
is generated from scratch and then placed in the cache.
The varybyparam is a required parameter of the OutputCache directive. It specifies a list of parameters which the the cache should be varied by. For instance, if you set it to "p", the cache is now depending on the value of the parameter p. Try changing our example to something like this:Now, run our example again, and try clicking the links. They each now have their own timestamp, based on when you first accessed the page. The cache is depending on the value of the p parameter! You can specify multiple parameters by seperating them with a semicolon.
The varybyparam is a required parameter of the OutputCache directive. It specifies a list of parameters which the the cache should be varied by. For instance, if you set it to "p", the cache is now depending on the value of the parameter p. Try changing our example to something like this:Now, run our example again, and try clicking the links. They each now have their own timestamp, based on when you first accessed the page. The cache is depending on the value of the p parameter! You can specify multiple parameters by seperating them with a semicolon.
The varybyparam is a required parameter of
the OutputCache directive. It specifies a list of parameters which the the
cache should be varied by. For instance, if you set it to "p", the
cache is now depending on the value of the parameter p. Try changing our example
to something like this:
OutputCache
- varybyparam
<%@
OutputCache duration="10" varybyparam="P" %>
<form id="form1" runat="server">
<%= DateTime.Now.ToString()
%><br
/>
<a href="?p=1">1</a><br />
<a href="?p=2">2</a><br />
<a href="?p=3">3</a><br />
</form>
They each now have their own timestamp,
based on when you first accessed the page. The cache is depending on the value
of the p parameter
OutputCache
- varybycontrol
The varybycontrol does exactly what it says
- it varies the cache depending on the value of the specified control.
<%@
OutputCache duration="10" varybyparam="none"
varybycontrol="NameOfControl" %>
OutputCache
- varybycustom
<%@
OutputCache duration="120" varybyparam="None"
varybycustom="Browser" %>
for this to work you need to override the
method in global.asax file
public override string
GetVaryByCustomString(HttpContext context, string custom)
{
if(custom == "Browser")
{
return context.Request.Browser.Browser;
}
return String.Empty;
}
OutputCache
- varybyheader
This one allows you to vary the content based on one or more of the headers that browser send.
This one allows you to vary the content based on one or more of the headers that browser send.
<%@
OutputCache duration="120" varybyparam="None"
varybyheader="Accept-Language" %>
This will vary cache based on the
Accept-Language header, which tells the server which languages the user accepts
and prefers.
Data Caching
ASP.NET also supports caching of data as objects. We can
store objects in memory and use them across various pages in our application.
This feature is implemented using the Cache
class. This cache has a lifetime equivalent to that of the application. Objects
can be stored as name value pairs in the cache. A string value can be inserted
into the cache as follows:
The stored string value can be retrieved like this:
Label1.Text= Cache["name"].ToString();
COOKIES
Cookies are small pieces of text, stored on the client's
computer to be used only by the website setting the cookies. This allows web applications
to save information for the user, and then re-use it on each page if needed.
Here is an example where we save a users choice of
background color:
<%@ Page Language="C#"
AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<html xmlns="http://www.w3.org/1999/xhtml"
>
<head runat="server">
<title>Cookies</title>
</head>
<body runat="server"
id="BodyTag">
<form id="form1" runat="server">
<asp:DropDownList runat="server" id="ColorSelector" autopostback="true" onselectedindexchanged="ColorSelector_IndexChanged">
<asp:ListItem value="White" selected="True">Select color...</asp:ListItem>
<asp:ListItem value="Red">Red</asp:ListItem>
<asp:ListItem value="Green">Green</asp:ListItem>
<asp:ListItem value="Blue">Blue</asp:ListItem>
</asp:DropDownList>
</form>
</body>
</html>
The page simply contains a DropDownList control, which
automatically posts back each time a new item is selected. It has 3 different
colors, besides the default one, which is simply white. Once a new item is
selected, the ColorSelector_IndexChanged method is fired, from our Code Behind
file:
using System;
using System.Data;
using System.Web;
public partial class
_Default : System.Web.UI.Page
{
protected void Page_Load(object
sender, EventArgs e)
{
if(Request.Cookies["BackgroundColor"] != null)
{
ColorSelector.SelectedValue =
Request.Cookies["BackgroundColor"].Value;
BodyTag.Style["background-color"] = ColorSelector.SelectedValue;
}
}
protected void ColorSelector_IndexChanged(object sender, EventArgs
e)
{
BodyTag.Style["background-color"] =
ColorSelector.SelectedValue;
HttpCookie cookie = new
HttpCookie("BackgroundColor");
cookie.Value =
ColorSelector.SelectedValue;
cookie.Expires = DateTime.Now.AddHours(1);
Response.SetCookie(cookie);
}
}
Okay, two different parts to be explained here. First, the
Page_Load method, which is called on each page request. Here we check for a
cookie to tell us which background color should be used. If we find it, we set
the value of our dropdown list to reflect this, as well as the background color
of the page, simply by accessing the style attribute of the body tag.
Then we have the ColorSelector_IndexChanged method, which is called each time the user selects a new color. Here we set the background color of the page, and then we create a cookie, to hold the value for us. We allow it to expire after one hour, and then we set it by calling the SetCookie method on the Response object.
Try running the example, and set a color. Now close the browser, and start it up again. You will see that the choice of color is saved, and it will remain saved for an hour. However, nothing prevents you from saving the choice for much longer. Simply add a bigger value to the expiry date, or set an absolute value for it.
Then we have the ColorSelector_IndexChanged method, which is called each time the user selects a new color. Here we set the background color of the page, and then we create a cookie, to hold the value for us. We allow it to expire after one hour, and then we set it by calling the SetCookie method on the Response object.
Try running the example, and set a color. Now close the browser, and start it up again. You will see that the choice of color is saved, and it will remain saved for an hour. However, nothing prevents you from saving the choice for much longer. Simply add a bigger value to the expiry date, or set an absolute value for it.
SESSIONS
Sessions
can be used to store even complex data for the user just like cookies.
Actually, sessions will use cookies to store the data, unless you explicitly
tell it not to. Sessions can be used easily in ASP.NET with the Session object.
We will re-use the cookie example, and use sessions instead. Keep in mind
though, that sessions will expire after a certain amount of minutes, as
configured in the web.config file.
session
values are tied to an instance of your browser. If you close down the browser,
the saved value(s) will usually be "lost". Also, if the webserver
recycles the aspnet_wp.exe process, sessions are lost, since they are saved in
memory as well. Sessions can be also stored in separate StateServer or also in
SQL Server.
Same as
above cookies example
protected void
ColorSelector_IndexChanged(object sender, EventArgs e)
{
BodyTag.Style["background-color"] =
ColorSelector.SelectedValue;
Session["BackgroundColor"] = ColorSelector.SelectedValue;
}
VIEWSTATE
When a form is submitted in classic ASP, all form values
are cleared. Suppose you have submitted a form with a lot of information and
the server comes back with an error. You will have to go back to the form and
correct the information. You click the back button, and what happens.......ALL
form values are CLEARED, and you will have to start all over again! The site
did not maintain your ViewState.
When a form is submitted in ASP .NET, the form reappears
in the browser window together with all form values. How come? This is because
ASP .NET maintains your ViewState. The ViewState indicates the status of the
page when submitted to the server. The status is defined through a hidden field
placed on each page with a <form runat="server"> control.
Maintaining the ViewState is the default setting for
ASP.NET Web Forms. If you want to NOT maintain the ViewState, include the
directive <%@ Page EnableViewState="false" %> at the top of an
.aspx page or add the attribute EnableViewState="false" to any
control.
cookies and sessions can be
accessed from all your pages on your website, ViewState values are not carried
between pages. Here is a simple example of using the ViewState to carry values
between postbacks:
<%@ Page Language="C#"
AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<html xmlns="http://www.w3.org/1999/xhtml"
>
<head runat="server">
<title>ViewState</title>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox runat="server" id="NameField" />
<asp:Button runat="server" id="SubmitForm" onclick="SubmitForm_Click" text="Submit & set name"
/>
<asp:Button runat="server" id="RefreshPage" text="Just submit" />
<br /><br />
Name retrieved from ViewState:
<asp:Label runat="server" id="NameLabel" />
</form>
</body>
</html>
And the CodeBehind:
using System;
using System.Data;
using System.Web;
public partial class
_Default : System.Web.UI.Page
{
protected void Page_Load(object
sender, EventArgs e)
{
if(ViewState["NameOfUser"] != null)
NameLabel.Text = ViewState["NameOfUser"].ToString();
else
NameLabel.Text = "Not set
yet...";
}
protected void SubmitForm_Click(object sender, EventArgs
e)
{
ViewState["NameOfUser"] = NameField.Text;
NameLabel.Text = NameField.Text;
}
}
Try
running the project, enter your name in the textbox and press the first button.
The name will be saved in the ViewState and set to the Label as well. No magic
here at all. Now press the second button. This one does nothing at all
actually, it just posts back to the server. As you will notice, the NameLabel
still contains the name, but so does the textbox. The first thing is because of
us, while the textbox is maintained by ASP.NET it self. Try deleting the value
and pressing the second button again. You will see that the textbox is now cleared,
but our name label keeps the name, because the value we saved to the ViewState
is still there!
ViewState is pretty good for storing simple values for use in the form, but if you wish to save more complex data, and keep them from page to page, you should look into using cookies or sessions
ViewState is pretty good for storing simple values for use in the form, but if you wish to save more complex data, and keep them from page to page, you should look into using cookies or sessions
Data Binding
The following controls are list controls which support
data binding:
·
asp:RadioButtonList
·
asp:CheckBoxList
·
asp:DropDownList
·
asp:Listbox
The
selectable items in each of the above controls are usually defined by one or
more asp:ListItem controls
<asp:RadioButtonList id="countrylist" runat="server">
<asp:ListItem value="N" text="Norway" />
<asp:ListItem value="S" text="Sweden" />
<asp:ListItem value="F" text="France" />
<asp:ListItem value="I" text="Italy" />
</asp:RadioButtonList>
<asp:ListItem value="N" text="Norway" />
<asp:ListItem value="S" text="Sweden" />
<asp:ListItem value="F" text="France" />
<asp:ListItem value="I" text="Italy" />
</asp:RadioButtonList>
with data
binding we may use a separate source, like a database, an XML file, or a script
to fill the list with selectable items.
New
Features in NET 2.0
(a) Master
Pages
Master pages are introduced to remove
one of the most important deficiencies of earlier version
of ASP.NET. One thing that has become apparent in the earlier version of
ASP.NET is the lack of architecture for applying a consistent look and feel. In
earlier version of ASP.NET whenever a developer wants to
replicate a common functionality of a web page in other pages, the most
possible options he uses is creating a user control and then replicate the
functionality in other pages.
ASP.NET 2.0 aims to solve this problem by
introducing the concept of Master pages. First the developer needs to define a
master page containing the content that he wants to appear on other pages and
then use the ContentPlaceHolder controls to define the locations where the sub
pages can plug in the content of their own. The he has to
build the sub pages - .aspx pages – that reference the master using directives
like this one:
<%@Page MasterPageFile =
~/MyMasterPage.master” %>
In addition, an application can
designate a default Master Page in web.config as shown here:
<configuration>
<system.web>
<pages masterPageFile="~/ MyMasterPage.master " />
</system.web>
</configuration>
<system.web>
<pages masterPageFile="~/ MyMasterPage.master " />
</system.web>
</configuration>
(b) PreCompilation
By default,
ASP.NET web pages and code files are compiled dynamically when a first request
is made to the page. After the initial compilation, the compiled pages is
cached; the cache is used to satisfy the subsequent requests for the same page.
Even though this approach is flexible, when the page is requested for the first time, it requires a bit of extra time to
compile the code. You can avoid this overhead by leveraging a new feature known
as precompilation; by using this feature, you can compile an ASP.NET web site
before making the web site available to the users.
(c) Sharing
code in the application
In earlier version of ASP.NET, if you were to reference a reusable
component from your dot net application, you had to compile the assembly and
place it in the bin folder (or place it in the GAC) of the web application. But
now with ASP.NET 2.0, creating a reusable component is very simple and
straightforward. All you need to do is to create a component in a pre-defined
subdirectory called code. Any component placed in this directory will be
automatically compiled at runtime into a single assembly. This assembly is automatically
referenced and will be available to all the page in the site.
(d) Themes
and Skins
ASP.NET 2.0
introduces the concepts of Themes and Skins by means of which the look and feel
of the web pages can be enhanced to a great extent to make them visually catchy
and attractive.
A skin is a
set of visual attributes applied to a control type. A theme is a collection of
skins. There are a lot of predefined themes in ASP.NET 2.0. One can use it by
using the following line of code:
<%@ Page
Theme=”SmokeAndGlass” %>
The page
directive’s Them attribute declaratively applies a theme to a page. Themes can
also be applied programmatically using the page class’s Theme property
New Features in NET 3.0
• Windows Presentation Foundation (WPF)
• Windows Communication Foundation (WCF)
• Windows Workflow Foundation (WWF)
• Windows CardSpace (WCS)
• Windows Communication Foundation (WCF)
• Windows Workflow Foundation (WWF)
• Windows CardSpace (WCS)
New Features in NET 3.5
New Controls
- ListView
- Datapager
ASP.NET Merge Tool
New Assemblies
- System.Core.dll - Includes the implementation for LINQ to Objects
- System.Data.Linq.dll - Includes the implementation for LINQ to SQL
- System.Xml.Linq.dll - Includes the implementation for LINQ to XML
- System.Data.DataSetExtensions.dll - Includes the implementation for LINQ to DataSet
- System.Web.Extensions.dll: Includes the implementation for ASP.NET AJAX (new enhancements added) and new web controls as explained earlier.
- ASP.NET 3.5 provides better support to IIS7. IIS7 and ASP.NET 3.5 modules and handlers support unified configuration.
- You can have multiple versions of ASP.NET on the same machine.
- For those who are wondering what happened to ASP.NET 3.0, well there isn’t anything called ASP.NET 3.0.
- VS 2002 worked with ASP.NET 1.0, VS 2003 worked with ASP.NET 1.1, and VS 2005 worked with ASP.NET 2.0. However VS 2008 supports multi-targeting, i.e it works with ASP.NET 2.0, and ASP.NET 3.5.
New Features in NET4.0
Extensible Output Caching
Session state compression
View state mode for individual control
Page.MetaKeyword and Page.MetaDescription properties
Response.RedirectPermanent method
Routing in ASP.NET
Increase the URL character length
New syntax for Html Encode
Predictable Client IDs
Web.config file refactoring
Auto-Start ASP.NET applications
Improvements on Microsoft Ajax Library
Html Encoded Code Expressions
Chart control
Better control of the ViewState
Setting Meta Tags
Permanently Redirecting a Page
Session state compression
View state mode for individual control
Page.MetaKeyword and Page.MetaDescription properties
Response.RedirectPermanent method
Routing in ASP.NET
Increase the URL character length
New syntax for Html Encode
Predictable Client IDs
Web.config file refactoring
Auto-Start ASP.NET applications
Improvements on Microsoft Ajax Library
Html Encoded Code Expressions
Chart control
Better control of the ViewState
Setting Meta Tags
Permanently Redirecting a Page
ASP.NET
Page Life Cycle
First
to begin the life cycle we have to call method ProcessRequest(), then the cycle begins.
Req.ProcessRequest()
Process Request Method
does following things:
1.
Intialize the memory
2. Load
the view state
3.
Page execution and post back events
4.
Rendering HTML content
5. Releasing
the memory
Process Request Method executes set of
events for page class .These are called as Page life cycle events.
Diagram showing all the stages of a Page Life Cycle:
All the stages of Page Life Cycle and its relevant methods used are:
(1)
Page Initialization = Page_Init
(2)
View State Loading
= LoadViewState
(3)
PostBack data processing = LoadPostData
(4) Page Loading = Page_Load
(5)
PostBack Change Notification = RaisePostDataChangedEvent
(6)
PostBack Event Handling = RaisePostBackEvent
(7)
Page Pre Rendering Phase = Page_PreRender
(8)
View State Saving = SaveViewState
(9)
Page Rendering
= Page_Render
(10)
Page Unloading =
Page_UnLoad
General
Page Life-Cycle Stages
1) Page Request - This is the first stage, before the page life
cycle starts. Whenever a page is requested, ASP.NET detects whether the page is
to be requested, parsed and compiled or whether the page can be cached from the
system.
2) Start - In this stage,
properties such as Request and Response are set. Its also determined at this
stage whether the request is a new request or old, and thus it sets the
IsPostBack property in the Start stage of the page life cycle.
3) Page Initialization - Each
control of the page is assigned a unique identification ID. If there are
themes, they are applied. Note that during the Page Initialization stage,
neither postback data is loaded, nor any viewstate data is retrieved.
4) Load - If current request is a
postback, then control values are retrieved from their viewstate.
5) Validation - The validate
method of the validation controls is invoked. This sets the IsValid property of
the validation control.
6) PostBack Event Handling -
Event handlers are invoked, in case the request is a postback.
7) Rendering - Viewstate for the
page is saved. Then render method for each control is called. A textwriter
writes the output of the rendering stage to the output stream of the page's
Response property.
8) Unload - This is the last
stage in the page life cycle stages. It is invoked when the page is completely
rendered. Page properties like Respone and Request are unloaded.
Note that each stage has its own events within it. These events may be used by developers to handle their code. Listed below are page events that are used more frequently.
Note that each stage has its own events within it. These events may be used by developers to handle their code. Listed below are page events that are used more frequently.
Life-Cycle
Events
PreInit - Checks the IsPostBack property. To create or recreate dynamic controls. To set master pages dynamically. Gets and Sets profile propety values.
Init - Raised after all controls are initialized, and skin properties are set.
InitComplete - This event may be used, when we need to be sure that all initialization tasks are complete.
PreLoad - If processing on a control or a page is required before the Load event.
Load - invokes the OnLoad event on the page. The same is done for each child control on the page. May set properties of controls, create database connections.
Control Events - These are the control specific events, such as button clicks, listbox item selects etc.
LoadComplete - To execute tasks that require that the complete page has been loaded.
PreRender - Some methods are called before the PreRenderEvent takes place, like EnsureChildControls, data bound controls that have a dataSourceId set also call the DataBind method.
Each control of the page has a PreRender event. Developers may use the prerender event to make final changes to the controls before it is rendered to the page.
SaveStateComplete - ViewState is saved before this event occurs. However, if any changes to the viewstate of a control is made, then this is the event to be used. It cannot be used to make changes to other properties of a control.
Render - This is a stage, not an event. The page object invokes this stage on each control of the page. This actually means that the ASP.NET server control's HTML markup is sent to the browser.
Unload - This event occurs for each control. It takes care of cleanup activities like wiping the database connectivities.
What is Web.Config File?
Web.config file, as it sounds like is a configuration
file for the Asp .net web application. An Asp .net
application has one web.config file which keeps the configurations required for
the corresponding application. Web.config file is written in XML with specific
tags having specific meanings.
What can be stored in Web.config file?
There are number of important settings that can be stored
in the configuration file. Here are some of the most frequently used
configurations, stored conveniently inside Web.config file..
1. Database
connections
2. Session
States
3. Error
Handling
4. Security
Database Connections:
The most
important configuration data that can be stored inside the web.config file is
the database connection string. Storing the connection
string in the web.config file makes sense, since any modifications to the
database configurations can be maintained at a single location. As otherwise
we'll have to keep it either as a class level variable in all the associated
source files or probably keep it in another class as a public static variable.
But it this is
stored in the Web.config file, it can be read and used anywhere in the program.
This will certainly save us a lot of alteration in different files where we
used the old connection.
Lets see a small example of the connection string which is
stored in the web.config file.
<configuration>
<appSettings>
<add key="DBCONNECTION" value="User
ID=sample_id;Password=password;Initial Catalog=sampledb;Data
Source=172.20.121.00\ID2"/>
</appSettings>
</configuration>
|
Lets see how we access the connection string from our Asp
.net web application.
using System.Configuration;
string connectionString = (string
)ConfigurationSettings.AppSettings["ConnectionString"];
|
The small code snippet above is all that is
needed to access the value stored inside the Web.config file.
SESSION STATES
Session in Asp
.net web application is very important. As we know that HTTP is a stateless
protocol and we needs session to keep the state alive. Asp .net stores the
sessions in different ways. By default the session is stored in the asp .net
process. You can always configure the application so that the session will be
stored in one of the following ways.
1) Session State
Service
There are two
main advantages of using the State Service. First the state service is not
running in the same process as the asp .net application. So even if the asp
.net application crashes the sessions will not be destroyed. Any advantage is
sharing the state information across a Web garden (Multiple processors for the
same computer).
Lets see a small example of the Session State Service.
<sessionState
mode="StateServer"
stateConnectionString="tcpip=127.0.0.1:55455" sqlConnectionString="data
source=127.0.0.1;user id=sa;password='' cookieless="false"
timeout="20"/>
|
The attributes are self explanatory but I will go over
them.
mode: This can
be StateServer or SqlServer. Since we are using StateServer we set the mode to
StateServer.
stateConnectionString:
connectionString that is used to locate the State Service.
sqlConnectionString:
The connection String of the sql server database.
cookieless: Cookieless
equal to false means that we will be using cookies to store the session on the
client side.
2) SQL Server
The final choice to save the session information is using
the Sql Server 2000 database. To use Sql Server for storing session state you
need to do the following:
1) Run the InstallSqlState.sql script on the Microsoft SQL
Server where you intend to store the session.
Your web.config settings will look something like this:
<sessionState mode = "SqlServer"
stateConnectionString="tcpip=127.0.0.1:45565"
sqlConnectionString="data source="SERVERNAME;user id=sa;password=''
cookiesless="false" timeout="20"/>
|
SQL Server lets you share session state among the
processors in a Web garden or the servers in a Web farm. Apart from that you
also get additional space to store the session. And after that you can take
various actions on the session stored.
The downside is SQL Server is slow as compared to storing
session in the state in process. And also SQL Server cost too much for a small
company.
3) InProc:
This is another
Session State. This one is mostly used for development purposes. The biggest
advantage of using this approach is the applications will run faster when
compared to other Session state types. But the disadvantage is Sessions are not
stored when there is any problem that occurs with the application, when there
is a small change in the files etc., Also there could be frequent loss of
session data experienced.
Error Handling:
Error handling is one of the most important part of any
web application. Each error has to be caught and suitable action has to be
taken to resolve that problem. Asp.net web.config file lets us configure, what
to do when an error occurs in our application.
Check the following xml tag in the web.config file that
deals with errors:
<customErrors mode = "On">
<error statusCode = "404" redirect =
"errorPage.aspx" />
</customErrors>
|
This tells the Asp.net to display custom errors from a
remote client or a local client and to display a page named errorPage.aspx.
Error "404" is "Page not found" error.
If custom error mode is turned "off" than you
will see Asp.net default error message. This error messages are good for
debugging purposes but should never be exposed to the users. The users should
always be presented with friendly errors if any.
Security:
The most critical aspect of any application is the security. Asp.net offers many different types of security
method which can be used depending upon the condition and type of security you
need.
1) No
Authentication:
No Authentication means "No
Authentication" :) , meaning that Asp.net will not implement any type of
security.
2) Windows
Authentication:
The Windows authentication allows us
to use the windows user accounts. This provider
uses IIS to perform the actual authentication, and then passes the
authenticated identity to your code. If you like to see that what windows user
is using the Asp.net application you can use:
User.Identity.Name;
3) Passport
Authentication:
Passport Authentication provider
uses Microsoft's Passport service to authenticate users. You need to purchase this service in order to use it.
4) Forms
Authentication:
Forms Authentication uses HTML forms to collect the user
information and than it takes required actions on those HTML collected values.
In order to use Forms Authentication you must set the
Anonymous Access checkbox checked. Now we need that whenever user tries to run
the application he/she will be redirected to the login page.
<authentication mode="Forms">
<forms loginUrl = "frmLogin.aspx"
name="3345C" timeout="1"/>
</authentication>
<authorization>
<deny users="?" />
</authorization>
As you can see we set the Authentication mode to
"Forms".
The forms loginUrl is the first page being displayed when
the application is run by any user.
The authorization tags has the deny users element which
contains "?", this means that full access will be given to the
authenticated users and none access will be given to the unauthenticated users.
You can replace "?" with "*" meaning that all access is given
to all the users no matter what.
adding additional keys
<add key="ActivationDate" value="06/12/2012"/>
<add key="80011" value="Please enter a correct values."/>
<add key="80010" value="You can not edit the text."/>
Instead of regitering user
controls, Namespaces in each page we can register here
<pages validateRequest="false">
<controls>
<add tagPrefix="control1" source=”~/usercontrols/Note.ascx”
tagName=”ABC” />
<add tagPrefix="asp"
namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions,
Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</controls>
</pages>
Assemblies can be added in web.config
<compilation debug="true">
<assemblies>
<add assembly="System.Design, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System.Windows.Forms, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=B77A5C561934E08"/>
<add assembly="System.Web, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
</assemblies>
</compilation>
BuildProviders
Defines a collection of build
providers that are used to compile custom resource files.
<buildProviders>
<add extension=".aspx" type="System.Web.Compilation.PageBuildProvider"/>
<add extension=".ascx" type="System.Web.Compilation.UserControlBuildProvider"/>
End Points
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Basic" closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2147483647" maxBufferPoolSize="52428800" maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None"
proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
<endpoint address="http://win-6ct0sfpkux3.corp.ads.valuelabs.net/MTReceiver_20052010/TSLMTRECEIVER.svc"
binding="basicHttpBinding" bindingConfiguration="Basic3" contract="ATSLMTReceiver.ITSLMTRECEIVER"
name="Basic1" />
</client>
</system.serviceModel>
GLOBAL.ASAX
The Global.asax file (also known as
the ASP.NET application file) is an optional file that is located in the
application's root directory and is the ASP.NET counterpart of the Global.asa
of ASP. This file exposes the application and session level events in ASP.NET
and provides a gateway to all the application and the session level events in
ASP.NET. This file can be used to implement the important application and
session level events such as Application_Start, Application_End, Session_Start,
Session_End, etc.
The following are some of the important events in the
Global.asax file.
· Application_Init
· Application_Start
· Session_Start
· Application_BeginRequest
· Application_EndRequest
· Application_AuthenticateRequest
· Application_Error
· Session_End
· Application_End
The purpose of these event handlers is discussed in this
section below.
Application_Init
The
Application_Init event is fired when an application initializes the first time.
Application_Start
The
Application_Start event is fired the first time when an application starts.
Session_Start
The
Session_Start event is fired the first time when a user’s session is started.
This typically contains for session
initialization logic code.
Application_BeginRequest
The
Application_BeginRequest event is fired each time a new request comes in.
Application_EndRequest
The
Application_EndRequest event is fired when the application terminates.
Application_AuthenticateRequest
The
Application_AuthenticateRequest event indicates that a request is ready to be
authenticated. If you are using Forms
Authentication, this event can be used to check for the user's roles and
rights.
Application_Error
The
Application_Error event is fired when an unhandled error occurs within the
application.
Session_End
The
Session_End Event is fired whenever a single user Session ends or times out.
Application_End
The
Application_End event is last event of its kind that is fired when the
application ends or times out. It typically contains application cleanup logic.
The following code sample shows how we can use the events
in the Global.asax file to store values in the Application state and then
retrieve them when necessary. The program stores an Application and a Session
counter in the Application state to determine the number of times the
application has been accessed and the number of users currently accessing the
application.
using System;
using System.ComponentModel;
using System.Web;
using System.Web.SessionState;
public class Global: HttpApplication
{
protected void Application_Start(Object sender, EventArgs e)
{
Application["appCtr"]=0;
Application["noOfUsers"]=0;
}
protected void Application_BeginRequest(Object sender,EventArgs e)
{
Application.Lock();
Application["appCtr"]=(int) Application["appCtr"]+1;
Application.UnLock();
}
protected void Session_Start(Object sender, EventArgs e)
{
Application.Lock();
Application["noOfUsers"] = (int) Application["noOfUsers"] + 1;
Application.UnLock();
}
// Code for other handlers
}
After storing the values in the
Application state, they can be retrieved using the statements given in the code
sample below.
Listing 2
Response.Write("This application has been
accessed "+Application["appCtr"] + " times");
Response.Write("There are "+
Application["noOfUsers"] + " users accessing this
application");
No comments:
Post a Comment