SlideShare a Scribd company logo
State Management
     in ASP.NET
Agenda
 View state
 Application cache
 Session state
 Profiles
 Cookies
1. View State
 Mechanism for persisting relatively small
 pieces of data across postbacks
   Used by pages and controls to persist state
   Also available to you for persisting state
 Relies on hidden input field (__VIEWSTATE)
 Accessed through ViewState property
 Tamper-proof; optionally encryptable
Reading and Writing View State
// Write the price of an item to view state
ViewState["Price"] = price;

// Read the price back following a postback
decimal price = (decimal) ViewState["Price"];
View State and Data Types
 What data types can you store in view state?
   Primitive types (strings, integers, etc.)
   Types accompanied by type converters
   Serializable types (types compatible with
   BinaryFormatter)
 System.Web.UI.LosFormatter performs
 serialization and deserialization
   Optimized for compact storage of strings,
   integers, booleans, arrays, and hash tables
2. Application Cache
 Intelligent in-memory data store
   Item prioritization and automatic eviction
   Time-based expiration and cache dependencies
   Cache removal callbacks
 Application scope (available to all users)
 Accessed through Cache property
   Page.Cache - ASPX
   HttpContext.Cache - Global.asax
 Great tool for enhancing performance
Using the Application Cache
// Write a Hashtable containing stock prices to the cache
Hashtable stocks = new Hashtable ();
stocks.Add ("AMZN", 10.00m);
stocks.Add ("INTC", 20.00m);
stocks.Add ("MSFT", 30.00m);
Cache.Insert ("Stocks", stocks);
  .
  .
  .
// Fetch the price of Microsoft stock
Hashtable stocks = (Hashtable) Cache["Stocks"];
if (stocks != null) // Important!
    decimal msft = (decimal) stocks["MSFT"];
  .
  .
  .
// Remove the Hashtable from the cache
Cache.Remove ("Stocks");
Temporal Expiration
Cache.Insert ("Stocks", stocks, null,
    DateTime.Now.AddMinutes (5), Cache.NoSlidingExpiration);




                 Expire after 5 minutes


          Expire if 5 minutes elapse without the
          item being retrieved from the cache



Cache.Insert ("Stocks", stocks, null,
    Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes (5));
Cache Dependencies
Cache.Insert ("Stocks", stocks,
    new CacheDependency (Server.MapPath ("Stocks.xml")));




                 Expire if and when Stocks.xml changes


   Expire if and when the "Stocks"
   database's "Prices" table changes



Cache.Insert ("Stocks", stocks,
    new SqlCacheDependency ("Stocks", "Prices"));
3. Session State
 Read/write per-user data store
 Accessed through Session property
   Page.Session - ASPX
   HttpApplication.Session - Global.asax
 Provider-based for flexible data storage
   In-process (default)
   State server process
   SQL Server
 Cookied or cookieless
Using Session State
// Write a ShoppingCart object to session state
ShoppingCart cart = new ShoppingCart ();
Session["Cart"] = cart;
  .
  .
  .
// Read this user's ShoppingCart from session state
ShoppingCart cart = (ShoppingCart) Session["Cart"];
  .
  .
  .
// Remove this user's ShoppingCart from session state
Session.Remove ("Cart");
In-Process Session State
<!-- Web.config -->
<configuration>
  <system.web>
    <sessionState mode="InProc" />
      ...
  </system.web>
</configuration>




Web Server

                                     Session state stored inside
      ASP.NET       Session State    ASP.NET's worker process
State Server Session State
<!-- Web.config -->
<configuration>
  <system.web>
    <sessionState mode="StateServer"
      stateConnectionString="tcpip=24.159.185.213:42424" />
        ...
  </system.web>
</configuration>




Web Server                  State Server

                                 aspnet_state          ASP.NET state
      ASP.NET                                          service (aspnet_-
                                   Process
                                                       state.exe)
SQL Server Session State
<!-- Web.config -->
<configuration>
  <system.web>
    <sessionState mode="SQLServer"
      sqlConnectionString="server=orion;integrated security=true" />
        ...
  </system.web>
</configuration>




Web Server                  Database Server

                                                       Created with
      ASP.NET                     ASPState
                                                       InstallSqlState.sql or
                                  Database
                                                       InstallPersistSql-
                                                       State.sql
Session Events
  Session_Start event signals new session
  Session_End event signals end of session
  Process with handlers in Global.asax
void Session_Start ()
{
    // Create a shopping cart and store it in session state
    // each time a new session is started
    Session["Cart"] = new ShoppingCart ();
}

void Session_End ()
{
    // Do any cleanup here when session ends
}
Session Time-Outs
  Sessions end when predetermined time
  period elapses without any requests from
  session's owner
  Default time-out = 20 minutes
  Time-out can be changed in Web.config
<!-- Web.config -->
<configuration>
  <system.web>
    <sessionState timeout="60" />
      ...
  </system.web>
</configuration>
4. Profile Service
 Stores per-user data persistently
   Strongly typed access (unlike session state)
   On-demand lookup (unlike session state)
   Long-lived (unlike session state)
   Supports authenticated and anonymous users
 Accessed through dynamically compiled
 HttpProfileBase derivatives (HttpProfile)
 Provider-based for flexible data storage
Profile Schema
Profiles
                                  HttpProfileBase

           HttpProfile (Autogenerated          HttpProfile (Autogenerated
           HttpProfileBase-Derivative)         HttpProfileBase-Derivative)

Profile Providers
       AccessProfileProvider       SqlProfileProvider         Other Providers


Profile Data Stores


                                                                  Other
                Access                   SQL Server
                                                                Data Stores
Defining a Profile
<configuration>
  <system.web>
    <profile>
      <properties>
        <add name="ScreenName" />
        <add name="Posts" type="System.Int32" defaultValue="0" />
        <add name="LastPost" type="System.DateTime" />
      </properties>
    </profile>
  </system.web>
</configuration>




Usage
// Increment the current user's post count
Profile.Posts = Profile.Posts + 1;

// Update the current user's last post date
Profile.LastPost = DateTime.Now;
How Profiles Work
                                      Autogenerated class
                                      representing the page

public partial class page_aspx : System.Web.UI.Page
{
  ...
    protected ASP.HttpProfile Profile
    {
        get { return ((ASP.HttpProfile)(this.Context.Profile)); }
    }
  ...
}




Autogenerated class derived                Profile property included in
from HttpProfileBase                       autogenerated page class
Defining a Profile Group
<configuration>
  <system.web>
    <profile>
      <properties>
        <add name="ScreenName" />
        <group name="Forums">
          <add name="Posts" type="System.Int32" defaultValue="0" />
          <add name="LastPost" type="System.DateTime" />
        </group>
      </properties>
    </profile>
  </system.web>
</configuration>



Usage
// Increment the current user's post count
Profile.Forums.Posts = Profile.Forums.Posts + 1;

// Update the current user's last post date
Profile.Forums.LastPost = DateTime.Now;
Anonymous User Profiles
 By default, profiles aren't available for
 anonymous (unauthenticated) users
   Data keyed by authenticated user IDs
 Anonymous profiles can be enabled
   Step 1: Enable anonymous identification
   Step 2: Specify which profile properties are
   available to anonymous users
 Data keyed by user anonymous IDs
Profiles for Anonymous Users
<configuration>
  <system.web>
    <anonymousIdentification enabled="true" />
    <profile>
      <properties>
        <add name="ScreenName" allowAnonymous="true" />
        <add name="Posts" type="System.Int32" defaultValue="0 />
        <add name="LastPost" type="System.DateTime" />
      </properties>
    </profile>
  </system.web>
</configuration>
5. Cookies
 Mechanism for persisting textual data
   Described in RFC 2109
   For relatively small pieces of data
 HttpCookie class encapsulates cookies
 HttpRequest.Cookies collection enables
 cookies to be read from requests
 HttpResponse.Cookies collection enables
 cookies to be written to responses
HttpCookie Properties
           Name                                Description

 Name             Cookie name (e.g., "UserName=Jeffpro")


 Value            Cookie value (e.g., "UserName=Jeffpro")


 Values           Collection of cookie values (multivalue cookies only)


 HasKeys          True if cookie contains multiple values


 Domain           Domain to transmit cookie to


 Expires          Cookie's expiration date and time


 Secure           True if cookie should only be transmitted over HTTPS


 Path             Path to transmit cookie to
Creating a Cookie
HttpCookie cookie = new HttpCookie ("UserName", "Jeffpro");
Response.Cookies.Add (cookie);




                               Cookie name

                                       Cookie value
Reading a Cookie
HttpCookie cookie = Request.Cookies["UserName"];
if (cookie != null) {
    string username = cookie.Value; // "Jeffpro"
      ...
}
Thank You

More Related Content

What's hot (19)

PPSX
ASP.Net Presentation Part3
Neeraj Mathur
 
PPTX
Ch05 state management
Madhuri Kavade
 
PPTX
Ch 04 asp.net application
Madhuri Kavade
 
PPTX
State management
Muhammad Amir
 
ODP
Running ms sql stored procedures in mule
AnilKumar Etagowni
 
PDF
Кирилл Латыш "ERP on Websockets"
Fwdays
 
PPTX
Rest with Java EE 6 , Security , Backbone.js
Carol McDonald
 
PPTX
Simple blog wall creation on Java
Max Titov
 
PDF
Servlets intro
vantinhkhuc
 
DOCX
Mule with jdbc(my sql)
charan teja R
 
PPTX
Web Technologies - forms and actions
Aren Zomorodian
 
PPTX
Calling database with groovy in mule
Anirban Sen Chowdhary
 
PPT
Asp.net.
Naveen Sihag
 
PDF
Google App Engine
Anil Saldanha
 
DOCX
javascript code for mysql database connection
Hitesh Kumar Markam
 
PDF
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
DicodingEvent
 
PDF
Rest hello world_tutorial
Aravindharamanan S
 
PPTX
Academy PRO: ASP .NET Core
Binary Studio
 
PPTX
jsp MySQL database connectivity
baabtra.com - No. 1 supplier of quality freshers
 
ASP.Net Presentation Part3
Neeraj Mathur
 
Ch05 state management
Madhuri Kavade
 
Ch 04 asp.net application
Madhuri Kavade
 
State management
Muhammad Amir
 
Running ms sql stored procedures in mule
AnilKumar Etagowni
 
Кирилл Латыш "ERP on Websockets"
Fwdays
 
Rest with Java EE 6 , Security , Backbone.js
Carol McDonald
 
Simple blog wall creation on Java
Max Titov
 
Servlets intro
vantinhkhuc
 
Mule with jdbc(my sql)
charan teja R
 
Web Technologies - forms and actions
Aren Zomorodian
 
Calling database with groovy in mule
Anirban Sen Chowdhary
 
Asp.net.
Naveen Sihag
 
Google App Engine
Anil Saldanha
 
javascript code for mysql database connection
Hitesh Kumar Markam
 
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
DicodingEvent
 
Rest hello world_tutorial
Aravindharamanan S
 
Academy PRO: ASP .NET Core
Binary Studio
 
jsp MySQL database connectivity
baabtra.com - No. 1 supplier of quality freshers
 

Viewers also liked (20)

PPTX
Ch3 server controls
Madhuri Kavade
 
PPTX
Electronic data interchange
Abhishek Nayak
 
PPT
Edi ppt
Sheetal Verma
 
PPTX
How to make more impact as an engineer
Peter Gfader
 
PPTX
Standard control in asp.net
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Ajax and ASP.NET AJAX
Julie Iskander
 
PPTX
Presentation - Electronic Data Interchange
Sharad Srivastava
 
PPTX
Introduction to ASP.NET
Peter Gfader
 
PPTX
Asp.Net Control Architecture
Sundararajan Subramanian
 
PPTX
Electronic data interchange
Rohit Kumar
 
PPTX
Validation controls in asp
Shishir Jain
 
PPTX
State Management in ASP.NET
Shyam Sir
 
PPT
Intro To Asp Net And Web Forms
SAMIR BHOGAYTA
 
PPT
Introduction To Asp.Net Ajax
Jeff Blankenburg
 
PPTX
Seminar ppt on digital signature
jolly9293
 
PPT
Validation controls ppt
Iblesoft
 
PPTX
Ajax control asp.net
Sireesh K
 
PPTX
ASP.NET State management
Shivanand Arur
 
PPTX
Presentation on asp.net controls
Reshi Unen
 
Ch3 server controls
Madhuri Kavade
 
Electronic data interchange
Abhishek Nayak
 
Edi ppt
Sheetal Verma
 
How to make more impact as an engineer
Peter Gfader
 
Ajax and ASP.NET AJAX
Julie Iskander
 
Presentation - Electronic Data Interchange
Sharad Srivastava
 
Introduction to ASP.NET
Peter Gfader
 
Asp.Net Control Architecture
Sundararajan Subramanian
 
Electronic data interchange
Rohit Kumar
 
Validation controls in asp
Shishir Jain
 
State Management in ASP.NET
Shyam Sir
 
Intro To Asp Net And Web Forms
SAMIR BHOGAYTA
 
Introduction To Asp.Net Ajax
Jeff Blankenburg
 
Seminar ppt on digital signature
jolly9293
 
Validation controls ppt
Iblesoft
 
Ajax control asp.net
Sireesh K
 
ASP.NET State management
Shivanand Arur
 
Presentation on asp.net controls
Reshi Unen
 
Ad

Similar to State management in ASP.NET (20)

PPT
Session and state management
Paneliya Prince
 
PPSX
05 asp.net session07
Vivek Singh Chandel
 
PPS
06 asp.net session08
Niit Care
 
PPT
StateManagement in ASP.Net.ppt
charusharma165
 
PPTX
State management
teach4uin
 
PPTX
Chapter 8 part1
application developer
 
PPS
05 asp.net session07
Mani Chaubey
 
PPSX
06 asp.net session08
Vivek Singh Chandel
 
PPTX
Chapter 8 part2
application developer
 
PPS
05 asp.net session07
Niit Care
 
PPS
06 asp.net session08
Mani Chaubey
 
DOC
State management in asp
Ibrahim MH
 
PPTX
81.pptx ajx fyjc semester paper 2 parrtens
epfoportal69
 
PPT
The complete ASP.NET (IIS) Tutorial with code example in power point slide show
Subhas Malik
 
PPTX
ASP.NET Lecture 2
Julie Iskander
 
PPT
2310 b 14
Krazy Koder
 
PDF
Session and Cookies.pdf
HamnaGhani1
 
PDF
state management asp.net
Pratiksha Srivastava
 
PPT
IEEE KUET SPAC presentation
ahsanmm
 
PPTX
Dotnet- An overview of ASP.NET & ADO.NET- Mazenet solution
Mazenetsolution
 
Session and state management
Paneliya Prince
 
05 asp.net session07
Vivek Singh Chandel
 
06 asp.net session08
Niit Care
 
StateManagement in ASP.Net.ppt
charusharma165
 
State management
teach4uin
 
Chapter 8 part1
application developer
 
05 asp.net session07
Mani Chaubey
 
06 asp.net session08
Vivek Singh Chandel
 
Chapter 8 part2
application developer
 
05 asp.net session07
Niit Care
 
06 asp.net session08
Mani Chaubey
 
State management in asp
Ibrahim MH
 
81.pptx ajx fyjc semester paper 2 parrtens
epfoportal69
 
The complete ASP.NET (IIS) Tutorial with code example in power point slide show
Subhas Malik
 
ASP.NET Lecture 2
Julie Iskander
 
2310 b 14
Krazy Koder
 
Session and Cookies.pdf
HamnaGhani1
 
state management asp.net
Pratiksha Srivastava
 
IEEE KUET SPAC presentation
ahsanmm
 
Dotnet- An overview of ASP.NET & ADO.NET- Mazenet solution
Mazenetsolution
 
Ad

More from Om Vikram Thapa (20)

PDF
Next Set of Leaders Series
Om Vikram Thapa
 
PDF
Integration Testing at go-mmt
Om Vikram Thapa
 
PDF
Understanding payments
Om Vikram Thapa
 
PDF
System Alerting & Monitoring
Om Vikram Thapa
 
PDF
Serverless computing
Om Vikram Thapa
 
PDF
Sumologic Community
Om Vikram Thapa
 
PPTX
Postman Integration Testing
Om Vikram Thapa
 
PDF
Scalibility
Om Vikram Thapa
 
PDF
5 Dysfunctions of a team
Om Vikram Thapa
 
PDF
AWS Must Know
Om Vikram Thapa
 
PDF
Continuous Feedback
Om Vikram Thapa
 
PDF
Sql views, stored procedure, functions
Om Vikram Thapa
 
PDF
Confluence + jira together
Om Vikram Thapa
 
PDF
Understanding WhatFix
Om Vikram Thapa
 
PDF
Tech Recruitment Process
Om Vikram Thapa
 
PPTX
Jira Workshop
Om Vikram Thapa
 
PPT
Security@ecommerce
Om Vikram Thapa
 
PPT
Understanding iis part2
Om Vikram Thapa
 
PPT
Understanding iis part1
Om Vikram Thapa
 
PPT
.Net framework
Om Vikram Thapa
 
Next Set of Leaders Series
Om Vikram Thapa
 
Integration Testing at go-mmt
Om Vikram Thapa
 
Understanding payments
Om Vikram Thapa
 
System Alerting & Monitoring
Om Vikram Thapa
 
Serverless computing
Om Vikram Thapa
 
Sumologic Community
Om Vikram Thapa
 
Postman Integration Testing
Om Vikram Thapa
 
Scalibility
Om Vikram Thapa
 
5 Dysfunctions of a team
Om Vikram Thapa
 
AWS Must Know
Om Vikram Thapa
 
Continuous Feedback
Om Vikram Thapa
 
Sql views, stored procedure, functions
Om Vikram Thapa
 
Confluence + jira together
Om Vikram Thapa
 
Understanding WhatFix
Om Vikram Thapa
 
Tech Recruitment Process
Om Vikram Thapa
 
Jira Workshop
Om Vikram Thapa
 
Security@ecommerce
Om Vikram Thapa
 
Understanding iis part2
Om Vikram Thapa
 
Understanding iis part1
Om Vikram Thapa
 
.Net framework
Om Vikram Thapa
 

Recently uploaded (20)

PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
July Patch Tuesday
Ivanti
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Python basic programing language for automation
DanialHabibi2
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
July Patch Tuesday
Ivanti
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 

State management in ASP.NET

  • 1. State Management in ASP.NET
  • 2. Agenda View state Application cache Session state Profiles Cookies
  • 3. 1. View State Mechanism for persisting relatively small pieces of data across postbacks Used by pages and controls to persist state Also available to you for persisting state Relies on hidden input field (__VIEWSTATE) Accessed through ViewState property Tamper-proof; optionally encryptable
  • 4. Reading and Writing View State // Write the price of an item to view state ViewState["Price"] = price; // Read the price back following a postback decimal price = (decimal) ViewState["Price"];
  • 5. View State and Data Types What data types can you store in view state? Primitive types (strings, integers, etc.) Types accompanied by type converters Serializable types (types compatible with BinaryFormatter) System.Web.UI.LosFormatter performs serialization and deserialization Optimized for compact storage of strings, integers, booleans, arrays, and hash tables
  • 6. 2. Application Cache Intelligent in-memory data store Item prioritization and automatic eviction Time-based expiration and cache dependencies Cache removal callbacks Application scope (available to all users) Accessed through Cache property Page.Cache - ASPX HttpContext.Cache - Global.asax Great tool for enhancing performance
  • 7. Using the Application Cache // Write a Hashtable containing stock prices to the cache Hashtable stocks = new Hashtable (); stocks.Add ("AMZN", 10.00m); stocks.Add ("INTC", 20.00m); stocks.Add ("MSFT", 30.00m); Cache.Insert ("Stocks", stocks); . . . // Fetch the price of Microsoft stock Hashtable stocks = (Hashtable) Cache["Stocks"]; if (stocks != null) // Important! decimal msft = (decimal) stocks["MSFT"]; . . . // Remove the Hashtable from the cache Cache.Remove ("Stocks");
  • 8. Temporal Expiration Cache.Insert ("Stocks", stocks, null, DateTime.Now.AddMinutes (5), Cache.NoSlidingExpiration); Expire after 5 minutes Expire if 5 minutes elapse without the item being retrieved from the cache Cache.Insert ("Stocks", stocks, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes (5));
  • 9. Cache Dependencies Cache.Insert ("Stocks", stocks, new CacheDependency (Server.MapPath ("Stocks.xml"))); Expire if and when Stocks.xml changes Expire if and when the "Stocks" database's "Prices" table changes Cache.Insert ("Stocks", stocks, new SqlCacheDependency ("Stocks", "Prices"));
  • 10. 3. Session State Read/write per-user data store Accessed through Session property Page.Session - ASPX HttpApplication.Session - Global.asax Provider-based for flexible data storage In-process (default) State server process SQL Server Cookied or cookieless
  • 11. Using Session State // Write a ShoppingCart object to session state ShoppingCart cart = new ShoppingCart (); Session["Cart"] = cart; . . . // Read this user's ShoppingCart from session state ShoppingCart cart = (ShoppingCart) Session["Cart"]; . . . // Remove this user's ShoppingCart from session state Session.Remove ("Cart");
  • 12. In-Process Session State <!-- Web.config --> <configuration> <system.web> <sessionState mode="InProc" /> ... </system.web> </configuration> Web Server Session state stored inside ASP.NET Session State ASP.NET's worker process
  • 13. State Server Session State <!-- Web.config --> <configuration> <system.web> <sessionState mode="StateServer" stateConnectionString="tcpip=24.159.185.213:42424" /> ... </system.web> </configuration> Web Server State Server aspnet_state ASP.NET state ASP.NET service (aspnet_- Process state.exe)
  • 14. SQL Server Session State <!-- Web.config --> <configuration> <system.web> <sessionState mode="SQLServer" sqlConnectionString="server=orion;integrated security=true" /> ... </system.web> </configuration> Web Server Database Server Created with ASP.NET ASPState InstallSqlState.sql or Database InstallPersistSql- State.sql
  • 15. Session Events Session_Start event signals new session Session_End event signals end of session Process with handlers in Global.asax void Session_Start () { // Create a shopping cart and store it in session state // each time a new session is started Session["Cart"] = new ShoppingCart (); } void Session_End () { // Do any cleanup here when session ends }
  • 16. Session Time-Outs Sessions end when predetermined time period elapses without any requests from session's owner Default time-out = 20 minutes Time-out can be changed in Web.config <!-- Web.config --> <configuration> <system.web> <sessionState timeout="60" /> ... </system.web> </configuration>
  • 17. 4. Profile Service Stores per-user data persistently Strongly typed access (unlike session state) On-demand lookup (unlike session state) Long-lived (unlike session state) Supports authenticated and anonymous users Accessed through dynamically compiled HttpProfileBase derivatives (HttpProfile) Provider-based for flexible data storage
  • 18. Profile Schema Profiles HttpProfileBase HttpProfile (Autogenerated HttpProfile (Autogenerated HttpProfileBase-Derivative) HttpProfileBase-Derivative) Profile Providers AccessProfileProvider SqlProfileProvider Other Providers Profile Data Stores Other Access SQL Server Data Stores
  • 19. Defining a Profile <configuration> <system.web> <profile> <properties> <add name="ScreenName" /> <add name="Posts" type="System.Int32" defaultValue="0" /> <add name="LastPost" type="System.DateTime" /> </properties> </profile> </system.web> </configuration> Usage // Increment the current user's post count Profile.Posts = Profile.Posts + 1; // Update the current user's last post date Profile.LastPost = DateTime.Now;
  • 20. How Profiles Work Autogenerated class representing the page public partial class page_aspx : System.Web.UI.Page { ... protected ASP.HttpProfile Profile { get { return ((ASP.HttpProfile)(this.Context.Profile)); } } ... } Autogenerated class derived Profile property included in from HttpProfileBase autogenerated page class
  • 21. Defining a Profile Group <configuration> <system.web> <profile> <properties> <add name="ScreenName" /> <group name="Forums"> <add name="Posts" type="System.Int32" defaultValue="0" /> <add name="LastPost" type="System.DateTime" /> </group> </properties> </profile> </system.web> </configuration> Usage // Increment the current user's post count Profile.Forums.Posts = Profile.Forums.Posts + 1; // Update the current user's last post date Profile.Forums.LastPost = DateTime.Now;
  • 22. Anonymous User Profiles By default, profiles aren't available for anonymous (unauthenticated) users Data keyed by authenticated user IDs Anonymous profiles can be enabled Step 1: Enable anonymous identification Step 2: Specify which profile properties are available to anonymous users Data keyed by user anonymous IDs
  • 23. Profiles for Anonymous Users <configuration> <system.web> <anonymousIdentification enabled="true" /> <profile> <properties> <add name="ScreenName" allowAnonymous="true" /> <add name="Posts" type="System.Int32" defaultValue="0 /> <add name="LastPost" type="System.DateTime" /> </properties> </profile> </system.web> </configuration>
  • 24. 5. Cookies Mechanism for persisting textual data Described in RFC 2109 For relatively small pieces of data HttpCookie class encapsulates cookies HttpRequest.Cookies collection enables cookies to be read from requests HttpResponse.Cookies collection enables cookies to be written to responses
  • 25. HttpCookie Properties Name Description Name Cookie name (e.g., "UserName=Jeffpro") Value Cookie value (e.g., "UserName=Jeffpro") Values Collection of cookie values (multivalue cookies only) HasKeys True if cookie contains multiple values Domain Domain to transmit cookie to Expires Cookie's expiration date and time Secure True if cookie should only be transmitted over HTTPS Path Path to transmit cookie to
  • 26. Creating a Cookie HttpCookie cookie = new HttpCookie ("UserName", "Jeffpro"); Response.Cookies.Add (cookie); Cookie name Cookie value
  • 27. Reading a Cookie HttpCookie cookie = Request.Cookies["UserName"]; if (cookie != null) { string username = cookie.Value; // "Jeffpro" ... }

Editor's Notes

  • #2: Programming ASP.NET Copyright © 2001-2002
  • #6: Programming ASP.NET Copyright © 2001-2002 View state is serialized and deserialized by the System.Web.UI.LosFormatter class (&amp;quot;Los&amp;quot; stands for &amp;quot;Limited Object Serialization&amp;quot;). LosFormatter is capable of serializing any type that is accompanied by a registered type converter or that can be serialized with BinaryFormatter, but it is optimized for storage of certain types.
  • #13: Programming ASP.NET Copyright © 2001-2002 Types stored in session state using this model do NOT have to be serializable.
  • #14: Programming ASP.NET Copyright © 2001-2002 Types stored in session state using this model must be serializable. Moving session state off-machine in this manner is one way to make sessions comaptible with Web farms. The state server process must be started before this model can be used. It can be configured to autostart through Windows&apos; Services control panel applet.
  • #15: Programming ASP.NET Copyright © 2001-2002 Types stored in session state using this model must be serializable. Moving session state off-machine in this manner is another way to make sessions comaptible with Web farms. The ASPState database must be created before SQL Server session state can be used. ASP.NET comes with two SQL scripts for creating the database. InstallSqlState.sql creates a database that stores data in temp tables (memory), meaning that if the database server crashes, session state is lost. InstallPersistSqlState, which was introduced in ASP.NET 1.1, creates a database that stores data in disk-based tables and thus provides a measure of robustness.
  • #18: Programming ASP.NET Copyright © 2001-2002 On the surface, the profile service sounds a lot like session state since both are designed to store per-user data. However, profiles and session state differ in significant ways. Profiles should not be construed as a replacement for session state, but rather as a complement to it. For applications that store shopping carts and other per-user data for a finite period of time, session state is still a viable option.
  • #19: Programming ASP.NET Copyright © 2001-2002 The HttpProfile class, which derives from System.Web.Profile.HttpProfileBase, provides strongly typed access to profile data. You won&apos;t find HttpProfile documented in the .NET Framework SDK because it&apos;s not part of the .NET Framework Class Library; instead, it is dynamically generated by ASP.NET. Applications read and write profile data by reading and writing HttpProfile properties. HttpProfile, in turn, uses providers to access the underlying data stores.
  • #20: Programming ASP.NET Copyright © 2001-2002 A profile characterizes the data that you wish to store for individual visitors to your site. It&apos;s defined in Web.config as shown here and will probably differ in every application. This sample profile uses only .NET Framework data types, but custom data types are supported, too. The type attribute specifies the data type; the default is string if no type is specified. The defaultValue attribute allows you to specify a property&apos;s default value. This example might be appropriate for a forums application where you wish to store a screen name, a post count, and the date and time of the last post for each visitor.
  • #21: Programming ASP.NET Copyright © 2001-2002 At first glance, statements that read and write profile properties seem like magic because there is no property named Profile in System.Web.UI.Page. Why, for example, does the code on the previous slide compile? It compiles because ASP.NET inserts a Profile property into classes that it derives from System.Web.UI.Page. This slide shows the property&apos;s implementation, which simply returns the HttpProfile reference stored in HttpContext.Profile. ASP.NET also inserts a Profile property into the HttpAplication-derived class that represents the application itself, meaning that you can use the Profile property to access profiles in Global.asax.
  • #22: Programming ASP.NET Copyright © 2001-2002 This example defines a profile containing an ungrouped property named ScreenName and grouped properties named Posts and LastPosts. The grouped properties belong to a group named Forums.
  • #23: Programming ASP.NET Copyright © 2001-2002 Profiles can be used for anonymous users as well as authenticated users, but only if anonymous user profiles are specifically enabled. Enabling anonymous profiles requires two steps. First you use a configuration directive to enable ASP.NET&apos;s anonymous identification service. Then you attribute each profile property that you wish to store for anonymous users allowAnonymous=&amp;quot;true.&amp;quot; For authenticated users, ASP.NET keys profile data with unique user IDs generated by the Membership service. For anonymous users, ASP.NET keys profile data with anonymous user IDs generated by the anonymous identification service. Anonymous user IDs are round-tripped (by default) in cookies. Cookieless operation is also supported for the benefit of users whose browsers don&apos;t support cookies (or have cookie support disabled).
  • #24: Programming ASP.NET Copyright © 2001-2002 &lt;anonymousIdentification enabled=&amp;quot;true&amp;quot;&gt; enables the anonymous identification service, which is a prerequisite for storing profile values for anonymous users. allowAnonymous=&amp;quot;true&amp;quot; tells ASP.NET to store ScreenName values for anonymous users. Since Posts and LastPost lack allowAnonymous=&amp;quot;true&amp;quot; attributes, they won&apos;t be persisted in profiles for anonymous users.