• The Problem of State• View State• The ViewState Collection• Cross-Page Posting• The Query String• Cookies• Session State...
• Stateless HTTP connection.• Additional steps required to retain information for  a longer period of time or over the lif...
View state uses a hidden field that ASP.NET automaticallyinserts in the final, rendered HTML of a web page.It’s a perfect ...
• Every item in a View State is stored in a separate “slot”  using a unique string name.• ViewState["Counter"] = 1;• ViewS...
ASP.NET runs the view state through a hashingalgorithm (with the help of a secret key value). Thehashing algorithm creates...
If your view state contains some information you wantto keep secret, you can enable view state encryption.You can turn on ...
You can store your own objects in view state just aseasily as you store numeric and string types.However, to store an item...
One of the most significant limitations with view stateis that it’s tightly bound to a specific page.If the user navigates...
With Cross-Page Posting one page can send the user toanother page, complete with all the information for thatPage.The infr...
Response.Redirect("newpage.aspx?recordID=10");You can send multiple parameters as long asthey’re separated with an ampersa...
• Information is limited to simple strings, which mustcontain URL-legal characters.• Information is clearly visible to the...
One potential problem with the query string is that somecharacters aren’t allowed in a URL. Furthermore, somecharacters ha...
Cookies are small files that are created in the webbrowser’s memory (if they’re temporary) or on theclient’s hard drive (i...
•   They’re limited to simple string information•   They’re easily accessible and readable if the user    finds and opens ...
using System.Net;// Create the cookie object.HttpCookie cookie = new HttpCookie("Preferences");// Set a value in it.cookie...
You retrieve cookies by cookie name using theRequest.Cookies collection:HttpCookie cookie = Request.Cookies["Preferences"]...
An application might need to store and access complexinformation such as custom data objects, which can’tbe sent through a...
ASP.NET tracks each session using a unique 120-bitidentifier.ASP.NET uses a proprietary algorithm to generate this value,t...
Using cookies: In this case, the session ID is transmitted ina special cookie (named ASP.NET_SessionId), whichASP.NET crea...
• If the user closes and restarts the browser.• If the user accesses the same page through a  different browser window, al...
You can interact with session state using theSystem.Web.SessionState.HttpSessionStateclass which is provided in an ASP.NET...
lblSession.Text = "Session ID: " + Session.SessionID;lblSession.Text += "<br />Number of Objects: ";lblSession.Text += Ses...
Chapter 8   part1
Upcoming SlideShare
Loading in …5
×

Chapter 8 part1

525 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
525
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
14
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Chapter 8 part1

  1. 1. • The Problem of State• View State• The ViewState Collection• Cross-Page Posting• The Query String• Cookies• Session State• Using Session Object to display Session Details
  2. 2. • Stateless HTTP connection.• Additional steps required to retain information for a longer period of time or over the lifetime of the application.• The information can be as simple as a user’s name or as complex as a stuffed full shopping cart for an ecommerce site.
  3. 3. View state uses a hidden field that ASP.NET automaticallyinserts in the final, rendered HTML of a web page.It’s a perfect place to store information that’s used formultiple postbacks in a single web page.The Web Server stores most of the properties of the WebControls of a requested page directly to its view state andretrieve it later when the page is posted back.
  4. 4. • Every item in a View State is stored in a separate “slot” using a unique string name.• ViewState["Counter"] = 1;• ViewState collection stores all items as basic objects so you also need to cast the retrieved value to the appropriate data type using the casting syntax• int counter;• counter = (int)ViewState["Counter"];
  5. 5. ASP.NET runs the view state through a hashingalgorithm (with the help of a secret key value). Thehashing algorithm creates a hash code. Which isadded at the end of the view state data and sent to thebrowser.When the page is posted back, ASP.NET then checkswhether the checksum it calculated matches the hashcode. If a malicious user changes part of the viewstate data, that doesn’t match.
  6. 6. If your view state contains some information you wantto keep secret, you can enable view state encryption.You can turn on encryption for an individual pageusing the ViewStateEncryptionMode property ofthe Page directive:<%@Page ViewStateEncryptionMode="Always" %>Or<configuration><system.web><pages viewStateEncryptionMode="Always" />...</system.web></configuration>
  7. 7. You can store your own objects in view state just aseasily as you store numeric and string types.However, to store an item in view state, ASP.NETmust be able to convert it into a stream of bytes sothat it can be added to the hidden input field in thepage. This process is called serialization.If your objects aren’t serializable (and by defaultthey’re not), you’ll receive an error message whenyou attempt to place them in view state.To make your objects serializable, you need to add aSerializable attribute before your class declaration.
  8. 8. One of the most significant limitations with view stateis that it’s tightly bound to a specific page.If the user navigates to another page, this informationis lost. Two basic techniques to transfer informationbetween pages are: Cross-page posting Query string
  9. 9. With Cross-Page Posting one page can send the user toanother page, complete with all the information for thatPage.The infrastructure that supports cross-page postbacks is aproperty named PostBackUrl which comes with ImageButton, LinkButton, and ButtonTo use cross-posting, you simply set PostBackUrl to thename of another web form.When the user clicks the button, the page will be posted tothat new URL with the values from all the input controls onthe current page.
  10. 10. Response.Redirect("newpage.aspx?recordID=10");You can send multiple parameters as long asthey’re separated with an ampersand (&):Response.Redirect("newpage.aspx?recordID=10&mode=full");The receiving can receive the values fromthe QueryString dictionary collection exposed bythe built-in Request object:string ID = Request.QueryString["recordID"];
  11. 11. • Information is limited to simple strings, which mustcontain URL-legal characters.• Information is clearly visible to the user and to anyoneelse who cares to eavesdrop on the Internet.• The enterprising user might decide to modify the querystring and supply new values, which your program won’texpect and can’t protect against.• Many browsers impose a limit on the length of a URL(usually from 1KB to 2KB). For that reason, you can’tplace a large amount of information in the query string.
  12. 12. One potential problem with the query string is that somecharacters aren’t allowed in a URL. Furthermore, somecharacters have special meaning. For example, theampersand (&) is used to separate multiple query stringparameters, the plus sign (+) is an alternate way to representa space, and the number sign (#) is used to point to aspecific bookmark in a web page.string url = "QueryStringRecipient.aspx?";url += "Item=" + Server.UrlEncode (lstItems. SelectedItem.Text) + "&";url += "Mode=" + chkDetails.Checked.ToString();Response.Redirect(url);
  13. 13. Cookies are small files that are created in the webbrowser’s memory (if they’re temporary) or on theclient’s hard drive (if they’re permanent).They work transparently without the user being awarethat information needs to be stored.They also can be easily used by any page in yourapplication and even be retained between visits,which allows for truly long-term storage.
  14. 14. • They’re limited to simple string information• They’re easily accessible and readable if the user finds and opens the corresponding file.• Some users disable cookies on their browsers, which will cause problems for web applications that require them.• Users might manually delete the cookie files stored on their hard drives.
  15. 15. using System.Net;// Create the cookie object.HttpCookie cookie = new HttpCookie("Preferences");// Set a value in it.cookie["LanguagePref"] = "English";// Add another value.cookie["Country"] = "US";// Add it to the current web response.Response.Cookies.Add(cookie);// This cookie lives for one year.cookie.Expires = DateTime.Now.AddYears(1);
  16. 16. You retrieve cookies by cookie name using theRequest.Cookies collection:HttpCookie cookie = Request.Cookies["Preferences"];if (cookie != null){language = cookie["LanguagePref"];}The only way to remove a cookie is by replacing itwith a cookie that has an expiration date that hasalready passed.HttpCookie cookie = new HttpCookie("Preferences");cookie.Expires = DateTime.Now.AddDays(-1);Response.Cookies.Add(cookie);
  17. 17. An application might need to store and access complexinformation such as custom data objects, which can’tbe sent through a query string.Or the application might have stringent securityrequirements that prevent it from storing informationabout a client in view state or in a custom cookie.Session state management allows you to store anytype of data in memory on the server. Every client thataccesses the application is given a distinct session ID.
  18. 18. ASP.NET tracks each session using a unique 120-bitidentifier.ASP.NET uses a proprietary algorithm to generate this value,thereby guaranteeing (statistically speaking) that the numberis unique and it’s random enough that a malicious user can’treverse-engineer or “guess” what session ID a given clientwill be using.This ID is the only piece of session-related information that istransmitted between the web server and the client.When the client presents the session ID, ASP.NET looks upthe corresponding session, retrieves the objects you storedpreviously, and places them into a special collection so theycan be accessed in your code.
  19. 19. Using cookies: In this case, the session ID is transmitted ina special cookie (named ASP.NET_SessionId), whichASP.NET creates automatically when the session collectionis used. This is the default.Using modified URLs: In this case, the session ID istransmitted in a specially modified (or munged) URL.This allows you to create applications that use sessionstate with clients that don’t support cookies.
  20. 20. • If the user closes and restarts the browser.• If the user accesses the same page through a different browser window, although the session will still exist if a web page is accessed through the original browser window. Browsers differ on how they handle this situation.• If the session times out due to inactivity.• If your web page code ends the session by calling the Session.Abandon() method.
  21. 21. You can interact with session state using theSystem.Web.SessionState.HttpSessionStateclass which is provided in an ASP.NET webpage as the built-in Session object.
  22. 22. lblSession.Text = "Session ID: " + Session.SessionID;lblSession.Text += "<br />Number of Objects: ";lblSession.Text += Session.Count.ToString();lblSession.Text += "<br />Mode: " + Session.Mode.ToString();lblSession.Text += "<br />Is Cookieless: ";lblSession.Text += Session.IsCookieless.ToString();lblSession.Text += "<br />Is New: ";lblSession.Text += Session.IsNewSession.ToString();lblSession.Text += "<br />Timeout (minutes): ";lblSession.Text += Session.Timeout.ToString();

×