Chapter 3
Chapter 3
Response Object
The Response object represents the server's response to the client request. It is an instance of
the System.Web.HttpResponse class.
In ASP.NET, the response object does not play any vital role in sending HTML text to the client,
because the server-side controls have nested, object oriented methods for rendering
themselves.
However, the HttpResponse object still provides some important functionalities, like the
cookie feature and the Redirect() method. The Response.Redirect() method allows
transferring the user to another page, inside as well as outside the application. It requires a
round trip.
Properties and Methods of the Response Object
Property Description
Buffer Gets or sets a value indicating whether to buffer the output and
send it after the complete response is finished processing.
BufferOutput Gets or sets a value indicating whether to buffer the output and
send it after the complete page is finished processing.
Charset Gets or sets the HTTP character set of the output stream.
ContentEncoding Gets or sets the HTTP character set of the output stream.
ContentType Gets or sets the HTTP MIME type of the output stream.
Cookies Gets the response cookie collection.
Expires Gets or sets the number of minutes before a page cached on a
browser expires.
ExpiresAbsolute Gets or sets the absolute date and time at which to remove cached
information from the cache.
HeaderEncoding Gets or sets an encoding object that represents the encoding for the
current header output stream.
Headers Gets the collection of response headers.
IsClientConnected Gets a value indicating whether the client is still connected to the
server.
Output Enables output of text to the outgoing HTTP response stream.
OutputStream Enables binary output to the outgoing HTTP content body.
RedirectLocation Gets or sets the value of the Http Location header.
Status Sets the status line that is returned to the client.
StatusCode Gets or sets the HTTP status code of the output returned to the
client.
StatusDescription Gets or sets the HTTP status string of the output returned to the
client.
SubStatusCode Gets or sets a value qualifying the status code of the response.
SuppressContent Gets or sets a value indicating whether to send HTTP content to the
client.
HttpApplicationState
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. This object 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.
HttpSessionState
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
SessionID The unique session identifier
Itemname The value of the session state item with the specified name. This is the default
property of the HttpSessionState class.
Count The number of items in the session state collection.
TimeOut Gets and sets the amount of time, in minutes, allowed between requests before
the session-state provider terminates the session.
Methods:
Addname, value Adds an item to the session state collection.
Clear Removes all the items from session state collection.
Removename Removes the specified item from the session state collection.
RemoveAll Removes all keys and values from the session-state collection.
RemoveAt Deletes an item at a specified index from the session-state collection.
State Management:
State management is a preserve state control and object in an application because ASP.NET
web applications are stateless. A new instance of the Web page class is created each time the
page is posted to the server. If a user enters information into a web application, that
information would be lost in the round trip from the browser (MSDN).
In a single line, State management maintains and stores the information of any user till the end
of the user session.
Hidden Fields
Hidden Fields are similar to a text box but does not get displayed on the UI. However you can
see the value of hidden fields when you view page source in the browser. Using Hidden Fields,
you can pass information from one page to another page without the end user's knowledge,
primarily for internal processing.
Drag and Drop a hiddenfield control on the web page from the Visual Studio toolbox and set its
value in the Page Load event as shown below -
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
siteReference.Value = "https://www.google.com";
}
}
Run the page and check the source code. You will see the Hidden Field value as shown below –
<div>
<input type=”hidden” name=”siteReference” id=”siteReference”
value=”http://www.google.com”/>
<input type=”submit” name=”btnpageHitCounter” value=”Page Hit Counter”
Id=”btnPageHitCounter”/>
</div>
ViewState
ViewState is a important client side state management technique. ViewState is used to store
user data on page at the time of post back of web page.
ViewState does not hold the controls, it holds the values of controls. It does not restore the
value to control after 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. Session can stores values across on multiple pages while ViewState stores values
on single page.
Viewstate Example
Store the value in viewstate
ViewState[“name”]=”Eagle Computers”;
Retrieve information from viewstate
string value=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);
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
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.
Design web page in visual studio as shows in below figure.
Here, we calculate total visit of uses visited web page by clicking “Click to Visit” button.
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.
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();
}
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
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 set session value on first page “default.aspx” on button click events. After
assigning a value to session we redirect to other page “next.aspx” using response.redirect
method. Here, we assign textbox name value to Session[“name”] and city value to
Session[“city”] and redirect to next.aspx page.
protected void btnsession_Click(object sender, EventArgs e)
{
Session["name"] = txtname.Text;
Session["city"] = txtcity.Text;
Response.Redirect("next.aspx");
}
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.
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
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.
Application_EndRequest() – This event raised at the end of each request right before the
objects released.
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_End() – This event raised just before when web application ends.
Application_Disposed() – This event fired after the web application is destroyed and this
event is used to reclaim the memory it occupies.
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:
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.
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
Configuration file looks like this
1. <configuration>
2. <connectionStrings>
3. <add name="myCon" connectionString="server=MyServer;database=puran;uid=pu
ranmehra;pwd=mydata1223" />
4. </connectionStrings>
5. </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
Machine.config File
Configuration files are applied to an executing site based on a hierarchy. There is a global
configuration file for all sites in a given machine which is called Machine.config. This file is
typically found in the C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG
directory.
The Machine.config file contains settings for all sites running on the machine provided another
.config further up the chain does not override any of these settings. Although Machine.config
provides a global configuration option, you can use .config files inside individual website
directories to provide more granular control. Between these two poles you can set a number of
other .config files with varying degree of applicable scope.
Application Configuration file (Web.config)
Each and Every ASP.NET application has its own copy of configuration settings stored in a file
called Web.config. If the web application spans multiple folders, each sub folder has its own
Web.config file that inherits or overrides the parent's file settings.