Download presentation
Presentation is loading. Please wait.
1
ASP.NET State Management
* ASP.NET State Management Session State, Application State, View State Ventsislav Popov Crossroad Ltd. (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
2
Table of Contents ASP.NET Intrinsic Objects
* Table of Contents ASP.NET Intrinsic Objects State Management in Web Applications Cookies Hidden Fields Parameterized Addresses Page Execution Lifecycle ASP.NET State Management Client side – View State Server side – Application State, Session State Manipulating the HTTP response headers (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
3
Intrinsic Objects in ASP.NET
* Intrinsic Objects in ASP.NET Session, Application, Request, Response, … Although the object-oriented design and underlying code of ASP.NET is radically different from ASP, many of the most commonly used keywords and operators in ASP remain in ASP.NET. Familiar intrinsic objects such as Request, Response, Server, Application, and Session are part of ASP.NET and are used in much the same way as they were in ASP. These intrinsic objects are now properties of the System.Web.HttpContext class but because the objects are automatically created by ASP.NET when a new request for a Web resource is received and a new context is created, you can use them directly without having to instantiate new objects. (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
4
Intrinsic Objects in ASP.NET
* Intrinsic Objects in ASP.NET Intrinsic Objects in ASP.NET are available in the context of any Page or Control Application (HttpApplication class) Session (HttpSession class) Request (HttpRequest class) Response (HttpResponse class) Server (HttpServerUtility class) Context (HttpContext class) Cache (System.Web.Caching.Cache class) Бележки на автора: Вградени обекти в ASP.NET Application (HttpApplication class) Session (HttpSession class) Request (HttpRequest class) Response (HttpResponse class) Server (HttpServerUtility class) Context (HttpContext class) Cache (System.Web.Caching.Cache class) (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
5
HttpApplication HttpApplication keeps the application state
* HttpApplication HttpApplication keeps the application state Provides access to other intrinsic objects Properties Application, Context, Request, Response, Server, Session etc. Provide events for: Start of a new request Authentication Authorization Working with the cache End of a Request HttpApplication defines the methods, properties, and events that are common to all application objects in an ASP.NET application. This class is the base class for applications that are defined by the user in the Global.asax file. HttpApplication instances of the HttpApplication class are created in the ASP.NET infrastructure, not by the user directly. One instance of the HttpApplication class is used to process many requests in its lifetime. However, it can process only one request at a time. Thus, member variables can be used to store per-request data. Events: The BeginRequest event signals the creation of any given new request. This event is always raised and is always the first event to occur during the processing of a request. The AuthenticateRequest event signals that the configured authentication mechanism has authenticated the current request. Subscribing to the AuthenticateRequest event ensures that the request will be authenticated before processing the attached module or event handler. The AuthorizeRequest event signals that ASP.NET has authorized the current request. Subscribing to the AuthorizeRequest event ensures that the request will be authenticated and authorized before processing the attached module or event handler. ResolveRequestCache Event occurs when ASP.NET finishes an authorization event to let the caching modules serve requests from the cache, bypassing execution of the event handler (for example, a page or an XML Web service). (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
6
* HttpRequest HttpRequest contains information about the current HTTP request ApplicationPath – root path on the server Browser – type, platform, capabilities, etc. Cookies – get the cookies collection HttpMethod – GET / POST QueryString – e.g. ?id=7&lang=en ServerVariables – IIS server settings Url – the requested URL 1) HttpRequest enables ASP.NET to read the HTTP values sent by a client during a Web request. 2) The methods and properties of the HttpRequest class are exposed through the Request properties of the HttpApplication, HttpContext, Page, and UserControl classes. (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
7
HttpResponse HttpResponse contains information about the HTTP response
* HttpResponse HttpResponse contains information about the HTTP response ContentType – MIME type (e.g. image/gif) Charset – response encoding, e.g. UTF8 Cookies – sets cookies Expires – sets browser's cache expiration BufferOutput – buffer or not the response ClearHeaders(…), AddHeader(…) Write(…), BinaryWrite(…), WriteFile(…) – send text or binary data to the client HttpResponse encapsulates HTTP-response information from an ASP.NET operation. The methods and properties of the HttpResponse class are exposed through the Response property of the HttpApplication, HttpContext, Page, and UserControl classes. Some methods of the HttpResponse class are supported only in postback scenarios and not in asynchronous postback scenarios (BinaryWrite, Clear, ClearContent, ClearHeaders, Close, End, Flush, TransmitFile, Write, WriteFile, WriteSubstitution) (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
8
* HttpServerUtility HttpServerUtility provides helper methods for processing HTTP requests HtmlEncode(…) – escapes given HTML, e.g. "<img>" "<img>" HtmlDecode(…) – un-escapes escaped HTML UrlEncode(…) – encode string for the browser URL, e.g. "+.net 4" "%2B.net+4" UrlDecode(…) – decode url-encoded string MapPath(…) – returns the server-side path for given resource given as relative path HTML encoding makes sure that text is displayed correctly in the browser and not interpreted by the browser as HTML. For example, if a text string contains a less than sign (<) or greater than sign (>), the browser would interpret these characters as the opening or closing bracket of an HTML tag URL encoding ensures that all browsers will correctly transmit text in URL strings. Characters such as a question mark (?), ampersand (&), slash mark (/), and spaces might be truncated or corrupted by some browsers. As a result, these characters must be encoded in <a> tags or in query strings where the strings can be re-sent by a browser in a request string. MapPath returns the physical file path that corresponds to the specified virtual path on the Web server (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
9
Intrinsic Objects – Examples
* Intrinsic Objects – Examples bool isSecureConnection = Request.IsSecureConnection; Application.Add("key", "value"); string LabelResult.Text = Server.UrlEncode("Did you try ASP.NET 4.0?"); Response.ContentType = "text/html"; Response.Charset = "UTF-8"; string imageFileName = Server.MapPath("img/logo.gif"); Бележки на автора: Примерна употреба bool isSecureConnection = Request.IsSecureConnection - Gets a value indicating whether the HTTP connection uses secure sockets (that is, HTTPS). Application.Add("key", "value"); string strEncoded = Server.UrlEncode("Загорка"); Response.ContentType = "text/html"; - Gets or sets the HTTP MIME type of the output stream. Response.Charset = “UTF-8” - Gets or sets the HTTP character set of the output stream. string url = Request.Url; string browserType = Request.Browser.Type; (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
10
Intrinsic ASP.NET Objects
* Intrinsic ASP.NET Objects Live Demo (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
11
Redirecting to Another URL
* Redirecting to Another URL Response.Redirect("Login.aspx") Client-side redirection (uses HTTP 302 Moved) Lets the browser to request a new URL Changes the URL address in the browser Server.Transfer("WebTest.aspx") Server-side redirection Keeps the URL in the browser The browser does not even know about the redirection Бележки на автора: Пренасочване на изхода 1) Response.Redirect("Login.aspx") - Пренасочване от страна на клиента (client redirection). Променя адреса на Web браузъра. Response.Redirect sends HTTP code 302 down to the users browser along with the new URL location of the wanted page. HTTP Code 302 actually means ' The requested resource resides temporarily under a different URI'. After browser receives this code it tries to open the new location of the resource that was suggested by the server. This actually causes two requests to the server, first one to the original URL, and second to the new URL that is suggested via 302 response. All the Query Strings and Form variables are lost during the redirect and they are not available to the redirected URL. Also its important to say that the new URL can reside on the same server but also it can be on some other server and the redirected URL does not need to be .aspx page it can be regular HTML page also). 2) Server.Forward("WebForm1.aspx") - Пренасочване от страна на сървъра (server redirection). Запазва адреса на Web браузъра. На практика Web браузърът не разбира за пренасочването. In contrast to all this when we call Server.Transfer we do not initiate another request to the server, but the original request is simply rewritten and transfered to some other page on the same server. (This off course means that we can use it only to transfer requests to the pages on the same server, not to some other servers and we can only transfer to .aspx pages and not other page types like HTML, php etc). All posted Form variables and query strings can optionally remain available to the second Page where we transfered request (if we use second overload Server.Transfer(string path, bool preserveForm) and supply true for the second parameter). Otherwise the Form Variables and Query String are cleared just like when we use Redirect. Its also important to note that because of the way Server.Transfer works, after the transfer, the URL shown in the users Web Browser remains the original one that was requested, because browser has no knowledge that its request was transfered (transfer occurs on the server side). Response.Redirect should be used when: we want to redirect the request to some plain HTML pages on our server or to some other web server we don't care about causing additional roundtrips to the server on each request we do not need to preserve Query String and Form Variables from the original request we want our users to be able to see the new redirected URL where he is redirected in his browser (and be able to bookmark it if its necessary) Server.Transfer should be used when: we want to transfer current page request to another .aspx page on the same server we want to preserve server resources and avoid the unnecessary roundtrips to the server we want to preserve Query String and Form Variables (optionally) we don't need to show the real URL where we redirected the request in the users Web Browser (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
12
Client and Server Redirection
* Client and Server Redirection Live Demo (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
13
State Management: Standard Mechanisms in Web Applications
Cookies, Hidden fields, Parameterized Addresses
14
What is a Cookie? A small piece of information (up to 4KB)
* What is a Cookie? A small piece of information (up to 4KB) Sent to a browser by the Web server Saved locally at the client as a text file Sent by the browser in all subsequent requests Sent as an HTTP header Set-Cookie: UserID=baj.ivan; path=/; domain=devbg.org; Expires=Saturday, 17-Jan GMT A cookie, also known as a web cookie, browser cookie, and HTTP cookie, is a piece of text stored by a user's web browser. It consists of one or more name-value pairs containing bits of information, which may be encrypted for information privacy and data security purposes. Cookies may be set by the server with or without an expiration date. Cookies without an expiration date exist until the browser terminates, while cookies with an expiration date may be stored by the browser until the expiration date passes. Usage: Session management (shopping carts, autologins) Personalization (auto-filling purposes, language and other preferences) Tracking (recording users browsing habits) Cookie: UserID: baj.ivan; (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
15
* Cookie Properties Cookies is ASP.NET are represented by HttpCookie objects Expires Sets when the validity of the cookie expires Domain A domain to which the cookie belongs Path Sets the top level directory to which the cookie belongs 1) The class provides a type-safe way to create and manipulate (store, retrieve, and manage) individual HTTP cookies. ASP.NET includes two intrinsic cookie collections. The collection accessed through the Cookies collection of the HttpRequest object contains cookies transmitted by the client to the server in the Cookie header. The collection accessed through the Cookies collection of the HttpResponse object contains new cookies created on the server and transmitted to the client in the Set-Cookie HTTP response header. 2) Path: The virtual path to transmit with the cookie. The default is /, which is the server root. 3) Domain: The name of the domain to associate the cookie with. The default value is the current domain. (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
16
Working With Cookies For Web applications For client applications
* Working With Cookies For Web applications System.Web.HttpCookie For client applications System.Net.Cookie HttpRequest.Cookies contains the cookies received by the server HttpResponse.Cookies contains the cookies sent to the client ASP.NET includes two intrinsic cookie collections. The collection accessed through the Cookies collection of HttpRequest contains cookies transmitted by the client to the server in the Cookie header. The collection accessed through the Cookies collection of HttpResponse contains new cookies created on the server and transmitted to the client in the Set-Cookie header. After you add a cookie by using the HttpResponse.Cookies collection, the cookie is immediately available in the HttpRequest.Cookies collection, even if the response has not been sent to the client. (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
17
Working With Cookies – Example
* Working With Cookies – Example Creating a cookie that will be sent to the client Web browser: Reading a cookie received at the server: HttpCookie cookie = new HttpCookie("UserName", "baj.ivan"); Response.Cookies.Add(cookie); HttpCookie cookie = Request.Cookies["UserName"]; (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
18
* Cookies Live Demo (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
19
* What are Hidden Fields? Hidden form fields keep information, not visible in the Web page, sent on form submit ASP.NET HiddenField is a control, which renders as a standard HTML hidden field Not visible in the browser, but you can use it to store information directly in the page Insecure, because malicious user can easily access hidden fields and tamper it <input type="hidden" name="Language" value="English"> ASP.NET allows you to store information in a HiddenField control, which renders as a standard HTML hidden field. A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in the HTTP form collection along with the values of other controls. A hidden field acts as a repository for any page-specific information that you want to store directly in the page. Security Note It is easy for a malicious user to see and modify the contents of a hidden field. Do not store any information in a hidden field that is sensitive or that your application relies on to work properly. For more information, see ASP.NET State Management Recommendations. (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
20
Parameterized Addresses
* Parameterized Addresses Also known as query strings Setting the parameters in the URL of a page after the ‘?’ sign: Reading a query parameter: Used to pass data from one page to another Insecure, because malicious user can copy or change the address string selectedTabID = Request.QueryString["tabid"]; 1) A query string is information that is appended to the end of a page URL. Query strings provide a simple but limited way to maintain state information. For example, they are an easy way to pass information from one page to another, such as passing a product number from one page to another page where it will be processed. However, some browsers and client devices impose a 2083-character limit on the length of the URL. Security Note Information that is passed in a query string can be tampered with by a malicious user. Do not rely on query strings to convey important or sensitive data. Additionally, a user can bookmark the URL or send the URL to other users, thereby passing that information along with it. For more information, see ASP.NET State Management Recommendations and How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings. (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
21
Page Execution Lifecycle
* Page Execution Lifecycle (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
22
Page Execution Lifecycle
* Page Execution Lifecycle On the server side, ASP.NET web form goes through several stages: Page framework initialization User code initialization Validation Event handling Automatic data binding Cleanup 1) When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering. It is important for you to understand the page life cycle so that you can write code at the appropriate life-cycle stage for the effect you intend. (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
23
Page Execution Lifecycle (2)
* Page Execution Lifecycle (2) (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
24
Page Execution Lifecycle (3)
* Page Execution Lifecycle (3) Page Framework Initialization: Generates all the controls you have defined If page is postback, ASP.NET deserializes the view state information and applies it to the controls Page.Init Event fires User Code Initialization: Here you can perform any required initialization (e.g. filling in dynamic text or configuring controls) Always fires Page.Load event Page.IsPostBack – commonly used in it 1) The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page. 2) During page initialization, controls on the page are available and each control's UniqueID property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state. (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
25
Page Execution Lifecycle (4)
* Page Execution Lifecycle (4) Validation: All validation controls are checked and Page.IsValid property is set Event Handling: All Control Events such TextBox.TextChanged, Button.Click, Page.PreRender are triggered 1) If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page. 2) Before rendering, view state is saved for the page and all controls. During the rendering stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page's Response property. (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
26
Page Execution Lifecycle (5)
* Page Execution Lifecycle (5) Automatic Data Binding: After the Page.PreRender event fired Data source controls executes theirs queries and insert the data into controls Data source Selecting and Selected are fired Cleanup: At the end page is rendered as HTML and Page.Disposed event is fired 1) The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and cleanup is performed. (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
27
Page Execution Lifecycle
* Page Execution Lifecycle Live Demo (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
28
ASP.NET State Management
* ASP.NET State Management (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
29
State Management HTTP is a stateless protocol
* State Management HTTP is a stateless protocol In order to tell whether a request comes from a previous client we need a mechanism over the HTTP protocol A number of standard ways to identify clients ASP.NET offers both standard and upper level mechanisms to manage state 1) HTTP is a text based protocol. You can transfer data and other info in such a way across the internet, that's how internet pages are transmitted. - if connections were always kept alive, servers will be permanently burning out - In addition if the server hosts other sites, the problem is multiplied - the solution is: connect get what you need, and then disconnect - How information is tracked then? – passed over and over again (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
30
ASP.NET Based State Management
* ASP.NET Based State Management Client side View state Server side Application state Session state (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
31
ASP.NET Client Side State Management
ViewState
32
* ViewState ViewState keeps the state of the controls over several consecutive requests to the same page (postbacks) Every change in the visualization of a control is saved in the ViewState E.g. adding an element to a list control Can save custom data defined by developers 1) View state is the method that the ASP.NET page framework uses to preserve page and control values between round trips. When the HTML markup for the page is rendered, the current state of the page and values that must be retained during postback are serialized into base64-encoded strings. This information is then put into the view state hidden field or fields. - Keep values between postbacks without storing them in session state or in a user profile. - Store the values of page or control properties that you define. ViewState["Username"] = txtUsername.Text.Trim(); lblUsername.Text = ViewState["Username"]; (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
33
ViewState – Behind the Scene
* ViewState – Behind the Scene Data saved in the ViewState is serialized and is sent to the client in a hidden field: At postback the ViewState is deserialized and the state of the controls is restored To accomplish serialization the ObjectStateFormatter class is used <input type="hidden" name="__VIEWSTATE“ id="__VIEWSTATE" value="/wEPDwUJODExMDE5NzY5D2QWAgIDD2QWAgIBDw8WA h4EVGV4dAUFS296bW9kZGR67yT0OasTSUMlwIXGj65FNx7ggA==" /> 1) View state information is serialized into XML and then encoded by using base-64 encoding, which can generate large amounts of data. 2) if the amount of data in a hidden field becomes large, some proxies and firewalls will prevent access to the page that contains them 3) Create a custom view state provider that lets you store view state information in a SQL Server database or in another data store. 4) ObjectStateFormatter Class Serializes and deserializes object graphs that represent the state of an object. This class cannot be inherited. The ObjectStateFormatter class is optimized to serialize and format many common .NET Framework reference types, as well as constants (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
34
ViewState Configuration
* ViewState Configuration To disable ViewState At page level At control level ViewState support encryption: Page EnableViewState="false" %> <asp:Label ID="lblName" Runat="server" Text="ligAZ" EnableViewState="False" /> 1) You can disable a control's view state if the control does not contain any dynamic data, its value is hard-coded, or its value is assigned on every page request and you're not handling its events. A good example of a big consumer of view state is .NET’s DataGrid control. It is desirable to disable view state for a page if the page does not post back. However, if the DataGrid has sorting or paging enabled, then enabling view state is desirable. 2) In ASP.NET 2.0 the support for controlling and utilizing encryption has been expanded. Encryption settings can now be controlled separately for each page. In addition, the controls on the page can request that encryption be used for the ViewState, but even this request can be overridden by the page setting. The ViewStateEncryptionMode enumeration has three values: Auto, Always, and Never. The default value is Auto. ViewStateEncryptionMode.Auto In this mode, ASP.NET will encrypt the ViewState for a page if any control on the page requests it. Note that this means all of the ViewState is encrypted, not just the ViewState for the control that requests it. A large part of the performance cost associated with encryption is in the overhead. So encrypting the whole ViewState is faster than doing separate encryption operations if more than one control makes the request. ViewStateEncryptionMode.Never As you would expect, in this mode ASP.NET will not encrypt the ViewState, even if the application is set for encryption and controls on the page have requested it. If you know that no data involved in the page needs to be encrypted, then it may be safe to set the mode to Never. However, at this point it is rare for the documentation about a control to disclose what is being saved in ViewState, so you will want to be careful if there is a chance that sensitive data could be exposed. ViewStateEncryptionMode.Always In this mode, ASP.NET does not wait for a control in the page to request encryption. ViewState is always encrypted. When working with sensitive data, it is a good practice to utilize encryption. Page ViewStateEncryptionMode="Always" %> (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
35
ASP.NET Server Side State Management
Application State and Session State
36
* Application State The Application State is shared storage of information at application level Store information in the memory of the server Single object for all clients HttpApplicationState A dictionary collection accessed through HttpContext or Page Available through all phases of the application lifecycle 1) Application state is stored in memory on the server and is faster than storing and retrieving information in a database. Unlike session state, which is specific to a single user session, application state applies to all users and sessions. Therefore, application state is a useful place to store small amounts of often-used data that does not change from one user to another 2) The HttpApplicationState instance is created the first time a user accesses any URL resource in an application. The HttpApplicationState class is most often accessed through the Application property of the HttpContext class 3) Because application state is stored in server memory, it is lost whenever the application is stopped or restarted. 4) Application state is not shared among multiple servers serving the same application (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
37
* Application State (2) In order to have synchronized access we use the Lock() and Unlock()methods Application State is rarely used in reality (unlike the cache) Supported only for the sake of the pure ASP Useful place to store small amounts of often- used data that is the shared for all users Application.Lock(); Application["Users"] = (int) Application["Users"] + 1; Application.UnLock(); 1) Application state is free-threaded, which means that application state data can be accessed simultaneously by many threads. Therefore, it is important to ensure that when you update application state data, you do so in a thread-safe manner by including built-in synchronization support. You can use the Lock and UnLock methods to ensure data integrity by locking the data for writing by only one source at a time. You can also reduce the likelihood of concurrency problems by initializing application state values in the Application_Start method in the Global.asax file. (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
38
ASP.NET Application State
* ASP.NET Application State Live Demo (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
39
Session State What is a Session State? The Session is active:
* Session State What is a Session State? Storage of information at user level (different one for each user) The Session is active: Till the user closes the browser or A certain period expires (20 minutes for example) Every session is identified by a unique SessionID Created at first entry in the site Transmitted in a cookie by default A session is defined as the period of time that a unique user interacts with a Web application. 1) Programmatically, session state is nothing more than memory in the shape of a dictionary or hash table, e.g. key-value pairs, which can be set and read for the duration of a user's session. For example, a user selects stocks to track and the Web application can store these values in the user's ASP session instance 2) ASP maintains session state by providing the client with a unique key assigned to the user when the session begins. This key is stored in an HTTP cookie that the client sends to the server on each request. The server can then read the key from the cookie and re-inflate the server session state 3) Cookieless Session (the ID is stored in the URL) (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
40
* Session State (2) The HttpSessionState dictionary collection is used through HttpContext or Page To handle events fired when a session is started or ended we use Session_OnStart and Session_OnEnd in the Global.asax file To deny/restrict access to the session Session["username"] = "pesho"; string = (string) Session["username"]; HttpSessionState Class Provides access to session-state values as well as session-level settings and lifetime management methods. Page EnableSessionState="False" %> Page EnableSessionState="ReadOnly" %> (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
41
Session Configuration
* Session Configuration We can configure various aspects of the session mechanism Use the sessionState section in Web.config Example: <system.web> <sessionState cookieless="true" mode="InProc" timeout="60" cookieName="MySite" /> </system.web> Session state settings in ASP.NET are configured through the ASP.NET XML configuration file config.web. (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
42
Session Configuration (2)
* Session Configuration (2) Important attributes Timeout A period for which the session is active Mode Where the session is saved – in the current process, SQL Server, State Server (separate process) Cookieless A Session that doesn’t use cookies – SessionID is a parameter in the URL Mode. The mode setting supports three options: inproc, sqlserver, and stateserver. As stated earlier, ASP.NET supports two modes: in process and out of process. There are also two options for out-of-process state management: memory based (stateserver), and SQL Server based (sqlserver). We'll discuss implementing these options shortly. Cookieless. The cookieless option for ASP.NET is configured with this simple Boolean setting. Timeout. This option controls the length of time a session is considered valid. The session timeout is a sliding value; on each request the timeout period is set to the current time plus the timeout value Sqlconnectionstring. The sqlconnectionstring identifies the database connection string that names the database used for mode sqlserver. Server. In the out-of-process mode stateserver, it names the server that is running the required Windows NT service: ASPState. Port. The port setting, which accompanies the server setting, identifies the port number that corresponds to the server setting for mode stateserver. (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
43
ASP.NET Session State Live Demo *
(c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
44
Session – Recommendations
* Session – Recommendations Use a wrapper class over the session Don’t save too much information in the session Don’t save lots of information in the ViewState (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
45
Manipulating the HTTP Response Headers
* Manipulating the HTTP Response Headers (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
46
Manipulating the HTTP Response Headers
* Manipulating the HTTP Response Headers Part of the server response Allow the server to pass additional information about the response Page content, caching, cookies, http codes etc. Give information about the server and about further access to the resource identified by the Request-URI Accessible from code behind through Response.Headers collection The Headers property is only supported with the IIS 7.0 integrated pipeline mode and at least the .NET Framework 3.0. Response headers can be used to specify cookies, to supply the modification date (for caching), to instruct the browser to reload the page after a designated interval, to say how long the file is so that persistent HTTP connections can be used, and many other tasks. Allow What request methods (GET, POST, etc.) does the server support? Content-Encoding What method was used to encode the document? You need to decode it to get the type specified by the Content-Type header Content-Length How many bytes are being sent? This information is only needed if the browser is using a persistent (keep-alive) HTTP connection. Refresh How soon should browser ask for an updated page (in seconds)? (<META HTTP-EQUIV="Refresh" CONTENT="5; URL= ) (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
47
Manipulating the HTTP Response Headers (2)
* Manipulating the HTTP Response Headers (2) Some response header members: HeaderEncoding – sets header encoding Headers – read only collection of headers ContentType – HTTP MIME type of the output Expires – numbers of minutes before page cached in browser expires StatusCode – Http Status code of the output AppendHeader() - Adds an HTTP header to the output stream Content-Type What is the MIME type of the following document? Default for servlets is text/plain, but they usually explicitly specify text/html. StatusCode importance: (bookmarks, search engines,…) (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
48
Manipulating the HTTP Response Headers – Example
* Manipulating the HTTP Response Headers – Example Downloading image file generated from an ASP.NET page: Response.Clear(); Bitmap generatedImage = new Bitmap(200, 200); Graphics gr = Graphics.FromImage(generatedImage); gr.FillRectangle(Brushes.MediumSeaGreen, 0, 0, 200, 200); gr.FillPie(Brushes.Yellow, 25, 25,150, 150, 0, 45); gr.FillPie(Brushes.Green, 25, 25, 150, 150, 45, 315); Response.ContentType = "image/gif"; generatedImage.Save( Response.OutputStream,ImageFormat.Gif); (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
49
Manipulating the HTTP Response Headers
* Manipulating the HTTP Response Headers Live Demo (c) 2008 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
50
ASP.NET State Management
? ? ? ? ? ? ? ? ? ?
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.