0% found this document useful (0 votes)
9 views31 pages

ASP Unit No2 Sem2

The document discusses ASP.NET state management, focusing on cross-page posting, navigation controls, and the differences between Server.Transfer and Response.Redirect. It provides examples of how to implement cross-page posting and navigation techniques, including code snippets for web forms. Additionally, it covers the use of hidden fields in ASP.NET to store values that persist across server posts without being visible to the user.

Uploaded by

pshiv09098
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)
9 views31 pages

ASP Unit No2 Sem2

The document discusses ASP.NET state management, focusing on cross-page posting, navigation controls, and the differences between Server.Transfer and Response.Redirect. It provides examples of how to implement cross-page posting and navigation techniques, including code snippets for web forms. Additionally, it covers the use of hidden fields in ASP.NET to store values that persist across server posts without being visible to the user.

Uploaded by

pshiv09098
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/ 31

DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S.

Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

What is Cross Page Posting in ASP.NET?


By default, buttons have a postback property. When you click the button it
reloads the page itself. However we can use the property PostBackUrl to redirect to
another page. If you want to use the data of one page to another page without using
session, object, or anything else, you can just use cross-page in your project.
Cross page posting means you are posting form data to another page. This is useful
when you want to post data to another page and do not want incur the overhead of
reloading the current page. The below code is given with a simple example. For this
example we have to require two pages. Below is given the page with design and coding.
Just follow along.
Cross-Page.aspx
<!DOCTYPE html PUBLIC "-
//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xht
ml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div align="center">
<asp:Label ID="Label1" runat="server" Text="User Name"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Label ID="Label2" runat="server" Text="Password"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Log In" PostBackUrl="~/Cros
s_page2.aspx" />
</div>
</form>
</body>
</html>
Cross-Pgae2.aspx
<!DOCTYPE html PUBLIC "-
//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

</head>
<body>
<form id="form1" runat="server">
<div align="center">
<b style="font-size: xx-
large; color: #669900"> Welcome To AspMaterials Blog</b><br />
<asp:Label ID="Label1" runat="server" Text="Label" Font-Bold="True" Font-
Size="Large" ForeColor="Blue"></asp:Label>
</div>
</form>
</body>
</html>
Cross-Page2.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Cross_page2: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox tb = new TextBox(); // this is a object for texbox
tb = (TextBox)(PreviousPage.FindControl("TextBox1"));
Label1.Text = tb.Text;
}
}
}
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

Navigation Controls-
The following are the different page navigation techniques in asp.net
1. Hyperlink control
2. Response.Redirect
3. Server.Transfer
4. Server.Execute
5. Cross-Page postback
6. Window.Open

1. Response.Redirect-
Response.Redirect is similar to clicking on a hyperlink. The Hyperlink control does not
expose any server side events. So when the user clicks on a hyperlink, there is no server
side event to intercept the click.

So, if you want to intercept a click event in code, use the Button, LinkButton or the
ImageButton server control. In the button click event, call Response.Redirect() method.
When the user clicks the button, the web server receives, a request for redirection. The
server then sends a response header to the client. The client then automatically issues a
new GET request to the web server. The web server will then serve the new page. So, in
short, Response.Redirect causes 2 request/response cycles.

Also, note that when Response.Redirect is used the URL in the address bar changes and
the browser history is maintained.

Response.Redirect() can be used to navigate pages/websites on the same web server or


on a different web server.

2. Server.Transfer
Server.Transfer navigates the pages within the same application or within the same
server, the page is still in memory that can read the values directly from page2 on
page1, in other words by using server.Transfer the page is not redirected permanently.
Suitable Uses
The suitable uses are:
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

 to transfer the current page request to another .aspx page on the same server.
 to preserve server resources and avoid the unnecessary round trips to the server.
 to preserve the Query String and Form Variables.
 don't need to show the real URL of where we redirected the request in the user's
Web Browser.
 don’t want to bookmark the pages.
Create an asp.net web application and add 2 webforms. Copy and paste the following
HTML on WebForm1.aspx
<div style="font-family: Arial">
<table>
<tr>
<td colspan="2">
<h1>
This is WebForm1</h1>
</td>
</tr>
<tr>
<td>
<b>Name</b>
</td>
<td>
:<asp:TextBox ID="txtName" runat="server">
</asp:TextBox>
</td>
</tr>
<tr>
<td>
<b>Email</b>
</td>
<td>
:<asp:TextBox ID="txtEmail" runat="server">
</asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnTransfer" runat="server"
Text="Transfer to WebForm2" Width="250px"
OnClick="btnTransfer_Click"/>
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnTransferToExternalWebsite"
runat="server" Width="250px"
OnClick="btnTransferToExternalWebsite_Click"
Text="Transfer to External WebSite"/>
</td>
</tr>
</table>
</div>

Code-Behind code for WebForm1.aspx.cs


protected void btnTransfer_Click(object sender, EventArgs e)
{
//Send the user to webform2 using Server.Transfer
//Set the boolean parameter preserveForm=true
//This ensures that the posted form values can be retrieved
//Since the default value for this parameter is true, the

//form values are preserved, even if this parameter is not used.


Server.Transfer("~/WebForm2.aspx", true);
}
protected void btnTransferToExternalWebsite_Click(object sender, EventArgs e)
{
//Transfer to websites/pages on a different web server causes
//runtime error
Server.Transfer("http://pragimtech.com/home.aspx");
}
WebForm2.aspx code:
<div>
<table>
<tr>
<td>
<b>Name</b>
</td>
<td>
:<asp:Label ID="lblName" runat="server">
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

</asp:Label>
</td>
</tr>
<tr>
<td>
<b>Email</b>
</td>
<td>
:<asp:Label ID="lblEmail" runat="server">
</asp:Label>
</td>
</tr>
</table>
</div>
WebForm2.aspx.cs code
protected void Page_Load(object sender, EventArgs e)
{
//Get the form values from the previous page
System.Collections.Specialized.NameValueCollectionnameValueCollection =
Request.Form;

lblName.Text = nameValueCollection["txtName"];
lblEmail.Text = nameValueCollection["txtEmail"];

//Page previousPage = this.Page.PreviousPage;


//if (previousPage != null)
//{
// TextBoxpreviousPageNameTextBox =
(TextBox)previousPage.FindControl("txtName");
// lblName.Text = previousPageNameTextBox.Text;

// TextBoxpreviousPageEmailTextBox =
(TextBox)previousPage.FindControl("txtEmail");
// lblEmail.Text = previousPageEmailTextBox.Text;
//}
}
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

The following are the differences between Server.Transfer and Response.Redirect


1. Just like hyperlink and Response.Redirect, Server.Transfer is used to navigate to other
pages/sites running on the same web server.
2. Server.Transfer cannot be used to navigate to sites/pages on a different web server.
3. Server.Transfer does not change the URL in the address bar
4. Server.Transfer is faster than Response.Redirect as the redirection happens on the
server in one Request/Response cycle. Response.Redirect() involves 2
Request/Response cycles.
5. With Server.Transfer the Form Variables from the original request are preserved.

3. ASP Write() Method


The ASP Write() method is used to display a string as an output on the webpage. It is a
predefined method of the Response and Textstream type object.
Syntax:
For response object:
Response.Write variant
For Textstream Object:
Textstream.write(string)
Parameter Values: This method contains the value j.e variant which represents the
specified string that you want to display as an Output.
Return Values: This method does not return any Values.
Example: Below code illustrates the ASP Write() Method
 ASP
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

<%
response.write("<h1>ASP Write() Method</h2>")
response.write("<p>Hello GeeksForGeeks)</p>")
%>

4. Hidden field in asp.net -


The HiddenField control is used to store a value that needs to be persisted across posts
to the server, but you don't want the control or it's value visible to the user. For
example, when editing and updaing an employee record, we don't want the user to see
the EmployeeId. So, we will store the EmployeeId in a HiddenField, so that it can then be
used on the server to update the correct employees record.

SQL Script
Create Table tblEmployees
(
Id int Primary Key,
Name nvarchar(50),
Gender nvarchar(10),
DeptName nvarchar(10)
)

Insert into tblEmployees values(201, 'Mark', 'Male', 'IT')


Insert into tblEmployees values(202, 'Steve', 'Male', 'Payroll')
Insert into tblEmployees values(203, 'John', 'Male', 'HR')

HTML of the ASPX Page


<asp:HiddenField ID="HiddenField1" runat="server" />
<table>
<tr>
<td>Name:</td>
<td>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Gender:</td>
<td>
<asp:TextBox ID="txtGender" runat="server"></asp:TextBox>
</td>
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

</tr>
<tr>
<td>Department:</td>
<td>
<asp:TextBox ID="txtDept" runat="server"></asp:TextBox>
</td>
</tr>
</table>
<asp:Button ID="Button1" runat="server" Text="Update Employee"
onclick="Button1_Click" />&nbsp;
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Load Employee" />

Code-Behind code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadEmployee();
}
}

private void LoadEmployee()


{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
string sqlQuery = "Select Id, Name, Gender, DeptName from tblEmployees where
Id=202";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
con.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
txtName.Text = rdr["Name"].ToString();
txtGender.Text = rdr["Gender"].ToString();
txtDept.Text = rdr["DeptName"].ToString();
HiddenField1.Value = rdr["Id"].ToString();
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

}
}
}
}

protected void Button1_Click(object sender, EventArgs e)


{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
string sqlQuery = "Update tblEmployees set Name=@Name, Gender=@Gender,
DeptName=@DeptName where Id=@Id";
SqlCommand cmd = new SqlCommand(sqlQuery, con);

cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@Gender", txtGender.Text);
cmd.Parameters.AddWithValue("@DeptName", txtDept.Text);
cmd.Parameters.AddWithValue("@Id", HiddenField1.Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();

txtName.Text = "";
txtDept.Text = "";
txtGender.Text = "";
}
}

protected void Button2_Click(object sender, EventArgs e)


{
LoadEmployee();
}
HiddenField:
1. Value property of the HiddenFiled is used to Get or set the value.
2. The value is stored as string
3. ViewState uses HiddenFiled to maintain state across postback
4. HiddenField is rendered as an <input type= "hidden"/> element
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

Alternatives for HiddenField:


View state, QueryStrings, session state, and cookies can be used as an alternative for
HiddenField. Session state and cookies will be accessible from other pages as well, and
will be available untill their timeout has reached. Where asViewState and HiddenField
data, is available only on that page and the data is lost when you navigate away from
the page.

Advantages of HiddenField:
HiddenFiled data is lost when you navigate away from the page. Doesn't require any
explicit cleanup task.
HiddenField is accessible to client-side scripts
<script type="text/javascript">
function GetHiddenFieldValue()
{
alert(document.getElementById('HiddenField1').value);
}
</script>

Disadvantage of HiddenField:
Hidden field data can be seen, by viewing the page source. Never, use HiddenFiled to
store confidential data

5. ViewState In ASP.NET
What is ViewState?
ViewState is a client side mechanism. It stores the value in the page itself. Preserving the
value of page controls between client to server and server to client is called "roundtrip".
It stores the page or control value in the mode of hidden fields. Viewing the source of
the page allows you to find the ViewState signature but stores the value in encrypted
format even though any programmer can de-encrypt the value.

Storing the value between postbacks is great, but it stores the data in the page itself,
that’s why the page becomes very heavy to load or takes time to render.

The ViewState is a dictionary kind of object which stores the value on the basis of
KEY/VALUE.

By default, the ViewState is enabled, but we can enable or disable ViewState on Page
level or Control level.
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

There are two properties on Page Level


1. ViewStateMode
2. EnableVIewState
3. ViewStateEncryptionMode = “Always” / “Auto” / “Never”
Example
1. <%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default.aspx.c
s"Inherits="_Default"EnableViewState="true"ViewStateMode="Enabled"Vi
ewStateEncryptionMode="Always"%>
There is one property on Control Level.
1. EnableViewState = “True” / “False”
Example
I took a list control on the page and switched to Properties of ListBox named
“lstPostBackDetail”.
You can see there is a property called EnableViewState = True/False.

How to store the value in ViewState?


ViewState stores the value in a Key/Value pair basis.
Syntax
ViewState[“KeyName”] = Object / String .etc.
Example
1. ViewState[“PageStartedDateTime”] = DateTime.Now;
2. Create a new WebSite project project called“ ViewStateExample”
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

Right click on project and select Add-->Add New Item and select WebForm.

Example 1
After successfully adding a new webform, now double click on Default.aspx file in
Solution Explorer and add four controls on the webpage.
1. ListBox
2. Button
Server
Server Control ID Description
Control
In this control EnableViewState="True"property is
ListBox lstViewStateEnabledList
true, that's why control retains the value of control
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

during postbacks.
Button btnViewStateEnabled Button to postbacks
In this control EnableViewState="False"property is
ListBox lstViewStateDisabledList false, that's why control doens't retain the value of
control during postbacks.
Button btnNormal Button to postbacks
By default, the first time page is executed on browser display it looks like this.

Both the listboxes display the same datetime while rendering for the first time on the
browser.

Check the ViewState functionality

Now, click on ViewState enabled ListBox Side Submit button.

You can see that it behaves in an additive attitude, which means it adds the datetime
value in the listbox because this listbox control's ViewState setting is ON by a property
called

EnableViewState="True"
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

Now, click on ViewState Disabled ListBox Side Submit button.

You can see that its ViewState disabled list box is empty on every postback and it can
stores only one entry, not more because this listbox control's ViewState setting is OFF
by a property called

EnableViewState="False"
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

6. Cookies in asp.net
Just like QueryStrings, Cookies can also be used to send data from one webform to
another. In general, web sites use cookies to store user preferences or other
information that is client-specific. Cookies store small amounts of information on the
client’s machine.

Cookies can be broadly classified into 2 types


1. Persistent cookies - Remain on the client computer, even after the browser is closed.
You can configure how long the cookies remain using the expires property of the
HttpCookie object.
2. Non-Persistent cookies - If you don't set the Expires property, then the cookie is
called as a Non-Persistent cookie. Non-Persistent cookies only remain in memory until
the browser is closed.

On WebForm1.aspx, user enters Name and Email. Let's write these values on to the
client's computer using cookies. Finally read the values from the cookie and display
them in WebForm2.aspx.

WebForm1.aspx HTML source:


<div style="font-family: Arial">
<table>
<tr>
<td colspan="2">
<h1>
This is WebForm1</h1>
</td>
</tr>
<tr>
<td>
<b>Name</b>
</td>
<td>
:<asp:TextBox ID="txtName" runat="server">
</asp:TextBox>
</td>
</tr>
<tr>
<td>
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

<b>Email</b>
</td>
<td>
:<asp:TextBox ID="txtEmail" runat="server">
</asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnSendData" runat="server"
Text="Go to WebForm2" onclick="btnSendData_Click" />
</td>
</tr>
</table>
</div>

WebForm1.aspx.cs code:
protected void btnSendData_Click(object sender, EventArgs e)
{
// Create the cookie object
HttpCookie cookie = new HttpCookie("UserDetails");
cookie["Name"] = txtName.Text;
cookie["Email"] = txtEmail.Text;
// Cookie will be persisted for 30 days
cookie.Expires = DateTime.Now.AddDays(30);
// Add the cookie to the client machine
Response.Cookies.Add(cookie);

Response.Redirect("WebForm2.aspx");
}

WebForm2.aspx HTML Source:


<div style="font-family: Arial">
<table>
<tr>
<td colspan="2">
<h1>This is WebForm2</h1>
</td>
</tr>
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

<tr>
<td>
<b>Name</b>
</td>
<td>
:<asp:Label ID="lblName" runat="server">
</asp:Label>
</td>
</tr>
<tr>
<td>
<b>Email</b>
</td>
<td>
:<asp:Label ID="lblEmail" runat="server">
</asp:Label>
</td>
</tr>
</table>
</div>

WebForm2.aspx.cs Code:
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["UserDetails"];
if (cookie != null)
{
lblName.Text = cookie["Name"];
lblEmail.Text = cookie["Email"];
}
}
How to Check if cookies are enabled or disabled in asp.net?
This is what we will discuss in this video session. Most of the articles on the internet,
states we can use Request.Browser.Cookies property to check, if the cookies are
enabled or disabled. This is incorrect.
if (Request.Browser.Cookies)
{
//Cookies Enabled
}
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

else
{
//Cookies Disabled
}

Request.Browser.Cookies property is used to check, if the browser supports


cookies. Most mordern browsers, support cookies. Irrespective of whether, the cookies
are enabled or disabled, if the browser supports cookies, Request.Browser.Cookies
always returns true. So use this property to check if the browser supports cookies and
not to check if the cookies are enabled or disabled.
if (Request.Browser.Cookies)
{
//Broswer supports cookies
}
else
{
//Broswer does not supports cookies
}
So, the next question is, how do we check, if cookies are enabled or disabled?
1. Write a Test Cookie
2. Redirect to the same page
3. Read the Test Cookie
4. If Cookies preseent - Cookies are enabled
5. Else - Cookies are disabled.

To disable cookies in Internet Explorer(IE 9)


1. Click on Tools
2. Select Internet Options
3. Click on the Privacy tab
4. Click the Advanced button, under settings
5. Check Override automatics cookie handling check box
6. Select Block radio button under First Party cookies and Third Party Cookie

The above steps disable cookies, only for the internet zone. If you are testing code on
your local machine, and to disable cookies for localhost
1. Run the application
2. Press F12, to open developer tools
3. Then Select, Cache - Disable Cookies
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

WebForm1.aspx HTML source:


<div style="font-family: Arial">
<table>
<tr>
<td colspan="2">
<h1>
This is WebForm1</h1>
</td>
</tr>
<tr>
<td>
<b>Name</b>
</td>
<td>
:<asp:TextBox ID="txtName" runat="server">
</asp:TextBox>
</td>
</tr>
<tr>
<td>
<b>Email</b>
</td>
<td>
:<asp:TextBox ID="txtEmail" runat="server">
</asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnSendData" runat="server"
Text="Go to WebForm2" onclick="btnSendData_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblMessage" runat="server"
ForeColor="Red" Font-Bold="true">
</asp:Label>
</td>
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

</tr>
</table>
</div>

WebForm1.aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Check if the browser supports cookies
if (Request.Browser.Cookies)
{
if (Request.QueryString["CheckCookie"] == null)
{
// Create the test cookie object
HttpCookie cookie = new HttpCookie("TestCookie", "1");
Response.Cookies.Add(cookie);
// Redirect to the same webform
Response.Redirect("WebForm1.aspx?CheckCookie=1");
}
else
{
//Check the existence of the test cookie
HttpCookie cookie = Request.Cookies["TestCookie"];
if (cookie == null)
{
lblMessage.Text = "We have detected that, the cookies are disabled on your
browser. Please enable cookies.";
}
}
}
else
{
lblMessage.Text = "Browser doesn't support cookies. Please install one of the
modern browser's that support cookies.";
}
}
}
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

protected void btnSendData_Click(object sender, EventArgs e)


{
// Create the cookie object
HttpCookie cookie = new HttpCookie("UserDetails");
cookie["Name"] = txtName.Text;
cookie["Email"] = txtEmail.Text;
// Cookie will be persisted for 30 days
//cookie.Expires = DateTime.Now.AddDays(30);
// Add the cookie to the client machine
Response.Cookies.Add(cookie);

Response.Redirect("WebForm2.aspx");
}

WebForm2.aspx HTML Source:


<div style="font-family: Arial">
<table>
<tr>
<td colspan="2">
<h1>This is WebForm2</h1>
</td>
</tr>
<tr>
<td>
<b>Name</b>
</td>
<td>
:<asp:Label ID="lblName" runat="server">
</asp:Label>
</td>
</tr>
<tr>
<td>
<b>Email</b>
</td>
<td>
:<asp:Label ID="lblEmail" runat="server">
</asp:Label>
</td>
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

</tr>
</table>
</div>

WebForm2.aspx.cs Code
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["UserDetails"];
if (cookie != null)
{
lblName.Text = cookie["Name"];
lblEmail.Text = cookie["Email"];
}
}
7. Asp.net session state
Just like Query strings, Session State variables can also be used to send data
from one webform to another.

Points to remember about session state variables:


1. Session state variables are stored on the web server by default, and are kept for the
life time of a session.
2. The default session state mode is InProc. We will discuss about different session state
modes in a later video session.
3. The life time of a session is determined by the timeout value in web.config file. The
default is 20 minutes. The time-out value can be adjusted according, to your application
requirements.
<sessionState mode="InProc" timeout="30"></sessionState>
4. Session state variables are available across all pages, but only for a given single
session. Session variables are like single-user global data.

5. It is always a good practice to check, if a session state variable is null before calling
any of its methods, such as ToString(). Otherwise, we may run into runtime
NullReferenceExceptions.
if (Session["Name"] != null)
{
lblName.Text = Session["Name"].ToString();
}
6. Application performance can be improved by disabling session state, if it's not
required. Session state can be turned off at the page or application level.
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

To turn of the session state at the page level, set EnableSessionState="False" in the page
directive
<%@ Page Language="C#" EnableSessionState="False" AutoEventWireup="true"
CodeBehind="WebForm1.aspx.cs" Inherits="AdoDemo.WebForm1" %>

To turn of the session state at the application level, set SessionState mode=false in
web.config file.
<sessionState mode="Off"></sessionState>

WebForm1.aspx HTML source


<div style="font-family: Arial">
<table>
<tr>
<td colspan="2">
<h1>
This is WebForm1</h1>
</td>
</tr>
<tr>
<td>
<b>Name</b>
</td>
<td>
:<asp:TextBox ID="txtName" runat="server">
</asp:TextBox>
</td>
</tr>
<tr>
<td>
<b>Email</b>
</td>
<td>
:<asp:TextBox ID="txtEmail" runat="server">
</asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

<asp:Button ID="btnSendData" runat="server"


Text="Go to WebForm2" onclick="btnSendData_Click" />
</td>
</tr>
</table>
</div>

WebForm1.aspx.cs code:
protected void btnSendData_Click(object sender, EventArgs e)
{
Session["Name"] = txtName.Text;
Session["Email"] = txtEmail.Text;
Response.Redirect("WebForm2.aspx");
}

WebForm2.aspx HTML Source:


<div style="font-family: Arial">
<table>
<tr>
<td colspan="2">
<h1>This is WebForm2</h1>
</td>
</tr>
<tr>
<td>
<b>Name</b>
</td>
<td>
:<asp:Label ID="lblName" runat="server">
</asp:Label>
</td>
</tr>
<tr>
<td>
<b>Email</b>
</td>
<td>
:<asp:Label ID="lblEmail" runat="server">
</asp:Label>
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

</td>
</tr>
</table>
</div>

WebForm2.aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Name"] != null)
{
lblName.Text = Session["Name"].ToString();
}
if (Session["Email"] != null)
{
lblEmail.Text = Session["Email"].ToString();
}
}

8. Asp.net Application state


1.Application State variables are available across all pages and across all sessions.
Application State variables are like multi-user global data.

2. Application State variables are stored on the web server.

3. Application State variables are cleared, only when the process hosting the
application is restarted, that is when the application ends.

4. Application State variables are not shared across a Web Farm or a Web Garden.

5. Application state variables are not thread safe. Lock and Unlock methods of the
application class must be used to protect against race conditions, deadlocks, and
access violations.
Application.Lock();
Application["GlobalVariable"] = (int)Application["GlobalVariable"] + 1;
Application.UnLock();

Please Note: In this example, we are using application state variables to send data
from one web form to another. If the requirement, is just to send data from
webform to another, you should consider other alternatives.
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

6. Use application state variables only, when the variables need to have global
access and when you need them for entire time, during the life time of an
application. Cache object, can be used, as an alternative, if you need to have global
access for a certain duration.
Application state variables are global, and all sessions have access to them. So,
these variables can be used to track the number of users online. Every time a new
user connects to your application, we want to increase the number of users online by
1. Along, the same lines, when ever a user session ends, then we need to decrease
the number of users online by 1. But how do we know, when a new user connects to
our application. Session_Start() event is fired when ever a new session is established.
When the session ends, Session_End() event is fired. The event handlers are in
global.asax file.
Global.asax code:
public class Global : System.Web.HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
// Code that runs when the application starts
Application["UsersOnline"] = 0;
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new user session is started
Application.Lock();
Application["UsersOnline"] = (int)Application["UsersOnline"] + 1;
Application.UnLock();
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when an existing user session ends.
Application.Lock();
Application["UsersOnline"] = (int)Application["UsersOnline"] - 1;
Application.UnLock();
}
}
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

The application state variable is accessible across the entire application. Copy and
paste the following code in the Page_Load() event of any webform.
if (Application["UsersOnline"] != null)
{
Response.Write("Number of Users Online = " +
Application["UsersOnline"].ToString());
}

By default, the browser instances share the session cookie. To have a new session id
assigned, when a new browser instance requests the webform,
set cookieless="true" for the sessionstate element in web.config. Now run the
application. The following message should be displayed.
Number of Users Online = 1

Open a new browser window, copy and paste the URL from the other window. Make
sure to delete the session-id, so the web server, assigns a new session-id to the second
request. At this point, Number of Users Online should be incremented to 2.

Global.asax file in ASP.NET


Have you ever felt the need of writing logic at the application level; precisely a
location or a file where you could handle events or errors at the application level? Well
if yes, then enter the Global.asax. Using this file, you can define event handlers with
application-wide or session-wide scope. In this article, we will explore the application
and session level events exposed in the Global.asax file and how we can utilize these
events in our applications.
The Global.asax, also known as the ASP.NET application file, is located in the root
directory of an ASP.NET application. This file contains code that is executed in response
to application-level and session-level events raised by ASP.NET or by HTTP modules. You
can also define ‘objects’ with application-wide or session-wide scope in the Global.asax
file. These events and objects declared in the Global.asax are applied to all resources in
that web application.
Note 1: The Global.asax is an optional file. Use it only when there is a need for it.
Note 2: If a user requests the Global.asax file, the request is rejected. External users
cannot view the file.
The Global.asax file is parsed and dynamically compiled by ASP.NET. You can deploy this
file as an assembly in the \bin directory of an ASP.NET application.
How to create Global.asax
Adding a Global.asax to your web project is quiet simple.
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

Open Visual Studio 2005 or 2008 > Create a new website > Go to the Solution Explorer >
Add New Item > Global Application Class > Add.
Examining the methods related to the events in Global.asax
There are 2 ‘set’ of methods that fire corresponding to the events. The first set
which gets invoked on each request and the second set which does not get invoked on
each request. Let us explore these methods.
Methods corresponding to events that fire on each request
Application_BeginRequest() – fired when a request for the web application comes in.
Application_AuthenticateRequest –fired just before the user credentials are
authenticated. You can specify your own authentication logic over here.
Application_AuthorizeRequest() – fired on successful authentication of user’s
credentials. You can use this method to give authorization rights to user.
Application_ResolveRequestCache() – fired on successful completion of an authorization
request.
Application_AcquireRequestState() – fired just before the session state is retrieved for
the current request.
Application_PreRequestHandlerExecute() - fired before the page framework begins
before executing an event handler to handle the request.
Application_PostRequestHandlerExecute() – fired after HTTP handler has executed the
request.
Application_ReleaseRequestState() – fired before current state data kept in the session
collection is serialized.
Application_UpdateRequestCache() – fired before information is added to output cache
of the page.
Application_EndRequest() – fired at the end of each request
Methods corresponding to events that do not fire on each request
Application_Start() – fired when the first resource is requested from the web server and
the web application starts.
Session_Start() – fired when session starts on each new user requesting a page.
Application_Error() – fired when an error occurs.
Session_End() – fired when the session of a user ends.
Application_End() – fired when the web application ends.
Application_Disposed() - fired when the web application is destroyed.
Show me an example!!
Let us see an example of how to use the Global.asax to catch unhandled errors that
occur at the application level.
To catch unhandled errors, do the following. Add a Global.asax file (Right click project >
Add New Item >Global.asax). In the Application_Error() method, add the following code:
DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

C#
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error in: " + Request.Url.ToString() +
". Error Message:" + objErr.Message.ToString();

Caching in asp.net -
Caching improves the performance and scalability of an application. Caching is
the technique of storing frequently used data/pages in memory. Let us practically
understand caching, with an example.
Create tblproducts table in sql server
Create Table tblProducts
(
[Id] int identity primary key,
[Name] nvarchar(50),
[Description] nvarchar(250)
)

Populate tblProducts with sample data


Insert into tblProducts values ('Laptops', 'Dell Laptops')
Insert into tblProducts values ('iPhone', 'iPhone 4S')
Insert into tblProducts values ('LCD TV', 'Samsung LCD TV')
Insert into tblProducts values ('Desktop', 'HP Desktop Computer')
Create "spGetProducts" stored procedure. In this procedure we are using WAITFOR
DELAY, to block the execution of the stored procedure for 5 seconds. In real time, we
may have large tables, where the query processing can take some time before the data
is returned. Table "tblProducts" is a very small table, with only 4 rows. So the stored
procedure "spGetProducts" would execute in a fraction of second. Just to simulate
artifical query processing time of 5 seconds, we are using WAITFOR DELAY.
Create Procedure spGetProducts
As
Begin
Waitfor Delay '00:00:05'

Select Id, Name, Description


DOODHASKAHAR MAHAVIDYALYA, BIDRI Teacher - S.S. Mithari
DEPARTMENT OF COMPUTER SCIENCE
Course Code- DSE-22E Computer Paper X B.Sc. Part-III Computer Science
Sem- 2 UNIT NO.2- ASP.Net State Management.

from tblProducts
End

Now, let us invoke the stored procedure in an asp.net web application, and display the
"Products" data in a gridview control. Drag and drop a "gridview" control onto the web
form. Copy and paste the following code in the code-behind file Page_Load() event.
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection(CS);
SqlDataAdapter da = new SqlDataAdapter("spGetProducts", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet DS = new DataSet();
da.Fill(DS);
GridView1.DataSource = DS;
GridView1.DataBind();
Also make sure you have the following "using" declarations
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
At this point, if you run the application, the page takes about 5 seconds to load. This is
because, when you request the webform, the web server has to process the web form
events, execute the stored procedure, create objects, generate HTML and send that
HTML to the client broswer.
Now let us cache the webform. To cache a webform, use the @OutputCache page
directive. The @OutputCache directive has 2 mandatory attributes
Duration - Specifies the time in seconds for which the webform should be cached
VaryByParam - Cache multiple responses of a single webform. For now set the value to
"None". We will discuss about "VaryByParam" in a later video.
Webform with the following "OutputCache" directive is cached for 30 seconds.
<%@ OutputCache Duration="30" VaryByParam="None" %>
When any user requests this Web form for the first time, the web server will process the
web form events, execute the stored procedure, create objects, generate HTML and
send that HTML to the client browser, and retains a copy of the response in memory for
the next 30 seconds. Any subsequent requests during that time receive the cached
response.

After the cache duration has expired, the next request for the Web form, has to process
the web form events, execute the stored procedure, create objects, generate HTML,
which is then cached for another 30 seconds. So this web form is processed by the
server, once every 30 second, at the most.

You might also like