Introduction Of ASP.
NET
[Link] is the next generation ASP, but it's not an upgraded version of ASP. [Link] is
an entirely new technology for server-side scripting. [Link] is a part of the Microsoft
.NET framework, and a powerful tool for creating dynamic and interactive web pages.
[Link] is a server side scripting technology that enables scripts (embedded in web
pages) to be executed by an Internet server
[Link] is a Microsoft Technology.
ASP stands for Active Server Pages
[Link] 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.
IIS is also a part of Windows 2000 and XP Professional.
Why is [Link] is Better Then ASP:
1. [Link] is a much improved replacement for original ASP framework
2. All [Link] code is fully compiled prior to execution.
3. [Link] doesn't require the use of scripting languages
4. [Link] allows for total separation of code from HTML
5. [Link] state management works in a Web farm environment
Page Life Cycle Of [Link]:
Use this event for the following:
• Check the IsPostBack property to determine whether this is the first
time the page is
PreInit being processed.
• Create or re-create dynamic controls.
• Set a master page dynamically.
• Set the Theme property dynamically.
Init Use this event to read or initialize control properties
Use this event for processing tasks that require all initialization
InitComplete
be complete.
Use this event if you need to perform processing on your page or
PreLoad
control before the Load event. After the Page raises this event, it loads
view state for itself and all controls, and then processes any postback
data included with the Request instance.
The Page calls the OnLoad event method on the Page, then recursively
Load does the same for each child control, which does the same for each of
its child controls until the page and all controls are loaded.
Use this event for tasks that require that all other controls on the page
LoadComplete
be loaded.
Page_PreRender The application is about to render the page object.
Page_Unload The page is unloaded from memory.
The page object is released from memory. This is the last event in the
Page_Disposed
life of a page object.
Architecture Of [Link] Framework:
In Above Figure:
The configuration of [Link] is managed by information stored in XML-format in a
configuration file ([Link]). The cache allows for improved performance of [Link],
as the most commonly requested pages would be served from the ASP .NET [Link]
management services for [Link] are provided by the [Link] state service. The .NET
Framework provides the Common Language Runtime (CLR) , which compiles and
manages the execution of [Link] code, and the class libraries, which offer prebuilt
programmatic functionality for Web Forms, XML support, and exception handling.
[Link] provides [Link] with connections to databases.
Basic Features In [Link]:
Easy-to-use, graphical data mapping interface
Instant data transformation
XSLT 1.0/2.0 and XQuery code generation
Java, C#, and C++ code generation
Advanced data processing functions
Support for all major relational databases including SQL Server, IBM DB2, Oracle,
and more
Integration with Altova StyleVision for report rendering
Visual Studio & Eclipse integration
Available in 32-bit and 64-bit versions
Advanced Features in [Link]:
Some of the new features in [Link] 2.0 are:
Master Pages, Themes, and Web Parts
Standard controls for navigation
Standard controls for security
Roles, personalization, and internationalization services
Improved and simplified data access controls
Full support for XML standards like, XHTML, XML, and WSDL
Improved compilation and deployment (installation)
Improved site management
New and improved development tools
Some of the new features in [Link] 3.5 are:
[Link] AJAX.
New ListView and DataPager Controls.
WCF Support for RSS, JSON, POX and Partial Trust.
LINQ (Language Integrated And Query).
New Web Design Interface.
Multi-targeting Support.
The new assemblies that would be of use to [Link] 3.5 developers are as
follows:
[Link] - Includes the implementation for LINQ to Objects
[Link] - Includes the implementation for LINQ to SQL
[Link] - Includes the implementation for LINQ to XML
[Link] - Includes the implementation for LINQ to
DataSet
[Link]: Includes the implementation for [Link] AJAX (new
enhancements added) and new web controls as explained earlier.
Advantage Of [Link]:
1. [Link] drastically reduces the amount of code required to build large
applications.
2. With built-in Windows authentication and per-application configuration, your
applications are safe and secured.
3. It provides better performance by taking advantage of early binding, just-in-time
compilation, native optimization, and caching services right out of the box.
4. The [Link] framework is complemented by a rich toolbox and designer in the
Visual Studio integrated development environment. WYSIWYG editing, drag-and-
drop server c ontrols, and automatic deployment are just a few of the features this
powerful tool provides.
5. Provides simplicity as [Link] makes it easy to perform common tasks, from
simple form submission and client authentication to deployment and site
configuration.
Architecture of [Link]
The configuration of [Link] is managed by information stored in XML-format in
a configuration file ([Link]).
The cache allows for improved performance of [Link], as the most commonly
requested pages would be served from
the [Link] [Link] management services for [Link] are provided by the
[Link] state service.
The .NET Framework provides the Common Language Runtime (CLR) , which
compiles and manages the execution of [Link]
code, and the class libraries, which offer prebuilt programmatic functionality for
Web Forms, XML support, and exception handling.
[Link] provides [Link] with connections to databases.
3-Tier Architecture in [Link] with C#
3-Tier architecture generally contains UI or Presentation Layer, Business Access Layer
(BAL) or Business Logic Layer and Data Access Layer (DAL).
Presentation Layer (UI)
Presentation layer c ontains pages like .aspx or windows form where data is presented to
the user or input is taken from the user.
Business Access Layer (BAL) or Business Logic Layer
BAL contains business logic, validations or calculations related with the data..
Data Access Layer (DAL)
DAL contains methods that helps business layer to connect the data and perform
required action, might be returning data or manipulating
data (insert, update, delete etc).
Designing 3-Tier Architecture
Data Access Layer (DAL) Code
Code for Data Access Layer
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link] ;
using [Link];
public class PersonDAL
{
string connStr =
[Link][ "connectionstring"].ToString();
public PersonDAL()
{
}
public int Insert(string name, string address, int age)
{
OleDbConnection conn = new OleDbConnection(connStr);
[Link]();
OleDbCommand dCmd = new OleDbCommand( "insert into insertrecord
values(@P,@q,@r)",conn);
try
{
[Link]("@p", name);
[Link]("@q", address);
[Link]("@r", age);
return [Link]();
}
catch
{
throw;
}
finally
{
[Link]();
[Link]();
[Link]();
}
}
}
Business Access Layer (BAL) Code
Code for Business Access Layer
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link] ;
public class PersonBAL
{
public PersonBAL()
{
}
public int Insert(string name, string address, int age)
{
PersonDAL pDAL = new PersonDAL();
try
{
return [Link](name, address, age);
}
catch
{
throw;
}
finally
{
pDAL = null;
}
}
}
Code for .cs file
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link] ;
using [Link];
using [Link];
using [Link];
public partial class _Default : [Link]
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//Lets validate the page first
if (![Link])
return;
int intResult = 0;
PersonBAL pBAL = new PersonBAL();
// Instantiate the object we have to deal with
string name = [Link];
string address = [Link];
int age = [Link]([Link]);
try
{
intResult = [Link](name, address, age);
if (intResult > 0)
[Link] = "New record inserted successfully.";
else
[Link] = "FirstName [<b>" + [Link] + "</b>]
alredy exists, try another name";
}
catch (Exception ee)
{
[Link] = [Link]();
}
finally
{
pBAL = null;
}
}
}
Presentation Layer
Code for .aspx page
<%@ Page
Language="C#"AutoEventWireup="true"Codevirtual="[Link]"Inherits="_Defaul
t"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"[Link] D/xht [Link]">
<html xmlns ="[Link] ml">
<head runat="server">
<title>Untitled Page</title>
<style type="text/css">
.style1
{
width: 100%;
height: 215px;
background-color: #FFFFCC;
}
.style2
{
width: 271px;
}
.style3
{
width: 271px;
height: 44px;
}
.style4
{
height: 44px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div style="background-color: #008000; height: 253px;">
<table class="style1">
<tr>
<td colspan="2">
ADD RECORDS </td>
</tr>
<tr>
<td class="style2">
Name </td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:Text Box>
</td>
</tr>
<tr>
<td class="style2">
 
Address </td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:Text Box>
</td>
</tr>
<tr>
<td class="style3">
Age </td>
<td class="style4">
<asp:TextBox ID="TextBox3" runat="server"></asp:Text Box>
</td>
</tr>
<tr>
<td class="style2">
<td>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Save Record" />
</td>
</tr>
<tr>
<td class="style2">
</td>
<td>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Life Cycle of [Link]
Page Life Cycle Events
Page_Init: The server controls are loaded and initialized from the Web form's
view state. it is basically used for initialized the object and control
Page_Load: The server controls are loaded in the page object. View state
information is available at this point, so this is where you put code to change
control settings or display text on the page.
Page_PreRender: The application is about to render the page object.
Page_Unload: The page is unloaded from memory.
Page_Disposed: The page object is released from memory. This is the last
event in the life of a page object.
Page_Error: An unhandled exception occurs.
Page_AbortTransaction: A transaction is aborted.
Page_CommitTransaction: A transaction is accepted.
Page_DataBinding: A server control on the page binds to a data source .
Control in [Link]
HTML Controls - Traditional HTML tags
Web Server Controls - New [Link] tags
Validation Server Controls - For input validation
HTML Server Controls
HTML server controls are HTML tags understood by the server.
HTML elements in [Link] 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 use d 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.
DESIGN OF HTML CONTROL
<script language="javascript"
type="text/javascript">
function Submit1_onclick() {
alert("click me");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Text1" type="text" value="anil"
/>
<input id="Submit1" type="submit"
value="submit " onclick="return Submit1_onclick()"
/></div>
</form>
</body>
</html>
Web Server Controls
Web server controls are special [Link] 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" />
DESIGN OF WEB SERVER CONTROL
.ASPX CODE
<html xmlns="[Link] ml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div style="width: 246px; background-color: #66FFFF;">
Name
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TextBox2"
runat="server" ></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="click me" />
<br />
<br />
</div>
</form>
</body>
</html>
.CS CODE
protected void Button1_Click(object sender, EventArgs e)
{
[Link] = "wiliam";
[Link] = "hello world";
}
Validation Server Controls
DESIGN OF VALIDATION SERVER CONTROL
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.
.ASPX CODE
<html xmlns ="[Link] ml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div style="width: 414px; background-color: #66FFFF;">
Name
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredF ieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="Text Box1" ErrorMessage="Blank are not allowed"
SetFocusOnError="True"></asp:RequiredFieldValidator>
<br />
Address
<asp:TextBox ID="TextBox2"
runat="server" ontextchanged="TextBox2_TextChanged"></asp:Text Box>
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="click me" />
<br />
<br />
</div>
</form>
</body>
</html>
.CS CODE
protected void Button1_Click(object sender, EventArgs e)
{
[Link] = "123";
[Link] = "hello world";
[Link]("hi display textbox 1 value"+[Link]);
}
Property
A property is a member that provides a flexible mechanism to read, write, or compute
the value of a private field. Properties can be used as if they are public data members,
but they are actually special methods called accessors.
Event
Events are user actions such as key press, clicks, mouse movements, etc., or some
occurrence such as system generated notifications. Applications need to respond to events
when they occur. For example, interrupts. Events are used for inter-process
communication.
The events are declared and raised in a class and associated with the event handlers using
delegates within the same class or some other class. The class containing the event is
used to publish the event. This is called the publisher class. Some other class that
accepts this event is called the subscriber class. Events use the publishe r-
subscriber model.
A publisher is an object that contains the definition of the event and the delegate. The
event-delegate association is also defined in this object. A publisher class object invokes
the event and it is notified to other objects.
A subscriber is an object that accepts the event and provides an event handler. The
delegate in the publisher class invokes the method (event handler) of the subscriber class.
Methods
A method is a code block that contains a series of statements. A program causes the
statements to be executed by calling themethod and specifying any
required method arguments. In C#, every executed instruction is performed in the context of
a method.
Various types of application that we can develop in .NET
When you hear the name .NET, it gives a feeling that it is something to do only with
internet or networked applications. Even though it is true that .NET provides solid
foundation for developing such applications it is possible to create many other types of
applications.
Following list will give you an idea about various types of application that we can develop
on .NET.
[Link] Web applications: These include dynamic and dat a driven browser
based applications.
Windows Form based applications: These refer to traditional rich client
applications.
Console applications: These refer to traditional DOS kind of applications like
batch scripts.
Component Libraries: This refers to components that typically encapsulate some
business logic.
Windows Custom Controls: As with traditional ActiveX controls, you can develop
your own windows controls.
Web Custom Controls: The concept of custom controls can be extended to web
applications allowing code reuse and modularization.
Web services: They are “web callable” functionality available via industry
standards like HTTP, XML and SOAP.
What is Partial Class
The purpose of a partial class is to allow you to textually break up a class declaration into
multiple parts, usually parts found in separate files. The motivation for this feature was
machine-generated code that is to be extended by the user by adding to it directly. When
you draw a form in the forms designer, the designer generates a class f or you representing
that form. You can then further customize that class by adding more code to it.
By the use of partial Class you can split the definition into multiple classes by using the
partial keyword. When the application is complied, the C# complier will group all the partial
classes together and treat them as a single class. There are a couple of good reasons to
use partial classes. Programmers can work on different parts of a class without needing to
share the same physical file. Also you can separate your application business logic from
the designer-generated code.
Example of Partial Class
Public partial class Employee
{
public void display()
{}
}
Public partial class Employee
{
public void show()
{}
}
State Management in [Link]
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
Client – Side State Management
[Link] provides various client side state management options like Cookies, Query
Strings (URL), Hidden fields, View State and Control state ([Link] 2.0).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 computer.
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.
Example of View state
Write code in .aspx page
<%@ Page Language="C#" AutoEventWireup="true"
Codevirtual="[Link]" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "[Link] D/xht ml 1-
[Link]">
<html xmlns ="[Link] ml" >
<head runat="server">
<title>ViewState</title>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox runat="server" id="NameField" />
<asp:Button runat="server" id="SubmitF or m "
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>
.Cs Code
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["NameOfUser"] != null)
[Link] = ViewState["NameOfUser"].ToString();
else
[Link] = "Not set yet...";
}
protected void SubmitForm_Click(object sender, EventArgs e)
{
ViewState["NameOfUser"] = [Link];
[Link] = [Link];
}
Advantages
The main advantage of view state is persisting controls properties without any
programming and memory will not be occupied on the client system or on the server
system.
Disadvantage
The disadvantage can be considered as a lot amount of data transmission between client
and server.
1. Control State – If you create a custom control that requires view state to work
properly, you should use control state to ensure other developers don’t break your
control by disabling view state.
2. 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.
3. 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.
4. 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.
Cookies in [Link]
A cookie is a small bit of text file that browser creates and stores on your machine (hard
drive). Cookie is a small piece of information stored as a string. Web server sends the
cookie and browser stores it, next time server returns that cookie .Cookies are mostly
used to store the information about the user. Cookies are stores on the client side .To
store data in a cookie is not secure due to it's location at client end. Cookie was introduced
with first version of Netscape navigator (that was 1.0).
Advantages
1. Cookies do not require any server resources since they are stored on the client.
2. Cookies are easy to implement.
3. You can configure cookies to expire when the browser session ends (session
cookies) or they can exist for a specified length of time on the client computer
(persistent cookies).
Disadvantages
1. Users can delete a cookies.
2. Users browser can refuse cookies, so your code has to anticipate that possibility.
3. Cookies exist as plain text on the client machine and they may pose a possible
security risk as anyone can open and tamper with cookies.
.ASPX CODE
<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="[Link]"
Inherits="Default3" %>
<html xmlns ="[Link] ml" >
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<fieldset>
<legend>rdfdf </legend>
<asp:TextBox ID="Text Box1" runat="server"></asp:Text Box>
<asp:Button ID="Button1" runat="server" Text="Add" Width="70px"
onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="View" Width="84px"
onclick="Button2_Click" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="" Width="138px"></asp:Label>
</fieldset>
</div>
</form>
</body>
</html>
.CS CODE
protected void Button1_Click(object sender, EventArgs e)
{
[Link]["MyCookie"]["Data"] = [Link]; // To Create Cookies
[Link]["MyCookie"]["Time"] = [Link]("G");
[Link]["MyCookie"].Expires = [Link](1);// For
Expire Cookies
[Link] = "Cookie created!<p>" + "Your cookie contains:<font color=red>" +
[Link]["MyCookie"]["Data"]
+ "<br>" + [Link]["MyCookie"]["Time"] + "</font>";
//[Link]("MyCookie").Expires = [Link]("2006-10-1");
}
protected void Button2_Click(object sender, EventArgs e)
{
if ([Link]["MyCookie"] == null)
[Link] = "There is no cookie:";
else
[Link] = "Your cookie contains:" + "<font color=red>" +
[Link]["MyCookie"]["Data"] + "<br>"
+ [Link]["MyCookie"]["Time"] + "</font>";
Query String In [Link]
Query string is used to pass the values or information form one page to anothe r
page.
The query string is a holdover from the ASP days of web programming. You will see this
a lot when you are surfing around the internet. Basically, it is passing information to the
next page with the URL .You can use a query string to submit data back to your page or
to another page through the URL. Query strings provide a simple but limited way of
maintaining some state information.
The advantages of using query strings are
No server resources required. The query string is contained in the HTTP request for
a specific URL.
Broad support. Almost all browsers and client devices support passing values in a
query string
it is very easy
The disadvantages of using query strings are
Security. The information in the query string is directly visible to the user via the
browser user interface. The query values are exposed to the Internet v ia the URL
so in some cases security may be an issue.
Limited capacity. Most browsers and client devices impose a 255-character limit on
URL length
.CS CODE
private void btnSubmit_Click(object sender, [Link] e)
{
[Link]("[Link]?Name=" +
[Link] + "&LastName=" +
[Link]);
}
Our first code part builds a query string for your application and send contents of your
textboxes to second page. Now how to retrieve this values from second page.
Put this code to second page page_load.
.ASPX CODE
private void Page_Load(object sender, [Link] e)
{
[Link] = [Link]["Name"];
[Link] = [Link]["LastName"];
}
Server Side State Management
When users visit Web sites it becomes necessary to maintain session related and controls
related information. In an HTTP exchange between a browser and a remote host, session
related information which identifies state, such as a unique session ID, information about
the user's preferences or authorization level is preserved. Note that sessions are
maintained in the data being exchanged.
State Management is the process by which we maintain session related information and
additional information about the controls and its state. The necessity of state management
arises when multiple users request for the same or different Web Pages of a Web Site.
State management can be accomplished using Client Side options or the Server side
options.
Session State: Its nothing but defined as a period of time shared between the web
application and user. Every user has individual session. Items/Objects can be placed into
the Session which would only define these object for that user. Session contains key
variables which help to identify the related values. This can be thought of as a hash table.
Each user would represent a different key node in the hash identifying unique values. The
Session variables will be clear by the application which can clear it, as well as through the
timeout property in the web config file. Usually the timeout is 20 minutes by default.
[Link] allows you to save values using session state, a storage mechanism that is
accessible from all pages requested by a single Web browser session. Therefore, you can
use session state to st ore user-specific information. Session state is similar to application
state, except that it is scoped to the current browser session. If different users are using
your application, each user session has a different session state. In addition, if a user
leaves your application and then returns later after the session timeout period, session
state information is lost and a new session is created for the user. Session state is stored
in the Session key/value dictionary.
Session Variables are stored on the server, can hold any type of data including references,
they are similar to global variables in a windows application and use HTTP cookies to store
a key with which to locate user's session variables .The collection of session variables is
indexed by the name of the variable or by an integer index. Session variables are created
by referring to the session variable by name. You do not have to declare a session variable
or explicitly add it to the collection.
Example:
//Storing informaton in session state
Session["username"] = "Ashish";
//Retrieving information from session state
string str = Session["username"];
Application State:
Application State is used to store information which is shared among users of the [Link]
web application. Application state is stored in the memory of the windows process which
is processing user requests on the web server. Application state is useful in storing small
amount of often-used data. If application state is used for such data instead of frequent
trips to database, then it increases the response time/performance of the web application.
In [Link], application state is an instance of HttpApplicationState class and it exposes
key-value pairs to store information. Its instance is automatically created when a first
request is made to web application by any user and same state object is being shared
across all subsequent users.
Application state can be used in similar manner as session state but it should be noted
that many user might be accessing application state simultaneously so any call to
application state object needs to be thread safe. This can be easily achieved in [Link]
by using lock keyword on the statements which are accessing application state object. This
lock keyword places a mutually exclusive lock on the statements and only allows a single
thread to access the application state at a time.
Code Sample
//Stroing information in application state
lock (this)
{
Application["username"] = "william";
}
//Retrieving value from application state
lock (this)
{
string str = Application["username"].ToString();
}