0% found this document useful (0 votes)
68 views26 pages

Unit-III ASP - Net Intrinsic Objects and State Management

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

Unit-III ASP - Net Intrinsic Objects and State Management

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

Programming Using Asp.

Net
Unit-III ASP.Net Intrinsic Objects and State Management

Intrinsic Objects:
Intrinsics are built-in objects that are explicitly referenced by the algorithms of this
specification and which usually have realm-specific identities. Unless otherwise specified
each intrinsic object actually corresponds to a set of similar objects, one per realm.
ASP.NET provides intrinsic objects to enable low-level access to the Web application
framework. With the help of these intrinsic objects, you can work directly with the
underlying HTTP streams, server, session, and application objects. The intrinsic objects can
be accessed in a Web form through the properties of the Page class. Table 3.1 lists the
important intrinsic objects and the properties of the Page class to which they are mapped.
• The HttpRequest
• HTTPResponce
• HTTPServerUtility
• HTTPApplicationState
• HTTP Session state

1. The HttpRequest
The HttpRequest object . represents the incoming request from the client to the Web
server. The request from the client can come in two ways—GET or POST. GET attaches the
data with the URL, whereas POST embeds the data within the HTTP request body.
The requested page and its details are encapsulated in an HttpRequest object.
The HttpRequest intrinsic object can be accessed by the Request property of the Page class.
Tables 3.2 and 3.3 list the properties and methods of the HttpRequest class, respectively.
Because the HttpRequest class provides information about the request sent by the client, all
the properties are read-only except the Filter property.
Properties of the HttpRequest Class:
Property Description
AcceptTypes Specifies the MIME types that the client browser accepts.

Prof. Manasi Talele 1


Programming Using Asp.Net
ApplicationPath Represents the application's virtual application root path on the
server.
Browser Provides access to the capabilities and characteristics of the
requesting browser.
ClientCertificate Represents the certificate, if any, sent by the client for secure
communications.
ContentEncoding Represents the character encoding (such as UTF7, ASCII, and so
on) for the entity body.
ContentLength Specifies the length in bytes of the request.

ContentType Specifies the MIME type of the incoming request.

Cookies Represents the cookies collection that is sent by the client to the
server.
CurrentExecutionFile Specifies the virtual path of the current executing page on the
Path Web server.
FilePath Specifies the virtual path of the file on the Web server.

Files Represents the file collection that is posted by the client to the
Web server.
Filter Represents a stream that is applied as a filter on the incoming
request.
Form Specifies the contents of a form posted to the server.

Headers Represents the HTTP headers passed in with the incoming


request.
HttpMethod Represents the method of the HTTP request (for
example, GET, POST, or HEAD).
InputStream Represents the stream that contains the incoming HTTP request
body.
IsAuthenticated Indicates whether the client has been authenticated to the Web
site.
IsSecureConnection Indicates whether the client connection is over a secure HTTPS
connection.

Prof. Manasi Talele 2


Programming Using Asp.Net
Params Represents the form, query string, cookies, and server variables
collection of the current request.
Path Specifies the virtual path of the current request, along with
additional path information.
PathInfo Specifies the additional path information of the current request.

PhysicalApplicationPa Specifies the physical file system path of the application's root
th directory.
PhysicalPath Specifies the physical file system path of the current request on
the Web server.
QueryString Represents the query string collection sent by the client to the
Web server through the URL.
RawUrl Specifies the URL portion of the current request, excluding the
domain information.
RequestType Represents the type of request (GET or POST) made by the client.

ServerVariables Represents the collection of Web server variables.

TotalBytes Represents the total number of bytes posted to the server in the
current request.
Url Specifies information about the current URL request.
UrlReferrer Specifies the URL of the client's previous request that linked to
the current URL request.
UserAgent Represents the browser being used by the client.
UserHostAddress Represents the IP address of the requesting client's machine.
UserHostName Represents the Domain Name System (DNS) name of the
requesting client's machine.
UserLanguages Specifies the languages preferred by the client's browser.

Prof. Manasi Talele 3


Programming Using Asp.Net
Methods of the HttpRequest Class:
Methods Description
BinaryRead() Reads the specified number of bytes from the request stream.
This method is provided for backward compatibility; you should
use InputStream property instead.
MapImageCoordinates() Returns the coordinates of a form image that is sent to the server
in the current request.
MapPath() Returns the physical file system path of the file for a specified
virtual path of a Web server.
SaveAs() Saves the current HTTP request into a disk file, with an option
to include or exclude headers.

2. The HttpResponse
The HttpResponse object represents the response sent back to the client from the Web
server. It contains properties and methods that provide direct access to the response stream
and allow you to set its behavior and operations. The Response property of the Page class
provides access to the HttpResponse object.
In ASP.NET, the HTTP response information is encapsulated in the HttpResponse class.
An instance of the class is created when the HTTP pipeline is set up to serve the request. The
instance is then linked to the HttpContext object associated with the request and exposed via
the Response property. The HttpResponse class defines methods and properties to manipulate
the text that will be sent to the browser. Although user-defined ASP.NET code never needs to
use the HttpResponse constructor, looking at it is still useful to get the gist of the class:

Properties of the HttpResponse Class:


Property Description
Buffer Indicates whether output to the response stream needs to be buffered
and sent to the client after the entire page is processed. This property
is provided for backward compatibility; the BufferOutput property
should be used instead.

Prof. Manasi Talele 4


Programming Using Asp.Net
BufferOutput Indicates whether the output to the response stream needs to be
buffered and then sent to the client after the entire page is processed.
The default is true.
Cache Represents the caching policy of the page. The policy controls where
caching can be done, the expiration time, and so on.
CacheControl Specifies where the caching should be done. The possible values
are Public and Private.
Charset Represents the character set of the output stream. If set to null, the
content-type header will be suppressed.
ContentEncoding Represents the character set of the response output stream.
ContentType Represents the MIME type for the outgoing response stream
like text/html, text/xml, and so on.
Cookies Represents the cookies collection that is sent by the server to the
client.
Expires Indicates the number of minutes until the page is cached by the client
browser.
ExpiresAbsolute Indicates the specific date and time until the page is cached by the
client browser.
Filter Represents a stream that is applied as a filter to the outgoing response.
IsClientConnected Indicates whether the client is connected to the server. This property is
very helpful when running a lengthy request.
Output Allows writing text output to the outgoing response.
OutputStream Allows writing binary output to the outgoing response.
Status Specifies the status of the HTTP output that is sent to the client. This
property returns both the status code and the text description of the
status (for example, 200 OK).
StatusCode Specifies the numeric representation of the status of the HTTP output
sent to the client (for example, 200, 302, and so on).
StatusDescription Specifies the text representation of the status of the HTTP output sent
to the client. (for example, OK, Redirect, and so on).

Prof. Manasi Talele 5


Programming Using Asp.Net
SupressContent Indicates whether the content in the page should be suppressed and not
sent to the client.

Methods of the HttpResponse Class:


Methods Description
AddCacheItemDependencies() Makes the validity of the cache item dependent on the
other items in the cache.
AddCacheItemDependency() Makes the validity of the cache item dependent on another
item in the cache.
AddFileDependencies() Adds a group of files to the collection on which the
current response depends.
AddFileDependency() Adds a file to the collection on which the current response
depends.
AddHeader() Adds an HTTP header to the outgoing response stream.
This method is provided for backward compatibility with
ASP.
AppendHeader() Adds an HTTP header to the outgoing response stream.
AppendToLog() Adds information to the IIS Web log file.
BinaryWrite() Allows writing binary data such as an image file or PDF
file to the response stream.
Clear() Clears the entire response stream buffer, including ts
contents and headers.
ClearContent() Clears the entire content portion of the response stream
buffer.
ClearHeaders() Clears the headers portion of the response stream buffer.
Close() Closes the response object and the socket connection to
the client.
End() Stops the execution of the page after flushing the output
buffer to the client.
Flush() Flushes the currently buffered content out to the client.

Prof. Manasi Talele 6


Programming Using Asp.Net
Pics() Adds a PICS-label HTTP header to the outgoing response.

Redirect() Redirects the client browser to any URL. This method


requires an additional roundtrip to the browser.

RemoveOutputCacheItem() Removes all cache items for the path specified.


Write() Writes output to the outgoing response.
WriteFile() Writes a file to the outgoing response.

3. The HTTPServerUtility
The HttpServerUtility object contains utility methods and properties to work with the
Web server. It contains methods to enable HTML/URL encoding and decoding, execute or
transfer to an ASPX page, create COM components, and so on. The Server property of
the Page class provides access to the HttpServerUtility object. list the properties and methods
of the HttpServerUtility class, respectively.
• Syntax
public void ClearError()

Properties of the HttpServerUtility Class:

Property Description
MachineName Returns the name of the server that hosts the Web application.

ScriptTimeout Indicates the number of seconds that are allowed to elapse when
processing the request before a timeout error is sent to the client.

Methods of the HttpServerUtility Class:


Methods Description

ClearError() Clears the last exception from memory. This method is


discussed in Chapter 4, "Error Handling for the User Interface."

Prof. Manasi Talele 7


Programming Using Asp.Net
CreateObject() Creates a COM object on the server. This method is discussed
in Chapter 10, "Working with Legacy Code."
CreateObjectFromClsid() Creates a COM object on the server identified by a specified
class identifier (CLSID).
Execute() Executes an ASPX page within the current requested page.
GetLastError() Returns the last exception that occurred on the Web server. This
method is discussed in Chapter 4.
HtmlDecode() Decodes a string that has been previously encoded to eliminate
invalid HTML characters.
HtmlEncode() Encodes a string converting any characters that are illegal in
HTML for transmission over HTTP.
MapPath() Returns the physical path for a specified virtual path on a Web
server.
Transfer() Allows the transfer of ASPX page execution from the current
page to another ASPX page on the same Web server.

UrlDecode() Decodes a string that has been previously encoded to eliminate


invalid characters for transmission over HTTP in a URL.

UrlEncode() Encodes a string converting any characters that are illegal in


URL for HTTP transmission.
UrlPathEncode() Encodes the path portion of the URL string for safe
transmission over HTTP.

4. The HttpApplicationState
Enables sharing of global information across multiple sessions and requests within an
ASP.NET application.
A single instance of an HttpApplicationState class is created the first time a client
requests any URL resource from within a particular ASP.NET application virtual directory. A
separate single instance is created for each ASP.NET application on a Web server. A
reference to each instance is then exposed via the intrinsic Application object.
Properties of the HttpApplicationState Class:
Property Description

Prof. Manasi Talele 8


Programming Using Asp.Net
AllKeys Gets the access keys in the HttpApplicationState collection.
Contents Gets a reference to the HttpApplicationState object.
Count Gets the number of objects in the HttpApplicationState collection.
IsReadOnly Gets or sets a value indicating whether
the NameObjectCollectionBase instance is read-only.
(Inherited from NameObjectCollectionBase)
Item[Int32] Gets a single HttpApplicationState object by index.
Item[String] Gets the value of a single HttpApplicationState object by name.
Keys Gets a NameObjectCollectionBase.KeysCollection instance that contains
all the keys in the NameObjectCollectionBase instance.
(Inherited from NameObjectCollectionBase)
StaticObjects Gets all objects declared by an <object> tag where the scope is set to
"Application" within the ASP.NET application.

Methods of the HttpApplicationState Class:


Methods Description

Add(String, Object) Adds a new object to


the HttpApplicationState collection.
BaseAdd(String, Object) Adds an entry with the specified key and value into
the NameObjectCollectionBase instance.
(Inherited from NameObjectCollectionBase)
BaseClear() Removes all entries from
the NameObjectCollectionBase instance.
(Inherited from NameObjectCollectionBase)
BaseGet(Int32) Gets the value of the entry at the specified index of
the NameObjectCollectionBase instance.
(Inherited from NameObjectCollectionBase)
BaseGet(String) Gets the value of the first entry with the specified key
from the NameObjectCollectionBase instance.

Prof. Manasi Talele 9


Programming Using Asp.Net
(Inherited from NameObjectCollectionBase)

BaseGetAllKeys() Returns a String array that contains all the keys in


the NameObjectCollectionBase instance.
(Inherited from NameObjectCollectionBase)
BaseGetAllValues() Returns an Object array that contains all the values in
the NameObjectCollectionBase instance.
(Inherited from NameObjectCollectionBase)
BaseGetAllValues(Type) Returns an array of the specified type that contains all
the values in the NameObjectCollectionBase instance.
(Inherited from NameObjectCollectionBase)
BaseGetKey(Int32) Gets the key of the entry at the specified index of
the NameObjectCollectionBase instance.
(Inherited from NameObjectCollectionBase)
BaseHasKeys() Gets a value indicating whether
the NameObjectCollectionBase instance contains
entries whose keys are not null.
(Inherited from NameObjectCollectionBase)
BaseRemove(String) Removes the entries with the specified key from
the NameObjectCollectionBase instance.
(Inherited from NameObjectCollectionBase)
BaseRemoveAt(Int32) Removes the entry at the specified index of
the NameObjectCollectionBase instance.
(Inherited from NameObjectCollectionBase)
BaseSet(Int32, Object) Sets the value of the entry at the specified index of
the NameObjectCollectionBase instance.
(Inherited from NameObjectCollectionBase)
BaseSet(String, Object) Sets the value of the first entry with the specified key in
the NameObjectCollectionBase instance, if found;
otherwise, adds an entry with the specified key and
value into the NameObjectCollectionBase instance.
(Inherited from NameObjectCollectionBase)

Prof. Manasi Talele 10


Programming Using Asp.Net
Clear() Removes all objects from
an HttpApplicationState collection.
Equals(Object) Determines whether the specified object is equal to the
current object.(Inherited from Object)
Get(Int32) Gets an HttpApplicationState object by numerical
index.
Get(String) Gets an HttpApplicationState object by name.
GetEnumerator() Returns an enumerator that iterates through
the NameObjectCollectionBase.
(Inherited from NameObjectCollectionBase)
GetHashCode() Serves as the default hash function.(Inherited
from Object)
GetKey(Int32) Gets an HttpApplicationState object name by index.
GetObjectData(SerializationInfo, Implements the ISerializable interface and returns the
StreamingContext) data needed to serialize
the NameObjectCollectionBase instance.
(Inherited from NameObjectCollectionBase)
GetType() Gets the Type of the current instance.
(Inherited from Object)
Lock() Locks access to an HttpApplicationState variable to
facilitate access synchronization.
MemberwiseClone() Creates a shallow copy of the current Object.
(Inherited from Object)

OnDeserialization(Object) Implements the ISerializable interface and raises the


deserialization event when the deserialization is
complete.
(Inherited from NameObjectCollectionBase)
Remove(String) Removes the named object from
an HttpApplicationState collection.
RemoveAll() Removes all objects from
an HttpApplicationState collection.

Prof. Manasi Talele 11


Programming Using Asp.Net
RemoveAt(Int32) Removes an HttpApplicationState object from a
collection by index.
Set(String, Object) Updates the value of an object in
an HttpApplicationState collection.
ToString() Returns a string that represents the current object.
(Inherited from Object)
UnLock() Unlocks access to an HttpApplicationState variable to
facilitate access synchronization.

5. The HTTPSession state

Provides access to session-state values as well as session-level settings and lifetime


management methods.
ASP.NET provides session-state management to enable you to store information
associated with a unique browser session across multiple requests. You can store a collection
of values referenced by a key name or by numerical index. Access to session values and
functionality is available using the HttpSessionState class, which is accessible through
the Session property of the current HttpContext, or the Session property of the Page.
Properties of the HttpSessionState Class:
Property Description
CodePage Gets or sets the character-set identifier for the current session.
Contents Gets a reference to the current session-state object.
CookieMode Gets a value that indicates whether the application is configured for
cookieless sessions.
Count Gets the number of items in the session-state collection.

IsCookieless Gets a value indicating whether the session ID is embedded in the URL
or stored in an HTTP cookie.
IsNewSession Gets a value indicating whether the session was created with the current
request.
IsReadOnly Gets a value indicating whether the session is read-only.

Prof. Manasi Talele 12


Programming Using Asp.Net
IsSynchronized Gets a value indicating whether access to the collection of session-state
values is synchronized (thread-safe).
Item[Int32] Gets or sets a session value by numerical index.
Item[String] Gets or sets a session value by name.
Keys Gets a collection of the keys for all values stored in the session-state
collection.
LCID Gets or sets the locale identifier (LCID) of the current session.
Mode Gets the current session-state mode.
SessionID Gets the unique identifier for the session.
StaticObjects Gets a collection of objects declared by <object Runat="Server"
Scope="Session"/> tags within the ASP.NET application file Global.asax.
SyncRoot Gets an object that can be used to synchronize access to the collection of
session-state values.
Timeout Gets or sets the amount of time, in minutes, allowed between requests
before the session-state provider terminates the session.

Methods of the HttpSessionState Class:

Methods Description
Abandon() Cancels the current session.
Add(String, Object) Adds a new item to the session-state collection.
Clear() Removes all keys and values from the session-state collection.
CopyTo(Array, Copies the collection of session-state values to a one-dimensional
Int32) array, starting at the specified index in the array.

Equals(Object) Determines whether the specified object is equal to the current


object.(Inherited from Object)
GetEnumerator() Returns an enumerator that can be used to read all the session-state
variable names in the current session.
GetHashCode() Serves as the default hash function.(Inherited from Object)
GetType() Gets the Type of the current instance.(Inherited from Object)

Prof. Manasi Talele 13


Programming Using Asp.Net
MemberwiseClone() Creates a shallow copy of the current Object.(Inherited from Object)
Remove(String) Deletes an item from the session-state collection.
RemoveAll() Removes all keys and values from the session-state collection.
RemoveAt(Int32) Deletes an item at a specified index from the session-state
collection.
ToString() Returns a string that represents the current object.(Inherited
from Object)

State Management
State Management is a process by which state and page information is maintained over
multiple requests for the same or different pages. As HTTP is a stateless protocol, the server
does not store any information once the response is sent back to the client based on his
request. When user submits a request again, the server treats it as a new user. This is called
stateless model. This model was workable when static web-sites were developed and hosted
in the past. Now, with interactive web sites or dynamic web site, there is a need to preserve
some information to identify user, interact with user again and again within same session and
same application. This concept is known as Stateful protocol. The information can be related
to user, data objects, web pages or server objects.

Client-side
• View State
• Cookies

Prof. Manasi Talele 14


Programming Using Asp.Net
View State
• ViewState is an important client-side state management technique. ViewState is used
to store user data on the page at the time of postback of the web page.
• ViewState does not hold the controls, it holds the values of controls. It does not restore
the value to control after the page post back. ViewState can hold the value on single
web page, if we go to other page using response. redirect then ViewState will be null.
• ViewState stores data on single page
• ViewState is client-side state management technique
• Session stores data on whole website pages
• Session is a server-side state management technique
• ViewState syntax same as Session, Session is a server-side object while ViewState is a
client-side object. The session can stores values across on multiple pages while
ViewState stores values on a single page.
• Viewstate Example
Store the value in viewstate
ViewState[“name”]=”Eagle Computers”;
Retrieve information from viewstate
string value=ViewState[“name”].ToString();

• View State Example in ASP.Net


Open Visual Studio and design a web form with two button controls, a textbox and a
label control as shown in below figure.
Here, we have two button controls one for a clear textbox value and the second one for
a retrieve the same textbox value after clearing it. Before clearing the textbox value store it
in ViewState[“name”] and after clearing it get the value from ViewState[“name”] and display
in label while clicking the display value button.
C# Code for above example
ViewState Example in ASP.Net
protected void Page_Load(object sender, EventArgs e){
}

Prof. Manasi Talele 15


Programming Using Asp.Net
protected void btnclear_Click(object sender, EventArgs e) {
ViewState["name"] = txtname.Text;
txtname.Text = "";
}
protected void btndisplay_Click(object sender, EventArgs e) {
lbl.Text = ViewState["name"].ToString();
}

Cookies
Cookies is a small pieces of text information which is stored on user hard drive using
users browser for identify users. It may contain username, ID, password or any information.
Cookie does not use server memory.
Cookies stored user computer at “C”\Document and Setting\Current
login_User\Cookie”. Types of Cookies
1. Persistence Cookie
2. Non-Persistence Cookie

1. Persistence Cookie
This type of cookies is permanently stored on user hard drive. Cookies which have an
expiry date time are called persistence cookies. These types of cookies stored user hard drive
permanently till the date time we set.
• Example to create persistence cookie
Response.Cookies[“name”].Value = “Eagle Computers”;
Response.Cookies[“Eagle”].Expires = DateTime.Now.AddMinutes(10);
• we can also create same cookies as like below
HttpCookie strname = new HttpCookie(“name”); strname.Value = “Eagle Computers”;
strname.Expires = DateTime.Now.AddMinutes(10); Response.Cookies.Add(strname);
In the above code we use Response.Cookies object for creating Cookie. In the above
example we have set 10 Minute time for Expire Cookie, we can retrieve cookie values up
to 10 minutes, after 10 minutes the cookies automatically expire.
Prof. Manasi Talele 16
Programming Using Asp.Net

2. Non-Persistence Cookie
This types of cookies are not permanently stored on user hard drive. It stores the
information up the user accesng the same browser. When user closes the browser the cookies
will be automatically deleted.
• Example to create non-persistnce cookie
Response.Cookies[“name”].Value = “Eagle Computers”;
• we can also create same non-persistence cookies as
HttpCookie strname = new HttpCookie(“name”); strname.Value = “Eagle
Computers”; Response.Cookies.Add(strname);
• Read Cookie Information
if (Request.Cookies[“name”] != null)
{
Label1.Text = Request.Cookies[“name”].Value;
}
• ASP.Net Cookie Example
Open visual studio and design web form as shows below figure for create
cookie and retrieve cookie information.
• C# code for Cookie Example Create Cookie Button C# Code

protected void btncreate_Click(object sender, EventArgs e)


{
Response.Cookies["name"].Value = txtcreatecookie.Text;
Response.Cookies["name"].Expires = DateTime.Now.AddMinutes(1);
Label1.Text = "Cookie Created";
txtcreatecookie.Text = "";
}
Here, we create cookie with name parameter and assign textbox values to name cookie
and also set expiry time 1 minute. The cookie destroyed after 1 minute.

Prof. Manasi Talele 17


Programming Using Asp.Net
Retrieve Cookie Button Code
protected void btnretrieve_Click(object sender, EventArgs e) {
if (Request.Cookies["name"] == null) {
txtretrieve.Text = "No cookie found";
}
else {
txtretrieve.Text = Request.Cookies["name"].Value;
}
}
On retrieve cookie button checks if cookie value not null then display cookie value in
result, but after 1 minute the cookie expires, after 1 minute cookie value will be null and
result will be “No cookie found”.

Server-Side State Management


Unlike Client-side state management techniques, Server-side options are more secure
but can become slow to respond, depending on the information that is stored. Since these
techniques directly use the resources of the web server, scalability issues is something to be
considered when storing large amount of data.
ASP.NET provides some options to implement server-side state management:

1. Application State

ASP.Net Application state is a server side state management technique.


Application state is a global storage mechanism that used to stored data on the server
and shared for all users, means data stored in Application state is common for all user. Data
from Application state can be accessible anywhere in the application. Application state is
based on the System.Web.HttpApplicationState class.
The application state used same way as session state, but session state is specific for a
single user session, where as application state common for all users of asp.net application.

Syntax of Application State


Prof. Manasi Talele 18
Programming Using Asp.Net
Store information in application state
Application[“name”] = “Eagle Computers”; Retrieve information from application state
string str = Application[“name”].ToString();

• Example of Application State in ASP.Net


Generally we use application state for calculate how many times a given page has
been visited by various clients.

• C# Code for Example


protected void btnvisit_Click(object sender, EventArgs e)
{
int count = 0;
if (Application["Visit"] != null)
{
count = Convert.ToInt32(Application["Visit"].ToString());
}
count = count + 1; Application["Visit"] = count;
Label1.Text = "Total Visit = " + count.ToString();
}
Here, above output screen we use different browser for visit same page. The result
counter value stored in Application object so it would be changed simultaneously for both
visitors.
In above case some time too many users click button at the same time, that time result
wont be accurate. This situation known as dead lock. To avoid dead lock we use Lock() and
UnLock() in application state.
Prof. Manasi Talele 19
Programming Using Asp.Net
• Lock() and UnLock() in Application State
protected void btnvisit_Click(object sender, EventArgs e) {
Application.Lock(); int cnt = 0;
if (Application["Visit"] != null) {
cnt = Convert.ToInt32(Application["Visit"].ToString());
}
cnt = cnt + 1; Application["Visit"] = cnt;
Application.UnLock();
Label1.Text = "Total Visit = " + cnt.ToString();
}

2. Session State
Session state is a period of time to visit a website for a particular user. Session can
store the client data on a server. Session is a best state management features to store the
client data on server separately for each user.
• Session can store value across on multiple pages of website.
• Viewstate can store value on single page.
In simple word we can say, At the same time more than one users login to system, all
user identification name store separately until they logout. session can store username or any
unique identification of user for a login period time.
Session value can be accessible from all pages from website. We can store some
information in session in one page and can access same information on rest of all page by
using session.
• By default, Session state is enabled for all ASP.NET applications
When you login to any website with username and password. your username shows on
all other pages.The username will be stored in session and on page we access session value
to display username.

• Syntax of session

Prof. Manasi Talele 20


Programming Using Asp.Net
Session[“session_name”] = “session value”;
• Declare session in asp.net
Session[“name”]=”Eagle Computers”; Response.Redirect(“nextpage.aspx”);
Above we create session with name parameter and assign value “Eagle Computers” to
session[“name”] and redirect user to other page “nextpage.aspx” using response.redirect
method.
• Retrieve session value on other page
string myvalue= Session[“name”].ToString(); Response.Write(“Name = ” + myvalue);
Here, we retrieve session[“name”] value and store session value in string variable
“myvalue”.

• Session Example on ASP.Net C#


Here, we take example to understand session in asp.net c#. Open visual studio and
design two web page, one for assign value to session and other for retrieve value from
session.

C# code for setting session value on the first page “default.aspx” on button click
events. After assigning a value to the session we redirect to other pages “next.aspx” using
response.redirect method. Here, we assign textbox name value to Session[“name”] and city
value to Session[“city”] and redirect to the next. aspx page.
protected void btnsession_Click(object sender, EventArgs e)
{
Session["name"] = txtname.Text; Session["city"] = txtcity.Text;
Response.Redirect("next.aspx");
}

Prof. Manasi Talele 21


Programming Using Asp.Net
On “next.aspx” page we retrieve and display session value on web page using label control.
C#
code on “next.aspx” page for retrieve session value.

protected void btngetvalue_Click(object sender, EventArgs e)


{
lblname.Text = Session["name"].ToString(); lblcity.Text = Session["city"].ToString();
}

Global.asax
• The Global.asax file, also known as the ASP.NET application file, is an optional file
that contains code for responding to application-level events raised by ASP.NET or by
HttpModules.
• The Global.asax file resides in the root directory of an ASP.NET-based application.
The Global.asax file is parsed and dynamically compiled by ASP.NET.
• The Global.asax file itself is configured so that any direct URL request for it is
automatically rejected; external users cannot download or view the code written within
it.
• The Global.asax file does not need recompilation if no changes have been made to it.
There can be only one Global.asax file per application and it should be located in the
application's root directory only.
• The Global.asax contains two types of events those are

Events which are fired for every request


• Application_BeginRequest() – This event raised at the start of every request for the
web application.
• Application_AuthenticateRequest – This event rose just before the user credentials
are authenticated. We can specify our own authentication logic here to provide custom
authentication.
• Application_AuthorizeRequest() – This event raised after successful completion of
authentication with user’s credentials. This event is used to determine user
permissions. You can use this method to give authorization rights to user.

Prof. Manasi Talele 22


Programming Using Asp.Net
• Application_ResolveRequestCache() – This event raised after completion of an
authorization request and this event used in conjunction with output caching. With
output caching, the rendered HTML of a page is reused without executing its code.
• Application_AcquireRequestState() – This event raised just before session-specific
data is retrieved for the client and is used to populate Session Collection for current
request.

• Application_PreRequestHandlerExecute() – This event called before the


appropriate HTTP handler executes the request.

• Application_PostRequestHandlerExecute() – This event called just after the request


is handled by its appropriate HTTP handler.

• Application_ReleaseRequestState() – This event raised when session specific


information is about to serialized from the session collection.

• Application_UpdateRequestCache() – This event raised just before information is


added to output cache of the page.

• Application_EndRequest() – This event raised at the end of each request right before
the objects released.

Events which are not fired for every request


• Application_Start() – This event raised when the application starts up and application
domain is created.
• Session_Start() – This event raised for each time a new session begins, This is a good
place to put code that is session-specific.
• Application_Error() – This event raised whenever an unhandled exception occurs in
the application. This provides an opportunity to implement generic application-wide
error handling.
• Session_End() – This event called when session of user ends.
• Application_End() – This event raised just before when web application ends.

Prof. Manasi Talele 23


Programming Using Asp.Net
• Application_Disposed() – This event fired after the web application is destroyed and
this event is used to reclaim the memory it occupies.

How to add global.asax file:


• Select Website >>Add New Item (or Project >> Add New Item if you're using the
Visual Studio web project model) and choose the Global Application Class template.
• After you have added the global.asax file, you will find that Visual Studio has added
Application Event handlers:

<%@ Application Language="C#" %>


<script runat="server">
void Application_Start(object sender, EventArgs e) {
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e) {
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e) {
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e) {
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e) {
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
</script>

Prof. Manasi Talele 24


Programming Using Asp.Net
Web.Config
A configuration file (web.config) is used to manage various settings that define a
website. The settings are stored in XML files that are separate from your application code. In
this way you can configure settings independently from your code. Generally a website
contains a single Web.config file stored inside the application root directory. However there
can be many configuration files that manage settings at various levels within an application.
• Usage of configuration file

• ASP.NET Configuration system is used to describe the properties and behaviors of


various aspects of ASP.NET applications. Configuration files help you to manage the
many settings related to your website. Each file is an XML file (with the extension
.config) that contains a set of configuration elements. Configuration information is
stored in XML-based text files.

Benefits of XML-based Configuration files


• ASP.NET Configuration system is extensible and application specific information can
be stored and retrieved easily. It is human readable.
• You need not restart the web server when the settings are changed in configuration
file. ASP.NET automatically detects the changes and applies them to the running
ASP.NET application.
• You can use any standard text editor or XML parser to create and edit ASP.NET
configuration files.

What Web.config file contains?


There are number of important settings that can be stored in the configuration file.
Some of the most frequently used configurations, stored conveniently inside Web.config file
are:
• Database connections
• Caching settings
• Session States
• Error Handling
• Security
The configuration file looks like this
Prof. Manasi Talele 25
Programming Using Asp.Net
<configuration>
<connectionStrings>
<add name="myCon"
connectionString="server=MyServer;database=puran;uid=puranmehra;pwd=mydata1223" />
</connectionStrings>
</configuration/>
• Different types of Configuration files
• Machine.config - Server or machine-wide configuration file
• Web.config - Application configuration files which deal with a single
application

Prof. Manasi Talele 26

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy