Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter 8 Slides

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 58

Chapter 8

How to work with state,


cookies, and URL
encoding

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 1
Objectives
Applied
1. Given the specifications for an application that requires the use of
state, cookies, or URL encoding, develop the application.
Knowledge
1. Describe the use of view state.
2. Describe the way that session state works, with the focus on the
session state object and the session ID.
3. Describe the events that are typically used to trigger the event
handlers that retrieve and save session state items.
4. Describe the use of the Cookieless attribute for the session state
element in the Web.config file.
5. Describe the use of application state and caching.
6. Distinguish between an application state object and a cache object.

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 2
Objectives (cont.)
7. Explain how the Global.asax file for an application is used with
application state.
8. Describe the use of cookies, including session cookies and persistent
cookies.
9. Describe the use of URL encoding.

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 3
View state concepts
 View state provides for retaining the values of page and control
properties that change from one execution of a page to another.
 Before ASP.NET sends a page back to the client, it determines
what changes the program has made to the properties of the page
and its controls.
 These changes are encoded in a string that’s assigned to the value
of a hidden input field named _VIEWSTATE.
 When the page is posted back to the server, the _VIEWSTATE
field is sent back to the server along with the HTTP request. Then,
ASP.NET retrieves the property values from the _VIEWSTATE
field and uses them to restore the page and control properties.
 ASP.NET also uses view state to save the values of the page
properties it uses, such as IsPostBack.

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 4
View state concepts (cont.)
 View state is not used to restore data entered by a user into a text
box or any other input control unless the control responds to
change events.
 If view state is enabled for a data-bound control, the control will
not be bound again when the page is reposted. Instead, the
control’s values will be restored from view state.

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 5
Two cases when you may want
to disable view state
 When restoring the control properties for a page affects the way
you want the form to work, you may want to disable view state for
one or more controls.
 When the size of the view state field gets so large that it affects
performance, you may want to disable view state for one or more
controls or for an entire page.

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 6
How to disable view state
For a control
 Set the control’s EnableViewState property to False.
For an entire page
 Set the EnableViewState property of the Page directive to
False.
For an entire application
 Set the EnableViewState attribute of the pages element in the
system.web element of the Web.config file to False.

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 7
How to enable view state for selected controls
 Set the EnableViewState property of the page and the controls
whose view state you want to enable to True.
 Set the ViewStateMode property of the Page directive to
Disabled.
 Set the ViewStateMode property of the selected controls to
Enabled.

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 8
How to determine the size of view state
for a page
 Enable the page’s trace feature by setting the Trace attribute of the
Page directive to True as described in chapter 5.
 Scroll down to the Control Tree section of the trace output to see
the number of bytes of view state used by the page and its
controls.

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 9
Common indexer of the StateBag class
[name]

Common properties of the StateBag class


Count
Keys
Values

Common methods of the StateBag class


Add(name, value)
Clear()
Remove(name)

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 10
A statement that adds or updates
a view state item
ViewState.Add("TimeStamp", DateTime.Now);

Another way to add or update a view state item


ViewState["TimeStamp"] = DateTime.Now;

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 11
A statement that retrieves the value
of a view state item
DateTime timeStamp = (DateTime) ViewState["TimeStamp"];

A statement that removes an item from view state


ViewState.Remove("TimeStamp");

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 12
Common indexer of the HttpSessionState class
[name]

Common properties of the HttpSessionState class


SessionID
Count

Common methods of the HttpSessionState class


Add(name, value)
Clear()
Remove(name)

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 13
A statement that adds or updates
a session state item
Session["Email"] = email;

A statement that retrieves the value


of a session state item
string email = Session["Email"].ToString();

A statement that removes an item


from session state
Session.Remove("Email");

A statement that retrieves a session state item


from a non-page class
string email =
HttpContext.Current.Session["Email"].ToString();

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 14
The page events that can be used
to get and save session state data
Event Handler name
Load Page_Load
PreRender Page_PreRender

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 15
A Load event handler that gets
the session state object named cart
private CartItemList cart;
protected void Page_Load(object sender, EventArgs e)
{
cart = CartItemList.GetCart();
if (!IsPostBack) DisplayCart();
}

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 16
A Click event handler
that updates the cart object
protected void btnRemove_Click(object sender,
EventArgs e)
{
if (cart.Count > 0)
{
if (lstCart.SelectedIndex > -1)
{
cart.RemoveAt(lstCart.SelectedIndex);
DisplayCart();
}
else
{
lblMessage.Text =
"Please select the item you want to remove.";
}
}
}

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 17
A PreRender event handler
that updates a value in the cart object
protected void Page_PreRender(object sender, EventArgs e)
{
cart["Count"] = sessionCount;
}

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 18
Four modes for storing session state data
 In-process
 State Server
 SQL Server
 Custom

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 19
Two options for tracking session IDs
 Cookie-based
 Cookieless

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 20
Attributes of the session state element
in the Web.config file
Mode
Cookieless
Timeout
StateConnectionString
SqlConnectionString
AllowCustomSqlDatabase

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 21
A sessionState element in the Web.config file
that uses in-process mode
<system.web>
<sessionState mode="InProc"
cookieless="AutoDetect"
timeout="30" />
</system.web>

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 22
Application concepts
 An ASP.NET application is the collection of pages, code, and
other files within a single directory on a web server.
 An application begins when the first user requests a page that’s a
part of the application. Then, ASP.NET initializes the application
before it processes the request for the page.
 As part of its initialization, ASP.NET creates
an application object from the HttpApplication class
an application state object from the HttpApplicationState class
a cache object from the Cache class.
 These objects exist for the duration of the application, and items
stored in application state or cache are available to all users of the
application.
 Once an application has started, it doesn’t normally end until the
web server is shut down.

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 23
Cache concepts
 Items stored in the cache object don’t necessarily stay in server
memory until the application ends.
 They can be set with an expiration date, and they can be
scavenged by the server to recover memory when memory is low.
 The cache object is typically used to store data that changes
infrequently, such as a list of states or countries.

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 24
Application state concepts
 Items stored in the application state object stay in server memory
until they are specifically removed, or until the application ends.
 Application state is most appropriate for storing small items of
data that change as an application executes.
 To make sure the application object is not accessed by more than
one user at a time, it should be locked while updating and
unlocked when the update is completed.

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 25
Common indexer of the HttpApplicationState
and Cache classes
[name]

Common property of the HttpApplicationState


and Cache classes
Count

Common methods of the HttpApplicationState


and Cache classes
Add(name, value)
Clear()
Remove(name)

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 26
The Insert method of the Cache class
Insert(name, value, dependency,
absolute, sliding)

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 27
Common methods
of the HttpApplicationState class
Clear()
Lock()
Unlock()

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 28
Two statements that add items
to application state and cache
Application.Add("ClickCount", 0);
Cache.Add("states", states);

Two statements that retrieve an item


from application state and cache
int applicationCount =
Convert.ToInt32(Application["ClickCount"]);
List<string> states = (List<string>)Cache["states"];

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 29
Two statements that retrieve an item
from a non-page class
int applicationCount =
Convert.ToInt32(HttpContext.Current.Application[
"ClickCount"]);
List<string> states =
(List<string>)HttpContext.Current.Cache["states"];

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 30
A statement that adds an item to cache
with an absolute expiration time
Cache.Insert("states", states, null,
DateTime.Now.AddMinutes(20),
System.Web.Caching.Cache.NoSlidingExpiration);

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 31
Four common application events
Application_Start
Application_End
Session_Start
Session_End

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 32
A Global.asax file that creates an object
in application state
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender,
EventArgs e)
{
// Code that runs on application startup
Application.Add("HitCount",
HalloweenDB.GetHitCount());
}
protected void Application_End(object sender,
EventArgs e)
{
// Code that runs on application shutdown
HalloweenDB.UpdateHitCount(
Application["HitCount"]);
}

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 33
A Global.asax file (cont.)
protected void Session_Start(object sender,
EventArgs e)
{
// Code that runs when a new session is started
Application.Lock();
int hitCount =
Convert.ToInt32(
Application["HitCount"]) + 1;
Application["HitCount"] = hitCount;
Application.UnLock();
}
}

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 34
Examples of cookies
ASP.NET_SessionId=jsswpu5530hcyx2w3jfa5u55

Email=grace@yahoo.com

user_ID=4993

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 35
Two ways to create a cookie
New HttpCookie(name)
New HttpCookie(name, value)

Common properties of the HttpCookie class


Expires
Name
Secure
Value

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 36
Code that creates a session cookie
HttpCookie nameCookie
= new HttpCookie("UserName", userName);

Code that creates a persistent cookie


HttpCookie nameCookie = new HttpCookie("UserName");
nameCookie.Value = userName;
nameCookie.Expires = DateTime.Now.AddYears(1);

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 37
The HttpCookieCollection class
Indexer
[name]
Common property
Count
Common methods
Add(cookie)
Clear()
Remove(name)

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 38
A method that creates a new cookie
and adds it to the HttpResponse object
private void AddCookie()
{
HttpCookie nameCookie =
new HttpCookie("UserName", txtUserName.Text);
nameCookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(nameCookie);
}

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 39
A method that retrieves the value of a cookie
from the HttpRequest object
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
if (!(Request.Cookies["UserName"] == null))
lblUserName.Text = "Welcome back, " +
Request.Cookies["UserName"].Value + ".";
}

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 40
A method that deletes a persistent cookie
private void DeleteCookie()
{
HttpCookie nameCookie = new HttpCookie("UserName");
nameCookie.Expires = DateTime.Now.AddSeconds(-1);
Response.Cookies.Add(nameCookie);
}

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 41
An IE dialog box with disabled cookies

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 42
How to enable or disable cookies
for Internet Explorer
1. Click the Tools icon to the right of the address bar, then select
Internet Options.
2. Select the Privacy tab, then use the slider control in the Settings
group to set the security level to accept or block cookies.
3. To enable or disable persistent cookies and session cookies
separately, click the Advanced button and select from the
advanced privacy settings.

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 43
How to enable or disable cookies
for Google Chrome
1. Click the menu icon to the right of the address bar, and then
select Settings.
2. Scroll to the bottom of the page and click on the Show
Advanced Settings link.
3. Click the Content Settings button in the Privacy group, then
select the Block Sites From Setting Any Data button.

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 44
How to enable or disable cookies
for Mozilla Firefox
1. Click the menu icon to the right of the address bar, and then
select Options.
2. Click the Privacy icon. Then, select the Use Custom Settings for
History option from the Firefox Will drop-down list.
3. Check or uncheck the Accept Cookies From Sites option, and
select an item from the Keep Until drop-down list.

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 45
Two URLs with query strings
~/Order.aspx?cat=costumes
~/Order.aspx?cat=props&prod=rat01

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 46
A hyperlink with a URL
that includes a query string
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl=
"~/Product.aspx?cat=fx&amp;prod=fog01">Fog machine
</asp:HyperLink>

An anchor element with a URL


that includes a query string
<a href="product.aspx?cat=fx&prod=fog01">Fog machine</a>

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 47
Statements that retrieve the values
of the query string attributes
string categoryID = Request.QueryString["cat"];
string productID = Request.QueryString["prod"];

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 48
Code that uses a URL with a query string
in a Redirect method
Response.Redirect("~/Order.aspx?cat=" + categoryID);

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 49
An SEO-friendly URL
~/Order.aspx/props/rat01

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 50
An Order page that uses a cookie
and application state

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 51
The CheckOut page

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 52
The aspx code for the welcome message
and the footer on the Order page
<main>
...
<div class="col-sm-12">
<asp:Label ID="lblWelcome" runat="server"
CssClass="text-capitalize text-info">
</asp:Label>
</div>
...
</main>
<footer class="text-center">Cache Timestamp:
<asp:Label ID="lblCacheTimestamp" runat="server">
</asp:Label>
<br />
Number of Page Hits:
<asp:Label ID="lblPageHits" runat="server">
</asp:Label>
</footer>

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 53
The critical C# code for the Order page
...
using System.Web.Caching;

protected void Page_Load(object sender, EventArgs e)


{
// bind drop-down list and update page hit count
// on first load
if (!IsPostBack)
{
ddlProducts.DataBind();
Application.Lock();
int hitCount = Convert.ToInt32(
Application["HitCount"]);
hitCount++;
Application["HitCount"] = hitCount;
Application.UnLock();
lblPageHits.Text = hitCount.ToString();
}
// get and show product data on every load
...

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 54
The critical C# code for the Order page (cont.)
// get firstname from cookie and set welcome message
// if it exists
HttpCookie firstName = Request.Cookies["FirstName"];
if (firstName != null)
lblWelcome.Text = "<h4>welcome back, " +
firstName.Value + "!</h4>";

// get timestamp from cache, then display it


// or set timestamp in cache to now plus 10,
// then display
object cacheTimestamp = Cache.Get("Timestamp");
if (cacheTimestamp == null)
{
cacheTimestamp = DateTime.Now;
Cache.Insert("Timestamp", cacheTimestamp, null,
DateTime.Now.AddMinutes(10),
Cache.NoSlidingExpiration);
}
lblCacheTimestamp.Text = cacheTimestamp.ToString();
}

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 55
The critical C# code for the Check Out page
protected void btnContinue_Click(object sender,
EventArgs e)
{
if (IsValid)
{
DateTime expiry = DateTime.Now.AddMinutes(5);
SetCookie("FirstName", txtFirstName.Text,
expiry);
SetCookie("LastName", txtLastName.Text, expiry);
}
Response.Redirect("~/Order.aspx");
}

private void SetCookie(string name, string value,


DateTime expiry)
{
HttpCookie cookie = new HttpCookie(name, value);
cookie.Expires = expiry;
Response.Cookies.Add(cookie);
}

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 56
Extra 8-1 Use session state
to store reservation data

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 57
Extra 8-2 Use cookies to store user information

© 2016, Mike Murach & Associates, Inc.


Murach's ASP.NET 4.6 with C# 2015 C8, Slide 58

You might also like