SlideShare una empresa de Scribd logo
1 de 33
Developing Web Applications Using ASP.NET
Objectives


                In this session, you will learn to:
                   Describe the ViewState and ControlState data models for Web
                   pages
                   Describe the Application and Session objects and explain how
                   state data is stored and retrieved in these objects
                   Describe various session-state data-storage strategies
                   Describe the Cache object and explain how you can use it to
                   store and manage state data




     Ver. 1.0                                                          Slide 1 of 33
Developing Web Applications Using ASP.NET
ASP.NET State Management Overview


               A new instance of the Web page class is created each time
               the page is posted to the server.
               In traditional Web programming, all information that is
               associated with the page, along with the controls on the
               page, would be lost with each roundtrip.
               Microsoft ASP.NET framework includes several options to
               help you preserve data on both a per-page basis and an
               application-wide basis. These options can be broadly
               divided into two categories:
                  Client-Based State Management Options
                  Server-Based State Management Options




    Ver. 1.0                                                      Slide 2 of 33
Developing Web Applications Using ASP.NET
Client-Based State Management Options


                Client-based options involve storing information either in the
                page or on the client computer.
                Some client-based state management options are:
                   View state
                   Control state
                   Hidden form fields
                   Cookies
                   Query strings




     Ver. 1.0                                                         Slide 3 of 33
Developing Web Applications Using ASP.NET
Client-Based State Management Options (Contd.)


                View State:
                   The ViewState property provides a dictionary object for
                   retaining values between multiple requests for the same page.
                   When the page is processed, the current state of the page and
                   controls is hashed into a string and saved in the page as a
                   hidden field.
                   When the page is posted back to the server, the page parses
                   the view-state string at page initialization and restores property
                   information in the page.
                   To specify the maximum size allowed in a single view-state
                   field, you can use the property,
                   System.Web.UI.Page.MaxPageStateFieldLength.
                   In addition to the contents of controls, the ViewState property
                   can also contain some additional information:
                   ViewState[“color”] = “Yellow” ;


     Ver. 1.0                                                               Slide 4 of 33
Developing Web Applications Using ASP.NET
Client-Based State Management Options (Contd.)


                Control State:
                 • The ControlState property allows you to persist property
                   information that is specific to a control.
                 • This property cannot be turned off at a page level as can the
                   ViewState property.
                Hidden Form Fields:
                 • ASP.NET provides the HtmlInputHidden control, which
                   offers hidden-field functionality.
                 • A hidden field does not render visibly in the browser.
                 • The content of a hidden field is sent in the HTTP form
                   collection along with the values of other controls.




     Ver. 1.0                                                             Slide 5 of 33
Developing Web Applications Using ASP.NET
Client-Based State Management Options (Contd.)


                Cookies:
                   Cookies are stored either in a text file on the client file system
                   or in memory in the client browser session.
                   They contain site-specific information that a server sends to
                   the client along with the page output.
                   When the browser requests a page, the client sends the
                   information in the cookie along with the request information.
                   The server can read the cookie and extract its value.
                Query Strings:
                   Query string is a piece of information that is appended to the
                   end of a page URL.
                   You must submit the page by using an HTTP GET command
                   to ensure availability of these values.



     Ver. 1.0                                                                 Slide 6 of 33
Developing Web Applications Using ASP.NET
Server-Based State Management Options


                Server-based options maintain state information on the
                server.
                Some server-based state management options are:
                   Application state
                   Session state




     Ver. 1.0                                                       Slide 7 of 33
Developing Web Applications Using ASP.NET
Server-Based State Management Options (Contd.)


                Application State:
                 • Application state is an instance of the
                   System.Web.HttpApplicationState class.
                 • It allows you to save values for each active Web application.
                 • Application state is stored in a key/value dictionary that is
                   created during each request to a specific URL.
                 • It is a global storage mechanism that is accessible from all
                   pages in the Web application.
                 • It supports the following events:
                     • Application.Start
                     • Application.End
                     • Application.Error
                 • The handlers for the preceding events can be defined in the
                   Global.asax file.


     Ver. 1.0                                                              Slide 8 of 33
Developing Web Applications Using ASP.NET
Server-Based State Management Options (Contd.)


                  Values can be saved in the Application state as:
                    Application[“Message”]=“Hello,world.”;
                • Values can be retrieved from the Application state as:
                    if (Application[“AppStartTime”] != null)
                    {
                          DateTime myAppStartTime = (DateTime)
                                  Application[“AppStartTime”];
                    }




     Ver. 1.0                                                              Slide 9 of 33
Developing Web Applications Using ASP.NET
Server-Based State Management Options (Contd.)


                Session State:
                • Session state is an instance of the
                  System.Web.SessionState.HttpSessionState class.
                • It allows you to save values for each active Web application
                  session.
                • It is similar to application state, except that it is scoped to the
                  current browser session.
                • It supports the following events:
                    • Session.Start
                    • Session.End
                • The handlers for the preceding events can be defined in the
                  Global.asax file.




     Ver. 1.0                                                                 Slide 10 of 33
Developing Web Applications Using ASP.NET
Server-Based State Management Options (Contd.)


                • Values can be saved in the Session state as:
                              string name = “Jeff”;
                      Session[“Name”] = name;
                • Values can be retrieved from the Session state as:
                      if(Session[“Name”]!=null)
                      {
                          string name=(string)Session[“Name”];
                      }




     Ver. 1.0                                                    Slide 11 of 33
Developing Web Applications Using ASP.NET
Strategies for Managing Session State Data


                •   Session state information can be stored in several locations.
                •   Location can be configured by setting the mode attribute of
                    the SessionState element in Web.config file.
                •   Three possible storage modes can be used:
                       InProc Mode
                       State Server Mode
                       SQL Server Mode




     Ver. 1.0                                                            Slide 12 of 33
Developing Web Applications Using ASP.NET
Strategies for Managing Session State Data


                InProc Mode:
                • This is the default mode.
                • Session state data is stored in memory on the Web server
                  within the process that is running the Web application.
                • This is the only mode that supports the Session.End event.
                • Session state information will be lost if application is restarted.
                • Session state cannot be shared between multiple servers in a
                  Web farm.
                • To enable InProc mode, the following markup can be added
                  within the <system.web> tags in the Web.config file:
                   <sessionState mode=“InProc”></sessionState>




     Ver. 1.0                                                                Slide 13 of 33
Developing Web Applications Using ASP.NET
Strategies for Managing Session State Data (Contd.)


                        Following Diagram shows how Session state information is
                        managed in InProc mode, when Cookies are enabled.

                          Client                                                Server
                                           Request first page
                                                                        Request received

                Receives first page      Store cookie on client,
                                         send along with first page     Create session object and
                 Session ID Cookies                                     store data in it

                                         Second request (with cookie)
                                                                        Fetch session object identified
                                                                        by cookie
                                         Send second page based
                                         on data in Session object
                 Receives second page
                                                                        Fetch data from session object




     Ver. 1.0                                                                                             Slide 14 of 33
Developing Web Applications Using ASP.NET
Strategies for Managing Session State Data
(Contd.)

                State Server Mode:
                   Session state data is managed by a separate process called
                   the ASP.NET State Service.
                   Session state information will not be lost if application is
                   restarted.
                   A single session state can be shared between multiple servers
                   in a Web farm.
                   ASP.NET State Service does not start automatically.
                   To use ASP.NET State Service, make sure it is running on the
                   desired server.




     Ver. 1.0                                                           Slide 15 of 33
Developing Web Applications Using ASP.NET
Strategies for Managing Session State Data
(Contd.)

                You need to configure each Web server in the Web farm to
                connect to the ASP.NET state service by modifying the
                Web.config file as:
                 <configuration>
                   <system.web>
                      <sessionState mode="StateServer“
                       stateConnectionString=
                       "tcpip=MyStateServer:42424"
                       cookieless="AutoDetect"
                       timeout="20"/>
                   </system.web>
                 </configuration>




     Ver. 1.0                                                       Slide 16 of 33
Developing Web Applications Using ASP.NET
Strategies for Managing Session State Data (Contd.)


                Status of ASP.NET State Service can be checked from the
                Services window on the server on which the service is
                running.




     Ver. 1.0                                                    Slide 17 of 33
Developing Web Applications Using ASP.NET
Strategies for Managing Session State Data
(Contd.)

                SQL Server Mode:
                   Session state data is stored in Microsoft SQL Server database.
                   Session state information will not be lost, in case application is
                   restarted.
                   Session state can be shared between multiple servers in a
                   Web farm.
                   To use SQLServer mode, session state database must be
                   installed on an existing SQL Server.




     Ver. 1.0                                                               Slide 18 of 33
Developing Web Applications Using ASP.NET
Strategies for Managing Session State Data
(Contd.)

                • After database has been installed, you need to specify
                  SQLServer mode in Web.config file as:
                   <configuration>
                       <system.web>
                           <sessionState mode="SQLServer"
                               sqlConnectionString="
                               Integrated Security=SSPI;data
                               source=MySqlServer;" />
                       </system.web>
                   </configuration>




     Ver. 1.0                                                              Slide 19 of 33
Developing Web Applications Using ASP.NET
The Cache Object


                An object can be stored in cache if it consumes a lot of
                server resources during creation and is being used
                frequently.
                This caching system can be used to improve the response
                time of an application.
                This caching system automatically removes items when
                system memory becomes scarce, in a process called
                scavenging.




     Ver. 1.0                                                     Slide 20 of 33
Developing Web Applications Using ASP.NET
How to: Store and Retrieve State Data in the Cache Object


                To cache an item, you can use any of the following
                methods:
                   Key name/Value pair method:
                    • Add a value to the cache object by using the key name as indexer.
                    • The following code caches the value in the Text property of a
                      TextBox control called txtExample:
                       Cache[“key"] = value;
                   Insert method:
                    • Specify the key name as the first argument and the value being
                      cached as the second argument.
                    • The following code performs the same task as the previous
                      example by using the Insert method of the Cache object:
                       Cache.Insert(“key", value);




     Ver. 1.0                                                                 Slide 21 of 33
Developing Web Applications Using ASP.NET
How to: Store and Retrieve State Data in the Cache Object (Contd.)


                •   To retrieve values from the cache, Cache object can be
                    referenced using the key name as the indexer:
                     if (Cache[“key"] != null)
                     {
                       txtExample.Text = (string)Cache[“key"];
                     }
                •   If you try to access an object from the cache that has been
                    removed because of scarcity of memory, the cache will
                    return a Null reference.




     Ver. 1.0                                                            Slide 22 of 33
Developing Web Applications Using ASP.NET
Controlling Expiration


                Expiration time of a cached object can be specified during
                the object addition into the cache.
                Expiration time can be:
                   Absolute
                   Sliding
                Absolute Expiration:
                   This method specifies a date and time when the object will be
                   removed.
                   To add an item to the cache with an absolute expiration of two
                   minutes, the following code snippet can be used:
                       Cache.Insert("CacheItem", "Cached Item Value",
                       null, DateTime.Now.AddMinutes(2),
                       System.Web.Caching.Cache.NoSlidingExpiration);




     Ver. 1.0                                                            Slide 23 of 33
Developing Web Applications Using ASP.NET
Controlling Expiration


                Sliding Expiration:
                   This method specifies a duration for which an item can lie
                   unused in the cache.
                   The caching system can scavenge the item if it has not been
                   used for a duration that exceeds this value.
                   To add an item to the cache with a sliding expiration of 10
                   minutes, the following code snippet can be used:
                   Cache.Insert("CacheItem", "Cached Item Value", null,
                   System.Web.Caching.Cache.NoAbsoluteExpiration,
                   new TimeSpan(0, 10, 0));




     Ver. 1.0                                                           Slide 24 of 33
Developing Web Applications Using ASP.NET
Cache Item Priority


                •   Policy for removing objects from the cache can be
                    influenced by specifying CacheItemPriority value.
                •   The caching system will scavenge low-priority items before
                    high-priority items when system memory becomes scarce.
                •   To set the priority of ac cached object to high at the time of
                    creation, the following code snippet can be used:
                    Cache.Insert("CacheItem", "Cached Item Value",
                    null,
                    System.Web.Caching.Cache.NoAbsoluteExpiration,
                    System.Web.Caching.Cache.NoSlidingExpiration,
                    System.Web.Caching.CacheItemPriority.High, null);




     Ver. 1.0                                                              Slide 25 of 33
Developing Web Applications Using ASP.NET
Cache Dependencies


               Cached items can become invalid because the source of
               the data has changed.
               Cached items may be dependent on files, directories, and
               other cached items.
               At the time of adding an item to the cache, you can specify
               the object on which the cached item depends.
               If any object (on which a cached item depends) changes,
               the cached item is automatically removed from the cache.




    Ver. 1.0                                                        Slide 26 of 33
Developing Web Applications Using ASP.NET
How to: Define Dependencies Between Cached Items


                •   You can add an item with a dependency to the cache by
                    using the dependencies parameter in the Cache.Insert
                    method, as:
                    Cache.Insert(“Key", value, new CacheDependency
                    Server.MapPath("~myConfig.xml")));
                    You can also add an item that depends on another cached
                    item to the cache, as:
                    string[] sDependencies = new string[1];
                    sDependencies[0] = “key_original";
                    CacheDependency dependency = new
                    CacheDependency(null, sDependencies);
                    Cache.Insert(“key_dependent", "This item depends
                    on OriginalItem", dependency);



     Ver. 1.0                                                        Slide 27 of 33
Developing Web Applications Using ASP.NET
How to: Delete Cached Data


                Cached data can be deleted by:
                • Setting expiration policies that determine the total amount of
                  time the item remains in the cache.
                • Setting expiration policies that are based on the amount of time
                  that must pass following the previous time the item was
                  accessed.
                • Specifying files, directories, or keys that the item is dependent
                  on. The item is removed from the cache when those
                  dependencies change.
                • Removing items from the cache by using the Cache.Remove
                  method as:
                  Cache.Remove("MyData1");




     Ver. 1.0                                                             Slide 28 of 33
Developing Web Applications Using ASP.NET
How to: Implement Deletion Notifications in Cached Data


                • CacheItemRemovedCallback delegate defines the
                  signature to use while writing the event handlers to respond
                  when an item is deleted from the cache.
                • CacheItemRemovedReason enumeration can be used to
                  make event handlers dependent upon the reason the item is
                  deleted.




     Ver. 1.0                                                         Slide 29 of 33
Developing Web Applications Using ASP.NET
How to: Implement Deletion Notifications in Cached Data (Contd.)


                To notify an application when an item is deleted from the
                cache:
                 • Create a local variable that raises the event for the
                   CacheItemRemovedCallback delegate as:
                     private static CacheItemRemovedCallback               onRemove
                       = null;
                   Create an event handler to respond when the item is removed
                   from the cache as:
                     static bool itemRemoved = false;
                     static CacheItemRemovedReason reason;
                     public void RemovedCallback(string key, object
                       value, CacheItemRemovedReason
                     callbackreason)
                     { itemRemoved = true;
                       reason = callbackreason;
                     }

     Ver. 1.0                                                              Slide 30 of 33
Developing Web Applications Using ASP.NET
How to: Implement Deletion Notifications in Cached Data (Contd.)


                • Create an instance of the CacheItemRemovedCallback
                  delegate that calls the event handler as:
                    onRemove = new
                      CacheItemRemovedCallback(this.RemovedCallback);

                • Add the item to the cache by using the Cache.Insert
                  method as:
                    Cache.Insert("MyData1", Source, null,
                    DateTime.Now.AddMinutes(2),
                    NoSlidingExpiration,
                    CacheItemPriority.High, onRemove);




     Ver. 1.0                                                       Slide 31 of 33
Developing Web Applications Using ASP.NET
Summary


               In this session, you learned that:
                  ViewState is the mechanism for preserving the contents and
                  state of the controls on a Web page during a round trip.
                  ASP.NET enables controls to preserve their ControlState even
                  when ViewState is disabled.
                  The Application and Session objects enable you to cache
                  information for use by any page in your ASP.NET application.
                  ASP.NET maintains a single Application object for each
                  application on your Web server.
                  An ASP.NET Session object is an object that represents a
                  user’s visit to your application.




    Ver. 1.0                                                          Slide 32 of 33
Developing Web Applications Using ASP.NET
Summary (Contd.)


                 The possible storage modes for storing session state
                 information are:
                  • InProc
                  • StateServer
                  • SQLServer
               • ASP.NET has a powerful caching system that you can use to
                 improve the response time of your application.
               • The ASP.NET caching system automatically removes items
                 from the cache when system memory becomes scarce.




    Ver. 1.0                                                            Slide 33 of 33

Más contenido relacionado

La actualidad más candente

Chapter6 web apps-tomcat
Chapter6 web apps-tomcatChapter6 web apps-tomcat
Chapter6 web apps-tomcatVenkat Gowda
 
Asp Net Advance Topics
Asp Net Advance TopicsAsp Net Advance Topics
Asp Net Advance TopicsAli Taki
 
11 asp.net session16
11 asp.net session1611 asp.net session16
11 asp.net session16Vivek chan
 
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl....net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...Nancy Thomas
 
Installing web sphere application server v7 on red hat enterprise linux v6.3
Installing web sphere application server v7 on red hat enterprise linux v6.3Installing web sphere application server v7 on red hat enterprise linux v6.3
Installing web sphere application server v7 on red hat enterprise linux v6.3Dave Hay
 
Wordcamp Thessaloniki 2011 The Nextweb
Wordcamp Thessaloniki 2011 The NextwebWordcamp Thessaloniki 2011 The Nextweb
Wordcamp Thessaloniki 2011 The NextwebGeorge Kanellopoulos
 
Wordcamp Thessaloniki 2011 Wordpress and Microsoft Web Platform
Wordcamp Thessaloniki 2011 Wordpress and Microsoft Web PlatformWordcamp Thessaloniki 2011 Wordpress and Microsoft Web Platform
Wordcamp Thessaloniki 2011 Wordpress and Microsoft Web PlatformGeorge Kanellopoulos
 
Phil_Pearl_Resume
Phil_Pearl_ResumePhil_Pearl_Resume
Phil_Pearl_ResumePhil Pearl
 
Asp interview Question and Answer
Asp interview Question and Answer Asp interview Question and Answer
Asp interview Question and Answer home
 
Java server faces
Java server facesJava server faces
Java server facesowli93
 
1 app 2 developers 3 servers
1 app 2 developers 3 servers1 app 2 developers 3 servers
1 app 2 developers 3 serversMark Myers
 
Php apache vs iis By Hafedh Yahmadi
Php apache vs iis  By Hafedh YahmadiPhp apache vs iis  By Hafedh Yahmadi
Php apache vs iis By Hafedh YahmadiTechdaysTunisia
 
Ruby on Rails: Building Web Applications Is Fun Again!
Ruby on Rails: Building Web Applications Is Fun Again!Ruby on Rails: Building Web Applications Is Fun Again!
Ruby on Rails: Building Web Applications Is Fun Again!judofyr
 
API & Custom Widgets coming in XCC next - Web Content and Custom App Extensio...
API & Custom Widgets coming in XCC next - Web Content and Custom App Extensio...API & Custom Widgets coming in XCC next - Web Content and Custom App Extensio...
API & Custom Widgets coming in XCC next - Web Content and Custom App Extensio...TIMETOACT GROUP
 
Integrating ASP.NET AJAX with SharePoint
Integrating ASP.NET AJAX with SharePointIntegrating ASP.NET AJAX with SharePoint
Integrating ASP.NET AJAX with SharePointRob Windsor
 
Know, Share, Do - Custom Apps
Know, Share, Do - Custom AppsKnow, Share, Do - Custom Apps
Know, Share, Do - Custom AppsTIMETOACT GROUP
 

La actualidad más candente (20)

Chapter6 web apps-tomcat
Chapter6 web apps-tomcatChapter6 web apps-tomcat
Chapter6 web apps-tomcat
 
ASP.NET Lecture 1
ASP.NET Lecture 1ASP.NET Lecture 1
ASP.NET Lecture 1
 
Asp Net Advance Topics
Asp Net Advance TopicsAsp Net Advance Topics
Asp Net Advance Topics
 
11 asp.net session16
11 asp.net session1611 asp.net session16
11 asp.net session16
 
Advanced Asp.Net Concepts And Constructs
Advanced Asp.Net Concepts And ConstructsAdvanced Asp.Net Concepts And Constructs
Advanced Asp.Net Concepts And Constructs
 
WSS And Share Point For Developers
WSS And Share Point For DevelopersWSS And Share Point For Developers
WSS And Share Point For Developers
 
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl....net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
 
Installing web sphere application server v7 on red hat enterprise linux v6.3
Installing web sphere application server v7 on red hat enterprise linux v6.3Installing web sphere application server v7 on red hat enterprise linux v6.3
Installing web sphere application server v7 on red hat enterprise linux v6.3
 
Wordcamp Thessaloniki 2011 The Nextweb
Wordcamp Thessaloniki 2011 The NextwebWordcamp Thessaloniki 2011 The Nextweb
Wordcamp Thessaloniki 2011 The Nextweb
 
Asp.net
Asp.netAsp.net
Asp.net
 
Wordcamp Thessaloniki 2011 Wordpress and Microsoft Web Platform
Wordcamp Thessaloniki 2011 Wordpress and Microsoft Web PlatformWordcamp Thessaloniki 2011 Wordpress and Microsoft Web Platform
Wordcamp Thessaloniki 2011 Wordpress and Microsoft Web Platform
 
Phil_Pearl_Resume
Phil_Pearl_ResumePhil_Pearl_Resume
Phil_Pearl_Resume
 
Asp interview Question and Answer
Asp interview Question and Answer Asp interview Question and Answer
Asp interview Question and Answer
 
Java server faces
Java server facesJava server faces
Java server faces
 
1 app 2 developers 3 servers
1 app 2 developers 3 servers1 app 2 developers 3 servers
1 app 2 developers 3 servers
 
Php apache vs iis By Hafedh Yahmadi
Php apache vs iis  By Hafedh YahmadiPhp apache vs iis  By Hafedh Yahmadi
Php apache vs iis By Hafedh Yahmadi
 
Ruby on Rails: Building Web Applications Is Fun Again!
Ruby on Rails: Building Web Applications Is Fun Again!Ruby on Rails: Building Web Applications Is Fun Again!
Ruby on Rails: Building Web Applications Is Fun Again!
 
API & Custom Widgets coming in XCC next - Web Content and Custom App Extensio...
API & Custom Widgets coming in XCC next - Web Content and Custom App Extensio...API & Custom Widgets coming in XCC next - Web Content and Custom App Extensio...
API & Custom Widgets coming in XCC next - Web Content and Custom App Extensio...
 
Integrating ASP.NET AJAX with SharePoint
Integrating ASP.NET AJAX with SharePointIntegrating ASP.NET AJAX with SharePoint
Integrating ASP.NET AJAX with SharePoint
 
Know, Share, Do - Custom Apps
Know, Share, Do - Custom AppsKnow, Share, Do - Custom Apps
Know, Share, Do - Custom Apps
 

Destacado

Capital Budgeting Decision
Capital Budgeting DecisionCapital Budgeting Decision
Capital Budgeting DecisionAshish Khera
 
ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1Kumar S
 

Destacado (8)

Ajs 3 a
Ajs 3 aAjs 3 a
Ajs 3 a
 
Ajs 3 b
Ajs 3 bAjs 3 b
Ajs 3 b
 
Ajs 4 c
Ajs 4 cAjs 4 c
Ajs 4 c
 
Ajs 4 a
Ajs 4 aAjs 4 a
Ajs 4 a
 
Ajs 4 b
Ajs 4 bAjs 4 b
Ajs 4 b
 
Ajs 1 b
Ajs 1 bAjs 1 b
Ajs 1 b
 
Capital Budgeting Decision
Capital Budgeting DecisionCapital Budgeting Decision
Capital Budgeting Decision
 
ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1
 

Similar a 05 asp.net session07

05 asp.net session07
05 asp.net session0705 asp.net session07
05 asp.net session07Mani Chaubey
 
05 asp.net session07
05 asp.net session0705 asp.net session07
05 asp.net session07Vivek chan
 
06 asp.net session08
06 asp.net session0806 asp.net session08
06 asp.net session08Niit Care
 
06 asp.net session08
06 asp.net session0806 asp.net session08
06 asp.net session08Mani Chaubey
 
06 asp.net session08
06 asp.net session0806 asp.net session08
06 asp.net session08Vivek chan
 
Session and state management
Session and state managementSession and state management
Session and state managementPaneliya Prince
 
Session viii(state mngtserver)
Session viii(state mngtserver)Session viii(state mngtserver)
Session viii(state mngtserver)Shrijan Tiwari
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questionsAkhil Mittal
 
Introduction to asp.net
Introduction to asp.netIntroduction to asp.net
Introduction to asp.netneeta1995
 
State management
State managementState management
State managementteach4uin
 
The complete ASP.NET (IIS) Tutorial with code example in power point slide show
The complete ASP.NET (IIS) Tutorial with code example in power point slide showThe complete ASP.NET (IIS) Tutorial with code example in power point slide show
The complete ASP.NET (IIS) Tutorial with code example in power point slide showSubhas Malik
 
Ch 04 asp.net application
Ch 04 asp.net application Ch 04 asp.net application
Ch 04 asp.net application Madhuri Kavade
 
State management
State managementState management
State managementIblesoft
 
Parallelminds.asp.net with sp
Parallelminds.asp.net with spParallelminds.asp.net with sp
Parallelminds.asp.net with spparallelminder
 

Similar a 05 asp.net session07 (20)

05 asp.net session07
05 asp.net session0705 asp.net session07
05 asp.net session07
 
05 asp.net session07
05 asp.net session0705 asp.net session07
05 asp.net session07
 
06 asp.net session08
06 asp.net session0806 asp.net session08
06 asp.net session08
 
ASP.NET Lecture 2
ASP.NET Lecture 2ASP.NET Lecture 2
ASP.NET Lecture 2
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
06 asp.net session08
06 asp.net session0806 asp.net session08
06 asp.net session08
 
06 asp.net session08
06 asp.net session0806 asp.net session08
06 asp.net session08
 
Session and state management
Session and state managementSession and state management
Session and state management
 
Session viii(state mngtserver)
Session viii(state mngtserver)Session viii(state mngtserver)
Session viii(state mngtserver)
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questions
 
Asp.net
Asp.netAsp.net
Asp.net
 
Introduction to asp.net
Introduction to asp.netIntroduction to asp.net
Introduction to asp.net
 
State management
State managementState management
State management
 
The complete ASP.NET (IIS) Tutorial with code example in power point slide show
The complete ASP.NET (IIS) Tutorial with code example in power point slide showThe complete ASP.NET (IIS) Tutorial with code example in power point slide show
The complete ASP.NET (IIS) Tutorial with code example in power point slide show
 
Ch 04 asp.net application
Ch 04 asp.net application Ch 04 asp.net application
Ch 04 asp.net application
 
State management
State managementState management
State management
 
Parallelminds.asp.net with sp
Parallelminds.asp.net with spParallelminds.asp.net with sp
Parallelminds.asp.net with sp
 
2310 b 15
2310 b 152310 b 15
2310 b 15
 
2310 b 15
2310 b 152310 b 15
2310 b 15
 
Ch05 state management
Ch05 state managementCh05 state management
Ch05 state management
 

Más de Niit Care (20)

Ajs 3 c
Ajs 3 cAjs 3 c
Ajs 3 c
 
Ajs 2 b
Ajs 2 bAjs 2 b
Ajs 2 b
 
Ajs 2 a
Ajs 2 aAjs 2 a
Ajs 2 a
 
Ajs 2 c
Ajs 2 cAjs 2 c
Ajs 2 c
 
Ajs 1 a
Ajs 1 aAjs 1 a
Ajs 1 a
 
Ajs 1 c
Ajs 1 cAjs 1 c
Ajs 1 c
 
Dacj 4 2-c
Dacj 4 2-cDacj 4 2-c
Dacj 4 2-c
 
Dacj 4 2-b
Dacj 4 2-bDacj 4 2-b
Dacj 4 2-b
 
Dacj 4 2-a
Dacj 4 2-aDacj 4 2-a
Dacj 4 2-a
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
 
Dacj 4 1-b
Dacj 4 1-bDacj 4 1-b
Dacj 4 1-b
 
Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-a
 
Dacj 1-2 b
Dacj 1-2 bDacj 1-2 b
Dacj 1-2 b
 
Dacj 1-3 c
Dacj 1-3 cDacj 1-3 c
Dacj 1-3 c
 
Dacj 1-3 b
Dacj 1-3 bDacj 1-3 b
Dacj 1-3 b
 
Dacj 1-3 a
Dacj 1-3 aDacj 1-3 a
Dacj 1-3 a
 
Dacj 1-2 c
Dacj 1-2 cDacj 1-2 c
Dacj 1-2 c
 
Dacj 1-2 a
Dacj 1-2 aDacj 1-2 a
Dacj 1-2 a
 
Dacj 1-1 c
Dacj 1-1 cDacj 1-1 c
Dacj 1-1 c
 
Dacj 1-1 b
Dacj 1-1 bDacj 1-1 b
Dacj 1-1 b
 

Último

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 

Último (20)

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 

05 asp.net session07

  • 1. Developing Web Applications Using ASP.NET Objectives In this session, you will learn to: Describe the ViewState and ControlState data models for Web pages Describe the Application and Session objects and explain how state data is stored and retrieved in these objects Describe various session-state data-storage strategies Describe the Cache object and explain how you can use it to store and manage state data Ver. 1.0 Slide 1 of 33
  • 2. Developing Web Applications Using ASP.NET ASP.NET State Management Overview A new instance of the Web page class is created each time the page is posted to the server. In traditional Web programming, all information that is associated with the page, along with the controls on the page, would be lost with each roundtrip. Microsoft ASP.NET framework includes several options to help you preserve data on both a per-page basis and an application-wide basis. These options can be broadly divided into two categories: Client-Based State Management Options Server-Based State Management Options Ver. 1.0 Slide 2 of 33
  • 3. Developing Web Applications Using ASP.NET Client-Based State Management Options Client-based options involve storing information either in the page or on the client computer. Some client-based state management options are: View state Control state Hidden form fields Cookies Query strings Ver. 1.0 Slide 3 of 33
  • 4. Developing Web Applications Using ASP.NET Client-Based State Management Options (Contd.) View State: The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field. When the page is posted back to the server, the page parses the view-state string at page initialization and restores property information in the page. To specify the maximum size allowed in a single view-state field, you can use the property, System.Web.UI.Page.MaxPageStateFieldLength. In addition to the contents of controls, the ViewState property can also contain some additional information: ViewState[“color”] = “Yellow” ; Ver. 1.0 Slide 4 of 33
  • 5. Developing Web Applications Using ASP.NET Client-Based State Management Options (Contd.) Control State: • The ControlState property allows you to persist property information that is specific to a control. • This property cannot be turned off at a page level as can the ViewState property. Hidden Form Fields: • ASP.NET provides the HtmlInputHidden control, which offers hidden-field functionality. • A hidden field does not render visibly in the browser. • The content of a hidden field is sent in the HTTP form collection along with the values of other controls. Ver. 1.0 Slide 5 of 33
  • 6. Developing Web Applications Using ASP.NET Client-Based State Management Options (Contd.) Cookies: Cookies are stored either in a text file on the client file system or in memory in the client browser session. They contain site-specific information that a server sends to the client along with the page output. When the browser requests a page, the client sends the information in the cookie along with the request information. The server can read the cookie and extract its value. Query Strings: Query string is a piece of information that is appended to the end of a page URL. You must submit the page by using an HTTP GET command to ensure availability of these values. Ver. 1.0 Slide 6 of 33
  • 7. Developing Web Applications Using ASP.NET Server-Based State Management Options Server-based options maintain state information on the server. Some server-based state management options are: Application state Session state Ver. 1.0 Slide 7 of 33
  • 8. Developing Web Applications Using ASP.NET Server-Based State Management Options (Contd.) Application State: • Application state is an instance of the System.Web.HttpApplicationState class. • It allows you to save values for each active Web application. • Application state is stored in a key/value dictionary that is created during each request to a specific URL. • It is a global storage mechanism that is accessible from all pages in the Web application. • It supports the following events: • Application.Start • Application.End • Application.Error • The handlers for the preceding events can be defined in the Global.asax file. Ver. 1.0 Slide 8 of 33
  • 9. Developing Web Applications Using ASP.NET Server-Based State Management Options (Contd.) Values can be saved in the Application state as: Application[“Message”]=“Hello,world.”; • Values can be retrieved from the Application state as: if (Application[“AppStartTime”] != null) { DateTime myAppStartTime = (DateTime) Application[“AppStartTime”]; } Ver. 1.0 Slide 9 of 33
  • 10. Developing Web Applications Using ASP.NET Server-Based State Management Options (Contd.) Session State: • Session state is an instance of the System.Web.SessionState.HttpSessionState class. • It allows you to save values for each active Web application session. • It is similar to application state, except that it is scoped to the current browser session. • It supports the following events: • Session.Start • Session.End • The handlers for the preceding events can be defined in the Global.asax file. Ver. 1.0 Slide 10 of 33
  • 11. Developing Web Applications Using ASP.NET Server-Based State Management Options (Contd.) • Values can be saved in the Session state as: string name = “Jeff”; Session[“Name”] = name; • Values can be retrieved from the Session state as: if(Session[“Name”]!=null) { string name=(string)Session[“Name”]; } Ver. 1.0 Slide 11 of 33
  • 12. Developing Web Applications Using ASP.NET Strategies for Managing Session State Data • Session state information can be stored in several locations. • Location can be configured by setting the mode attribute of the SessionState element in Web.config file. • Three possible storage modes can be used: InProc Mode State Server Mode SQL Server Mode Ver. 1.0 Slide 12 of 33
  • 13. Developing Web Applications Using ASP.NET Strategies for Managing Session State Data InProc Mode: • This is the default mode. • Session state data is stored in memory on the Web server within the process that is running the Web application. • This is the only mode that supports the Session.End event. • Session state information will be lost if application is restarted. • Session state cannot be shared between multiple servers in a Web farm. • To enable InProc mode, the following markup can be added within the <system.web> tags in the Web.config file: <sessionState mode=“InProc”></sessionState> Ver. 1.0 Slide 13 of 33
  • 14. Developing Web Applications Using ASP.NET Strategies for Managing Session State Data (Contd.) Following Diagram shows how Session state information is managed in InProc mode, when Cookies are enabled. Client Server Request first page Request received Receives first page Store cookie on client, send along with first page Create session object and Session ID Cookies store data in it Second request (with cookie) Fetch session object identified by cookie Send second page based on data in Session object Receives second page Fetch data from session object Ver. 1.0 Slide 14 of 33
  • 15. Developing Web Applications Using ASP.NET Strategies for Managing Session State Data (Contd.) State Server Mode: Session state data is managed by a separate process called the ASP.NET State Service. Session state information will not be lost if application is restarted. A single session state can be shared between multiple servers in a Web farm. ASP.NET State Service does not start automatically. To use ASP.NET State Service, make sure it is running on the desired server. Ver. 1.0 Slide 15 of 33
  • 16. Developing Web Applications Using ASP.NET Strategies for Managing Session State Data (Contd.) You need to configure each Web server in the Web farm to connect to the ASP.NET state service by modifying the Web.config file as: <configuration> <system.web> <sessionState mode="StateServer“ stateConnectionString= "tcpip=MyStateServer:42424" cookieless="AutoDetect" timeout="20"/> </system.web> </configuration> Ver. 1.0 Slide 16 of 33
  • 17. Developing Web Applications Using ASP.NET Strategies for Managing Session State Data (Contd.) Status of ASP.NET State Service can be checked from the Services window on the server on which the service is running. Ver. 1.0 Slide 17 of 33
  • 18. Developing Web Applications Using ASP.NET Strategies for Managing Session State Data (Contd.) SQL Server Mode: Session state data is stored in Microsoft SQL Server database. Session state information will not be lost, in case application is restarted. Session state can be shared between multiple servers in a Web farm. To use SQLServer mode, session state database must be installed on an existing SQL Server. Ver. 1.0 Slide 18 of 33
  • 19. Developing Web Applications Using ASP.NET Strategies for Managing Session State Data (Contd.) • After database has been installed, you need to specify SQLServer mode in Web.config file as: <configuration> <system.web> <sessionState mode="SQLServer" sqlConnectionString=" Integrated Security=SSPI;data source=MySqlServer;" /> </system.web> </configuration> Ver. 1.0 Slide 19 of 33
  • 20. Developing Web Applications Using ASP.NET The Cache Object An object can be stored in cache if it consumes a lot of server resources during creation and is being used frequently. This caching system can be used to improve the response time of an application. This caching system automatically removes items when system memory becomes scarce, in a process called scavenging. Ver. 1.0 Slide 20 of 33
  • 21. Developing Web Applications Using ASP.NET How to: Store and Retrieve State Data in the Cache Object To cache an item, you can use any of the following methods: Key name/Value pair method: • Add a value to the cache object by using the key name as indexer. • The following code caches the value in the Text property of a TextBox control called txtExample: Cache[“key"] = value; Insert method: • Specify the key name as the first argument and the value being cached as the second argument. • The following code performs the same task as the previous example by using the Insert method of the Cache object: Cache.Insert(“key", value); Ver. 1.0 Slide 21 of 33
  • 22. Developing Web Applications Using ASP.NET How to: Store and Retrieve State Data in the Cache Object (Contd.) • To retrieve values from the cache, Cache object can be referenced using the key name as the indexer: if (Cache[“key"] != null) { txtExample.Text = (string)Cache[“key"]; } • If you try to access an object from the cache that has been removed because of scarcity of memory, the cache will return a Null reference. Ver. 1.0 Slide 22 of 33
  • 23. Developing Web Applications Using ASP.NET Controlling Expiration Expiration time of a cached object can be specified during the object addition into the cache. Expiration time can be: Absolute Sliding Absolute Expiration: This method specifies a date and time when the object will be removed. To add an item to the cache with an absolute expiration of two minutes, the following code snippet can be used: Cache.Insert("CacheItem", "Cached Item Value", null, DateTime.Now.AddMinutes(2), System.Web.Caching.Cache.NoSlidingExpiration); Ver. 1.0 Slide 23 of 33
  • 24. Developing Web Applications Using ASP.NET Controlling Expiration Sliding Expiration: This method specifies a duration for which an item can lie unused in the cache. The caching system can scavenge the item if it has not been used for a duration that exceeds this value. To add an item to the cache with a sliding expiration of 10 minutes, the following code snippet can be used: Cache.Insert("CacheItem", "Cached Item Value", null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 10, 0)); Ver. 1.0 Slide 24 of 33
  • 25. Developing Web Applications Using ASP.NET Cache Item Priority • Policy for removing objects from the cache can be influenced by specifying CacheItemPriority value. • The caching system will scavenge low-priority items before high-priority items when system memory becomes scarce. • To set the priority of ac cached object to high at the time of creation, the following code snippet can be used: Cache.Insert("CacheItem", "Cached Item Value", null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, null); Ver. 1.0 Slide 25 of 33
  • 26. Developing Web Applications Using ASP.NET Cache Dependencies Cached items can become invalid because the source of the data has changed. Cached items may be dependent on files, directories, and other cached items. At the time of adding an item to the cache, you can specify the object on which the cached item depends. If any object (on which a cached item depends) changes, the cached item is automatically removed from the cache. Ver. 1.0 Slide 26 of 33
  • 27. Developing Web Applications Using ASP.NET How to: Define Dependencies Between Cached Items • You can add an item with a dependency to the cache by using the dependencies parameter in the Cache.Insert method, as: Cache.Insert(“Key", value, new CacheDependency Server.MapPath("~myConfig.xml"))); You can also add an item that depends on another cached item to the cache, as: string[] sDependencies = new string[1]; sDependencies[0] = “key_original"; CacheDependency dependency = new CacheDependency(null, sDependencies); Cache.Insert(“key_dependent", "This item depends on OriginalItem", dependency); Ver. 1.0 Slide 27 of 33
  • 28. Developing Web Applications Using ASP.NET How to: Delete Cached Data Cached data can be deleted by: • Setting expiration policies that determine the total amount of time the item remains in the cache. • Setting expiration policies that are based on the amount of time that must pass following the previous time the item was accessed. • Specifying files, directories, or keys that the item is dependent on. The item is removed from the cache when those dependencies change. • Removing items from the cache by using the Cache.Remove method as: Cache.Remove("MyData1"); Ver. 1.0 Slide 28 of 33
  • 29. Developing Web Applications Using ASP.NET How to: Implement Deletion Notifications in Cached Data • CacheItemRemovedCallback delegate defines the signature to use while writing the event handlers to respond when an item is deleted from the cache. • CacheItemRemovedReason enumeration can be used to make event handlers dependent upon the reason the item is deleted. Ver. 1.0 Slide 29 of 33
  • 30. Developing Web Applications Using ASP.NET How to: Implement Deletion Notifications in Cached Data (Contd.) To notify an application when an item is deleted from the cache: • Create a local variable that raises the event for the CacheItemRemovedCallback delegate as: private static CacheItemRemovedCallback onRemove = null; Create an event handler to respond when the item is removed from the cache as: static bool itemRemoved = false; static CacheItemRemovedReason reason; public void RemovedCallback(string key, object value, CacheItemRemovedReason callbackreason) { itemRemoved = true; reason = callbackreason; } Ver. 1.0 Slide 30 of 33
  • 31. Developing Web Applications Using ASP.NET How to: Implement Deletion Notifications in Cached Data (Contd.) • Create an instance of the CacheItemRemovedCallback delegate that calls the event handler as: onRemove = new CacheItemRemovedCallback(this.RemovedCallback); • Add the item to the cache by using the Cache.Insert method as: Cache.Insert("MyData1", Source, null, DateTime.Now.AddMinutes(2), NoSlidingExpiration, CacheItemPriority.High, onRemove); Ver. 1.0 Slide 31 of 33
  • 32. Developing Web Applications Using ASP.NET Summary In this session, you learned that: ViewState is the mechanism for preserving the contents and state of the controls on a Web page during a round trip. ASP.NET enables controls to preserve their ControlState even when ViewState is disabled. The Application and Session objects enable you to cache information for use by any page in your ASP.NET application. ASP.NET maintains a single Application object for each application on your Web server. An ASP.NET Session object is an object that represents a user’s visit to your application. Ver. 1.0 Slide 32 of 33
  • 33. Developing Web Applications Using ASP.NET Summary (Contd.) The possible storage modes for storing session state information are: • InProc • StateServer • SQLServer • ASP.NET has a powerful caching system that you can use to improve the response time of your application. • The ASP.NET caching system automatically removes items from the cache when system memory becomes scarce. Ver. 1.0 Slide 33 of 33

Notas del editor

  1. Tell the student how to set the value