0% found this document useful (0 votes)
44 views16 pages

ASP - NET Class Notes

This class notes describes the contents of ADO.NET and ASP.NET.

Uploaded by

kumarajay7th
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views16 pages

ASP - NET Class Notes

This class notes describes the contents of ADO.NET and ASP.NET.

Uploaded by

kumarajay7th
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

ADO.

Net
&
ASP.Net UNIT-V
Mr.Chirag Joshi | DIT University
UNIT#V

ADO.NET: ODBC

The ODBC .NET data provider communicates with native ODBC drivers through COM
interop (.NET’s interoperability layer for COM). The following ODBC providers are
guaranteed to be compatible with the ODBC.NET data provider:

1. Microsoft SQL Server ODBC Driver


2. Microsoft ODBC Driver for Oracle
3. Microsoft Access (Jet) ODBC Driver

The .NET data provider for ODBC connects to ODBC data sources through the
OdbcConnection object. The ODBC driver connection string is specified using the
ConnectionString property. It includes settings needed to establish the connection to the data
source. The connection string format closely matches the ODBC connection string format.
Additionally, you can specify an ODBC data source name (DSN) or file DSN by setting the
ConnectionString attribute to "DSN=myDSN" or "FileDSN=myFileDSN". For more
information about specifying ODBC connection strings, see the topic “SQLDriverConnect”
in the ODBC Programmer’s Reference within MSDN Library.

ADO.NET OLEDB Connection

An instance of the OleDbConnection class in .NET Framework is supported the OLEDB


Data Provider. The OleDbConnection instance takes Connection String as argument and pass
the value to the Constructor statement. When the connection is established , SQL Commands
may be executed, with the help of the Connection Object, to retrieve or manipulate data in the
database.
Once the Database activities over , Connection should be closed and release the resources .
The Close() method in SqlConnection class is used to close the Database Connection. The
Close method rolls back any pending transactions and releases the Connection from the
Database connected by the OLEDB Data Provider.

SQL Connected and Disconnected Mode

As mentioned earlier, ADO.NET supports two different programming environments:


connected and disconnected. The connected environment provides forward-only, read-only
access to data in the data source and the ability to execute commands against the data source.
The connected classes provide a common way to work with connected data regardless of the
underlying data source. They include Connection, Command, DataReader, Transaction,
ParameterCollection, and Parameter classes.

The disconnected environment allows data retrieved from the data source to be manipulated
and later reconciled with the data source. The disconnected classes provide a common way to
work with disconnected data regardless of the underlying data source. They include the
DataSet, DataTable, DataColumn, DataRow, Constraint, DataRelationship, and DataView
classes. Finally, ADO.NET introduces the connected DataAdapter class to bridge the data

Mr.Chirag Joshi CSE Deptt. DIT University 1


source and disconnected classes by way of the connected classes. The DataAdapter is
an abstraction of the connected classes that simplifies filling the disconnected DataSet
or DataTable classes with data from the data source and updating the data source to
reflect any changes made to the disconnected data.

Connected Classes

The following classes are used by ADO.NET to communicate directly with the data source:
Connection
Maintains information required to connect to the data source through a connection string. The
connection string contains information such as the name of the data source and its location,
and authorization credentials and settings. The Connection class has methods to open and
close the connection, for transactions to be initiated on the connection, as well as control
other properties of the connection.

Command
Executes SQL statements or stored procedures against the data source. The command class
has a ParameterCollection object containing Parameter objects that allow parameterized SQL
statements and stored procedures to be used against the data source.
DataReader

Allows parameters for both parameterized queries and stored procedures to be defined and set
to appropriate values. The Parameter class is accessed through the ParametersCollection
object within a Command object. It supports input and output parameters as well as return
values from stored procedures.
Transaction
Allows transactions to be created on a connection so that multiple changes to data in a data
source are treated as a single unit of work and either all committed or cancelled.
DataAdapter
Bridges the data source and the disconnected DataSet or DataTable classes. The DataAdapter
wraps the connected classes to provide this functionality. It provides a method to retrieve data

Mr.Chirag Joshi CSE Deptt. DIT University 2


into a disconnected object and a method to reconcile modified data in the disconnected object
with the data source. The CommandBuilder class can generate the logic to reconcile changes
in simple situations; custom logic can be supplied to deal with complex situations and
optimize performance.
Disconnected Classes
The following ADO.NET classes allow data to be retrieved from the data set, examined
and modified offline, and reconciled with the data source through the DataAdapter:
DataSet

Provides a consistent way to deal with disconnected data completely independently of the
data source. The DataSet is essentially an in-memory relational database, serving as a
container for the DataTable, DataColumn, DataRow, Constraint, and DataRelation objects.
The XML format serializes and transports a DataSet. A DataSet can be accessed and
manipulated either as XML or through the methods and properties of the DataSet
interchangeably; the XmlDataDocument class represents and synchronizes the relational data
within a DataSet object of DataColumn and DataRow classes. The DataTable allows
constraints such as foreign keys and unique constraints to be defined using the Constraint
class.

DataColumn
Corresponds to a column in a table. The DataColumn class stores metadata about the
structure of the column that, together with constraints, defines the schema of the table. The
DataColumn can also create expression columns based on other columns in the table.
DataRow
Corresponds to a row in a table and can examine and update data in the DataTable. The
DataTable exposes DataRow objects through the DataRowCollection object it contains. The
DataRow caches changes made to data contained in its columns, storing both original and
current values. This allows changes to be cancelled or to be later reconciled with the data
source.
Constraint
Allows constraints to be placed on data stored within a DataTable. Unique and foreign key
constraints can be created to maintain data integrity.
DataRelation
Provides a way to indicate a relationship between different DataTable objects within a
DataSet. The DataRelation relates columns in the parent and child tables allowing navigation
between the parent and child tables and referential integrity to be enforced through cascading
updates and deletes.
DataView
Allows data, once retrieved into a DataSet or DataTable, to be viewed in different ways. It
allows data to be sorted based on column values and for a subset of the data to be filtered so
that only rows matching specified criteria are displayed.

Mr.Chirag Joshi CSE Deptt. DIT University 3


Web Based Application on ASP.Net

ASP.NET :

ASP.NET is a web development platform, which provides a programming model, a


comprehensive software infrastructure and various services required to build up robust web
applications for PC, as well as mobile devices. ASP.NET works on top of the HTTP protocol,
and uses the HTTP commands and policies to set a browser-to-server bilateral
communication and cooperation.
ASP.NET is a part of Microsoft .Net platform. ASP.NET applications are compiled codes,
written using the extensible and reusable components or objects present in .Net framework.
These codes can use the entire hierarchy of classes in .Net framework.
The ASP.NET application codes can be written in any of the following languages:
C#
Visual Basic.Net
Jscript
J#
ASP.NET is used to produce interactive, data-driven web applications over the internet. It
consists of a large number of controls such as text boxes, buttons, and labels for assembling,
configuring, and manipulating code to create HTML pages.
ASP.NET life cycle specifies, how:
ASP.NET processes pages to produce dynamic output
The application and its pages are instantiated and processed
ASP.NET compiles the pages dynamically

The ASP.NET life cycle could be divided into two groups:


Application Life Cycle
Page Life Cycle
ASP.NET Application Life Cycle
The application life cycle has the following stages:

User makes a request for accessing application resource, a page. Browser sends this
request to the web server.
A unified pipeline receives the first request and the following events take place:
 An object of the class ApplicationManager is created.
 An object of the class HostingEnvironment is created to provide information regarding the
resources.
 Top level items in the application are compiled.
Response objects are created. The application objects such as HttpContext, HttpRequest
and HttpResponse are created and initialized.
An instance of the HttpApplication object is created and assigned to the request.
The request is processed by the HttpApplication class. Different events are raised by this
class for processing the request.

Life Cycle of ASP.NET Page

Mr.Chirag Joshi CSE Deptt. DIT University 4


When a page is requested, it is loaded into the server memory, processed, and sent to the
browser. Then it is unloaded from the memory. At each of these steps, methods and events
are available, which could be overridden according to the need of the application. In other
words, you can write your own code to override the default code.
The Page class creates a hierarchical tree of all the controls on the page. All the components
on the page, except the directives, are part of this control tree. You can see the control tree by
adding trace= "true" to the page directive. We will cover page directives and tracing under
'directives' and 'event handling'.
The page life cycle phases are:
Initialization
Instantiation of the controls on the page
Restoration and maintenance of the state
Execution of the event handler codes
Page rendering
Understanding the page cycle helps in writing codes for making some specific thing happen
at any stage of the page life cycle. It also helps in writing custom controls and initializing
them at right time, populate their properties with view-state data and run control behavior
code.
Following are the different stages of an ASP.NET page:
Page request - When ASP.NET gets a page request, it decides whether to parse and compile
the page, or there would be a cached version of the page; accordingly the response is sent.
Starting of page life cycle - At this stage, the Request and Response objects are set. If
the request is an old request or post back, the IsPostBack property of the page is set to
true. The UICulture property of the page is also set.
Page initialization - At this stage, the controls on the page are assigned unique ID by
setting the UniqueID property and the themes are applied. For a new request, postback
data is loaded and the control properties are restored to the view-state values.
Page load - At this stage, control properties are set using the view state and control state
values.
Validation - Validate method of the validation control is called and on its successful
execution, the IsValid property of the page is set to true.

Postback event handling - If the request is a postback (old request), the related event
handler is invoked.
Page rendering - At this stage, view state for the page and all controls are saved. The
page calls the Render method for each control and the output of rendering is written to
the OutputStream class of the Response property of page.
Unload - The rendered page is sent to the client and page properties, such as Response
and Request, are unloaded and all cleanup done.

Mr.Chirag Joshi CSE Deptt. DIT University 5


ASP.NET Page Life Cycle Events

At each stage of the page life cycle, the page raises some events, which could be
coded. An event handler is basically a function or subroutine, bound to the event, using
declarative attributes such as Onclick or handle.
Following are the page life cycle events:
PreInit - PreInit is the first event in page life cycle. It checks the IsPostBack property and
determines whether the page is a postback. It sets the themes and master pages, creates
dynamic controls, and gets and sets profile property values. This event can be handled
by overloading the OnPreInit method or creating a Page_PreInit handler.
Init - Init event initializes the control property and the control tree is built. This event
can be handled by overloading the OnInit method or creating a Page_Init handler.
InitComplete - InitComplete event allows tracking of view state. All the controls turn on
view-state tracking.
LoadViewState - LoadViewState event allows loading view state information into the
controls.
LoadPostData - During this phase, the contents of all the input fields are defined with
the <form> tag are processed.
PreLoad - PreLoad occurs before the post back data is loaded in the controls. This event
can be handled by overloading the OnPreLoad method or creating a Page_PreLoad
handler.
Load - The Load event is raised for the page first and then recursively for all child
controls. The controls in the control tree are created. This event can be handled by
overloading the OnLoad method or creating a Page_Load handler.
LoadComplete - The loading process is completed, control event handlers are run, and
page validation takes place. This event can be handled by overloading the OnLoadComplete
method or creating a Page_LoadComplete handler.
PreRender - The PreRender event occurs just before the output is rendered. By handling
this event, pages and controls can perform any updates before the output is rendered.
PreRenderComplete - As the PreRender event is recursively fired for all child controls,
this event ensures the completion of the pre-rendering phase.
SaveStateComplete - State of control on the page is saved. Personalization, control state
and view state information is saved. The HTML markup is generated. This stage can be
handled by overriding the Render method or creating a Page_Render handler.
UnLoad - The UnLoad phase is the last phase of the page life cycle. It raises the UnLoad
event for all controls recursively and lastly for the page itself. Final cleanup is done and
all resources and references, such as database connections, are freed. This event can be
handled by modifying the OnUnLoad method or creating a Page_UnLoad handler.

Manage State In ASP.NET

Hyper Text Transfer Protocol (HTTP) is a stateless protocol. When the client disconnects
from the server, the ASP.NET engine discards the page objects. This way, each web
application can scale up to serve numerous requests simultaneously without running out of

Mr.Chirag Joshi CSE Deptt. DIT University 6


server memory. However, there needs to be some technique to store the information between
requests and to retrieve it when required. This information i.e., the current value of all the
controls and variables for the current user in the current session is called the State.
ASP.NET manages four types of states:
View State
Control State
Session State
Application State
View State
The view state is the state of the page and all its controls. It is automatically maintained
across posts by the ASP.NET framework. When a page is sent back to the client, the changes
in the properties of the page and its controls are determined, and stored in the value of a
hidden input field named _VIEWSTATE. When the page is again posted back, the
VIEWSTATE field is sent to the server with the HTTP request.
The view state could be enabled or disabled for:
The entire application by setting the EnableViewState property in the <pages> section
of web.config file.
A page by setting the EnableViewState attribute of the Page directive, as <%@ Page
Language="C#" EnableViewState="false" %>
A control by setting the Control.EnableViewState property.
It is implemented using a view state object defined by the StateBag class which defines a
collection of view state items. The state bag is a data structure containing attribute value
pairs, stored as strings associated with objects. The StateBag class has the following
properties:
Properties Description
The value of the view state item with
Item(name) the specified name. This is
the default property of the StateBag
class.

Count The number of items in the view state


collection.
Keys Collection of keys for all the items in
the collection.
Values Collection of values for all the items in
the collection.

The StateBag class has the following methods:

Methods Description
Adds an item to the view state
Add(name, value) collection and existing item is
updated.
Clear Removes all the items from the
collection.
Determines whether the specified object
Equals(Object) is equal to the current
object.

Mr.Chirag Joshi CSE Deptt. DIT University 7


Finalize Allows it to free resources and perform
other cleanup operations.
Returns an enumerator that iterates over
GetEnumerator all the key/value pairs
of the StateItem objects stored in the
StateBag object.
GetType Gets the type of the current instance.
Checks a StateItem object stored in the
IsItemDirty StateBag object to
evaluate whether it has been modified.
Remove(name) Removes the specified item.
Sets the state of the StateBag object as
SetDirty well as the Dirty property
of each of the StateItem objects
contained by it.
Sets the Dirty property for the specified
SetItemDirty StateItem object in the
StateBag object.
ToString Returns a string representing the state
bag object.

Session State
When a user connects to an ASP.NET website, a new session object is created. When session
state is turned on, a new session state object is created for each new request. This session
state object becomes part of the context and it is available through the page.
Session state is generally used for storing application data such as inventory, supplier list,
customer record, or shopping cart. It can also keep information about the user and his
preferences, and keep the track of pending operations.
Sessions are identified and tracked with a 120-bit SessionID, which is passed from client to
server and back as cookie or a modified URL. The SessionID is globally unique and random.
The session state object is created from the HttpSessionState class, which defines a collection
of session state items. The HttpSessionState class has the following properties:
Properties Description
SessionID The unique session
identifier.
The value of the session
state item with the specified
Item(name) name. This
is the default property of the
HttpSessionState class.
Count The number of items in the
session state collection.
Gets and sets the amount of
time, in minutes, allowed
TimeOut between
requests before the session-
state provider terminates the
session.

Mr.Chirag Joshi CSE Deptt. DIT University 8


The HttpSessionState class has the following methods:
Methods Description
Add(name, value) Adds an item to the session
state collection.
Clear Removes all the items from
session state collection.
Removes the specified item
Remove(name) from the session state
collection.
Removes all keys and values
RemoveAll from the session-state
collection.
Deletes an item at a
RemoveAt specified index from the
session-state
collection.
The session state object is a name-value pair to store and retrieve some information from the
session state object. You could use the following code for the same:
void StoreSessionInfo()
{
String fromuser = TextBox1.Text;
Session["fromuser"] = fromuser;
}
void RetrieveSessionInfo()
{
String fromuser = Session["fromuser"];
Label1.Text = fromuser;
}
The above code stores only strings in the Session dictionary object, however, it can store all
the primitive data types and arrays composed of primitive data types, as well as the DataSet,
DataTable, HashTable, and Image objects, as well as any user-defined class that inherits
fromthe ISerializable object.

Application State
The ASP.NET application is the collection of all web pages, code and other files within a
single virtual directory on a web server. When information is stored in application state, it is
available to all the users. To provide for the use of application state, ASP.NET creates an
application state object for each application from the HTTPApplicationState class and stores
this object in server memory. Thisobject is represented by class file global.asax.
Application State is mostly used to store hit counters and other statistical data, global
application data like tax rate, discount rate etc. and to keep the track of users visiting the site.
The HttpApplicationState class has the following properties:
Properties Description
The value of the application state item
Item(name) with the specified name.
This is the default property of the
HttpApplicationState class.

Mr.Chirag Joshi CSE Deptt. DIT University 9


Count

The number of items in the application


state collection.

The HttpApplicationState class has the following methods:

Methods Description
Add(name, value) Adds an item to the application state collection.

Removes all the items from the application state


Clear
collection.

Removes the specified item from the application


Remove(name)
state collection.

Removes all objects from an HttpApplicationState


RemoveAll
collection.

Removes an HttpApplicationState object from a


RemoveAt collection by
index.

Locks the application state collection so only the


Lock() current user can
access it.

Unlocks the application state collection so all the


Unlock() users can access
it.
Application state data is generally maintained by writing handlers for the events:
Application_Start
Application_End
Application_Error
Session_Start
Session_End
The following code snippet shows the basic syntax for storing application state information:
Void Application_Start(object sender, EventArgs e)
{
Application["startMessage"] = "The application has started.";
}
Void Application_End(object sender, EventArgs e)
{
Application["endtMessage"] = "The application has ended.";

Mr.Chirag Joshi CSE Deptt. DIT University 10


Differentiate between ASP and ASP.NET

ASP and ASP.Net are very different programming languages. ASP is a scripting
language, whereas ASP.NET is the web formulation of a compiled language (Visual Basic,
C#, J#,
C++, .Net). Moreover, unlike ASP, ASP.NET is an object-oriented language.
Process Isolation
ASP is run under the inetinfo.exe(IIS) process space and is therefore susceptible to
application crashes due to IIS being stopped or restarted.On the other hand, the ASP.NET
worker process is a distinct process (aspnet_wp.exe) separate from the IIS process
inetinfo.exe. The process model in ASP.NET is unrelated to process isolation
settings in IIS.
Interpretation vs. Compilation
When a traditional ASP page is requested, the text of that page is parsed linearly. All content
that is not server-side script is rendered as-is back to the response. All server-side script in the
page is first run through the appropriate interpreter (JScript or VBScript), the output of which
is then rendered back to the response.
In contrast, ASP.NET pages are always compiled into .NET classes housed within
assemblies. This class includes all of the server-side code and the static HTML, so once a
page is accessed for the first time (or any page within a particular directory is accessed),
subsequent rendering of that page is serviced by executing compiled code. This eliminates all
the inefficiencies of the scripting model of traditional ASP.
Performance Implications
Since ASP scripts are interpreted on the fly, there is a performance impact. A common
optimization for ASP applications, therefore, is to move a lot of server-side script into
precompiled COM components to improve response times. Since all components in
ASP.NET are assemblies, there is no performance degradation by using server-side code.
With ASP, intermingling server-side evaluation blocks with static HTML is less efficient
than a single server-side script block, because the interpreter has to be invoked multiple
times. To avoid this, many ASP developers resort to large blocks of server-side script,
replacing static HTML elements with Response.Write() invocations instead. For ASP.NET,
such steps are not required for performance improvement.
ASP allows different blocks of script within a page to be written in different scripting
languages. While this may be appealing in some ways, it also degrades performance by
requiring that a particular page load both scripting engines (JScript, VBScript) to process
a request, which takes more time and memory than using just one language. ASP.NET
has "code-behind" in .aspx files that are parsed and compiled. Multiple server-side
languages cannot be used within a single .aspx file.
Debugging
Since ASP involves scripts being interpreted, debugging is difficult. But with ASP.NET, all
the tools available to the .NET developer are applicable to the .aspx developer. Errors with
pages are generated as compiler errors, and there is a good chance that most errors will be
found at compilation time instead of runtime, because VB.NET and C# are both strongly
typed languages.

Mr.Chirag Joshi CSE Deptt. DIT University 11


Differentiate between ASP and ASP.NET

ASP:
i. It has limited oops support and not having built in support for xml.
ii. Very less development and debugging tool available. Meaning that difficult to debug the
code.
iii. ASP you can only do scripting using visual basic scripting and java scripting.
iv. Error handling is very poor.
v. It has no high level programming structure. Mixed of html and server side scripting.
vi. You must be entering first line as -
<%LANGUAGE="VBSCRIPT" CODEPAGE="960"%>
vii. It has no in built validation control. Meaning that validating page is difficult for
developers.
viii. In the classic ASP if you need to update code on the existing page then it is mandatory to
restart the server to get reflect.
ASP.NET
i. ASP.NET is full featured object oriented programming.
ii. It has full support of xml. Which helps easy data exchange.
iii. Various tools and compiler available. Microsoft Visual studio makes your debugging job
easier.
iv. ASP.NET we can use either C# or VB.NET as server side programming language.
v. ASP.NET gives you three tire architecture. It allow you to keep your business logic, views
everything separate. Meaning that easy to enhance applications.
vi. Error handling is very good.
vii. You are required to make language directive with page as below.
<%@Page Language="VB" CodePage="960"%>
<%@QutputCache Duration="60" VaryByParam="none" %>
viii. It has state management support.
ix. In built validation controls. It has rich validation set - custom validator, range validator,
regular expression, compare and require field validation control which makes your job easier.

Mr.Chirag Joshi CSE Deptt. DIT University 12


PostBack in ASP.NET

PostBack is the name given to the process of submitting an ASP.NET page to the server for
processing. PostBack is done if certain credentials of the page are to be checked against some
sources (such as verification of username and password using database). This is something
that a client machine is not able to accomplish and thus these details have to be 'posted back'
to the server.

A post back is round trip from the client (Browser) to the server and then back to the client.
This enables you page to go through the asp engine on the server and any dynamic content to
be updated.

Life Cycle of a Web Page:

To work with the ASP.Net Web Controls events, we need a solid understanding of the web
page life cycle. The following actions will be taken place when a user changes a control that
has the AutoPostBack property set to true :

1. On the client side, the JavaScript _doPostBack function is invoked, and the page is
resubmitted to the server.
2. ASP.NET re-creates the Page object using the .aspx file.
3. ASP.NET retrieves state information from the hidden view state field and updates the
controls accordingly.
4. The Page.Load event is fired.
5. The appropriate change event is fired for the control. (If more than one control has
been changed, the order of change events is undetermined.)
6. The Page.PreRender event fires, and the page is rendered (transformed from a set of
objects to an HTML page).
7. Finally, the Page.Unload event is fired.
8. The new page is sent to the client.

Master Page In ASP.NET

The master page defines placeholders for the content, which can be overridden by content
pages. The output result is a combination of the master page and the content page . This
improves the maintainability of your site and avoids unnecessary duplication of code for
shared site structure or behaviour.

A single master page defines the look and feel and standard behaviour that you want for all of
the pages (or a group of pages) in your application. Defining a Master page is similar to
defining a normal page, but saving a Master page is different from saving a normal page. You
must save the Master pages by using the .master file extension. Master pages are completely
transparent to end users and permit developers to create Web sites where pages share a
common layout . The page layout for Master Pages is easy to create, simple to maintain, and
simple to assign to a Web application. The master page is identified by a special @ Master
directive that replaces the @ Page directive that is used for ordinary .aspx pages.

Mr.Chirag Joshi CSE Deptt. DIT University 13


Use of Master Pages

The master pages can be used to accomplish the following:

 Creating a set of controls that are common across all the web pages and attaching them to all
the web pages.
 A centralized way to change the above created set of controls which will effectively change
all the web pages.
 Dynamically changing the common UI elements on master page from content pages based on
user preferences.

Mr.Chirag Joshi CSE Deptt. DIT University 14

You might also like