This document provides objectives and content about working with state, cookies, and URL encoding in ASP.NET applications. It discusses view state, session state, application state, caching, cookies, and URL encoding. Key points covered include how each type of state works, common properties and methods for accessing state, and configuration options like disabling view state and setting the session state mode. Events for getting and saving session state are also identified.
This document provides objectives and content about working with state, cookies, and URL encoding in ASP.NET applications. It discusses view state, session state, application state, caching, cookies, and URL encoding. Key points covered include how each type of state works, common properties and methods for accessing state, and configuration options like disabling view state and setting the session state mode. Events for getting and saving session state are also identified.
This document provides objectives and content about working with state, cookies, and URL encoding in ASP.NET applications. It discusses view state, session state, application state, caching, cookies, and URL encoding. Key points covered include how each type of state works, common properties and methods for accessing state, and configuration options like disabling view state and setting the session state mode. Events for getting and saving session state are also identified.
This document provides objectives and content about working with state, cookies, and URL encoding in ASP.NET applications. It discusses view state, session state, application state, caching, cookies, and URL encoding. Key points covered include how each type of state works, common properties and methods for accessing state, and configuration options like disabling view state and setting the session state mode. Events for getting and saving session state are also identified.
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.
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.
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.
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.
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.
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.
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.
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.
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"];
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
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(); }
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; }
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
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>
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.
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.
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.
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"];
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"];
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);
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"]); }
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(); } }
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)
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); }
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 + "."; }
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); }
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.
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.
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.
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&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>
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"];
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);
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>
{ // 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 ...
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(); }