SlideShare una empresa de Scribd logo
1 de 28
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

Más contenido relacionado

La actualidad más candente

ASP.Net Presentation Part3
ASP.Net Presentation Part3ASP.Net Presentation Part3
ASP.Net Presentation Part3Neeraj Mathur
 
Ch 04 asp.net application
Ch 04 asp.net application Ch 04 asp.net application
Ch 04 asp.net application Madhuri Kavade
 
Running ms sql stored procedures in mule
Running ms sql stored procedures in muleRunning ms sql stored procedures in mule
Running ms sql stored procedures in muleAnilKumar Etagowni
 
Кирилл Латыш "ERP on Websockets"
Кирилл Латыш "ERP on Websockets"Кирилл Латыш "ERP on Websockets"
Кирилл Латыш "ERP on Websockets"Fwdays
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsCarol McDonald
 
Simple blog wall creation on Java
Simple blog wall creation on JavaSimple blog wall creation on Java
Simple blog wall creation on JavaMax Titov
 
Mule with jdbc(my sql)
Mule with jdbc(my sql)Mule with jdbc(my sql)
Mule with jdbc(my sql)charan teja R
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actionsAren Zomorodian
 
Calling database with groovy in mule
Calling database with groovy in muleCalling database with groovy in mule
Calling database with groovy in muleAnirban Sen Chowdhary
 
javascript code for mysql database connection
javascript code for mysql database connectionjavascript code for mysql database connection
javascript code for mysql database connectionHitesh Kumar Markam
 
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...DicodingEvent
 
Academy PRO: ASP .NET Core
Academy PRO: ASP .NET Core Academy PRO: ASP .NET Core
Academy PRO: ASP .NET Core Binary Studio
 

La actualidad más candente (19)

ASP.Net Presentation Part3
ASP.Net Presentation Part3ASP.Net Presentation Part3
ASP.Net Presentation Part3
 
Ch05 state management
Ch05 state managementCh05 state management
Ch05 state management
 
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
 
Running ms sql stored procedures in mule
Running ms sql stored procedures in muleRunning ms sql stored procedures in mule
Running ms sql stored procedures in mule
 
Кирилл Латыш "ERP on Websockets"
Кирилл Латыш "ERP on Websockets"Кирилл Латыш "ERP on Websockets"
Кирилл Латыш "ERP on Websockets"
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 
Simple blog wall creation on Java
Simple blog wall creation on JavaSimple blog wall creation on Java
Simple blog wall creation on Java
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
Mule with jdbc(my sql)
Mule with jdbc(my sql)Mule with jdbc(my sql)
Mule with jdbc(my sql)
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
Calling database with groovy in mule
Calling database with groovy in muleCalling database with groovy in mule
Calling database with groovy in mule
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
 
Google App Engine
Google App EngineGoogle App Engine
Google App Engine
 
javascript code for mysql database connection
javascript code for mysql database connectionjavascript code for mysql database connection
javascript code for mysql database connection
 
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
 
Rest hello world_tutorial
Rest hello world_tutorialRest hello world_tutorial
Rest hello world_tutorial
 
Academy PRO: ASP .NET Core
Academy PRO: ASP .NET Core Academy PRO: ASP .NET Core
Academy PRO: ASP .NET Core
 
jsp MySQL database connectivity
jsp MySQL database connectivityjsp MySQL database connectivity
jsp MySQL database connectivity
 

Destacado

Destacado (20)

Ch3 server controls
Ch3 server controlsCh3 server controls
Ch3 server controls
 
Electronic data interchange
Electronic data interchangeElectronic data interchange
Electronic data interchange
 
Edi ppt
Edi pptEdi ppt
Edi ppt
 
How to make more impact as an engineer
How to make more impact as an engineerHow to make more impact as an engineer
How to make more impact as an engineer
 
Standard control in asp.net
Standard control in asp.netStandard control in asp.net
Standard control in asp.net
 
Ajax and ASP.NET AJAX
Ajax and ASP.NET AJAXAjax and ASP.NET AJAX
Ajax and ASP.NET AJAX
 
Presentation - Electronic Data Interchange
Presentation - Electronic Data InterchangePresentation - Electronic Data Interchange
Presentation - Electronic Data Interchange
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
 
Controls in asp.net
Controls in asp.netControls in asp.net
Controls in asp.net
 
Asp.Net Control Architecture
Asp.Net Control ArchitectureAsp.Net Control Architecture
Asp.Net Control Architecture
 
Electronic data interchange
Electronic data interchangeElectronic data interchange
Electronic data interchange
 
Validation controls in asp
Validation controls in aspValidation controls in asp
Validation controls in asp
 
State Management in ASP.NET
State Management in ASP.NETState Management in ASP.NET
State Management in ASP.NET
 
Intro To Asp Net And Web Forms
Intro To Asp Net And Web FormsIntro To Asp Net And Web Forms
Intro To Asp Net And Web Forms
 
Introduction To Asp.Net Ajax
Introduction To Asp.Net AjaxIntroduction To Asp.Net Ajax
Introduction To Asp.Net Ajax
 
Seminar ppt on digital signature
Seminar ppt on digital signatureSeminar ppt on digital signature
Seminar ppt on digital signature
 
Validation controls ppt
Validation controls pptValidation controls ppt
Validation controls ppt
 
Ajax control asp.net
Ajax control asp.netAjax control asp.net
Ajax control asp.net
 
ASP.NET State management
ASP.NET State managementASP.NET State management
ASP.NET State management
 
Presentation on asp.net controls
Presentation on asp.net controlsPresentation on asp.net controls
Presentation on asp.net controls
 

Similar a State management in ASP.NET

ASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauSpiffy
 
Whats new in ASP.NET 4.0
Whats new in ASP.NET 4.0Whats new in ASP.NET 4.0
Whats new in ASP.NET 4.0py_sunil
 
Session viii(state mngtserver)
Session viii(state mngtserver)Session viii(state mngtserver)
Session viii(state mngtserver)Shrijan Tiwari
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile appsIvano Malavolta
 
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
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session ManagementFahad Golra
 
Lifecycle Management of SOA Artifacts for WSO2 Products
Lifecycle Management of SOA Artifacts for WSO2 ProductsLifecycle Management of SOA Artifacts for WSO2 Products
Lifecycle Management of SOA Artifacts for WSO2 ProductsWSO2
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with SpringJoshua Long
 
05 asp.net session07
05 asp.net session0705 asp.net session07
05 asp.net session07Vivek chan
 
Rich Portlet Development in uPortal
Rich Portlet Development in uPortalRich Portlet Development in uPortal
Rich Portlet Development in uPortalJennifer Bourey
 
Creating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemCreating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemAzharul Haque Shohan
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWAREFIWARE
 
Site activity & performance analysis
Site activity & performance analysisSite activity & performance analysis
Site activity & performance analysisEyal Vardi
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web appsIvano Malavolta
 
Configuring was webauth
Configuring was webauthConfiguring was webauth
Configuring was webauthnagesh1003
 
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5Tieturi Oy
 

Similar a State management in ASP.NET (20)

ASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin Lau
 
Whats new in ASP.NET 4.0
Whats new in ASP.NET 4.0Whats new in ASP.NET 4.0
Whats new in ASP.NET 4.0
 
Session viii(state mngtserver)
Session viii(state mngtserver)Session viii(state mngtserver)
Session viii(state mngtserver)
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
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
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
Lifecycle Management of SOA Artifacts for WSO2 Products
Lifecycle Management of SOA Artifacts for WSO2 ProductsLifecycle Management of SOA Artifacts for WSO2 Products
Lifecycle Management of SOA Artifacts for WSO2 Products
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with Spring
 
05 asp.net session07
05 asp.net session0705 asp.net session07
05 asp.net session07
 
Rich Portlet Development in uPortal
Rich Portlet Development in uPortalRich Portlet Development in uPortal
Rich Portlet Development in uPortal
 
Servlets
ServletsServlets
Servlets
 
Managing states
Managing statesManaging states
Managing states
 
Creating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemCreating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login System
 
Dropwizard
DropwizardDropwizard
Dropwizard
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWARE
 
Site activity & performance analysis
Site activity & performance analysisSite activity & performance analysis
Site activity & performance analysis
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web apps
 
Configuring was webauth
Configuring was webauthConfiguring was webauth
Configuring was webauth
 
Spring WebApplication development
Spring WebApplication developmentSpring WebApplication development
Spring WebApplication development
 
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
 

Más de Om Vikram Thapa

Más de Om Vikram Thapa (20)

Next Set of Leaders Series
Next Set of Leaders SeriesNext Set of Leaders Series
Next Set of Leaders Series
 
Integration Testing at go-mmt
Integration Testing at go-mmtIntegration Testing at go-mmt
Integration Testing at go-mmt
 
Understanding payments
Understanding paymentsUnderstanding payments
Understanding payments
 
System Alerting & Monitoring
System Alerting & MonitoringSystem Alerting & Monitoring
System Alerting & Monitoring
 
Serverless computing
Serverless computingServerless computing
Serverless computing
 
Sumologic Community
Sumologic CommunitySumologic Community
Sumologic Community
 
Postman Integration Testing
Postman Integration TestingPostman Integration Testing
Postman Integration Testing
 
Scalibility
ScalibilityScalibility
Scalibility
 
5 Dysfunctions of a team
5 Dysfunctions of a team5 Dysfunctions of a team
5 Dysfunctions of a team
 
AWS Must Know
AWS Must KnowAWS Must Know
AWS Must Know
 
Continuous Feedback
Continuous FeedbackContinuous Feedback
Continuous Feedback
 
Sql views, stored procedure, functions
Sql views, stored procedure, functionsSql views, stored procedure, functions
Sql views, stored procedure, functions
 
Confluence + jira together
Confluence + jira togetherConfluence + jira together
Confluence + jira together
 
Understanding WhatFix
Understanding WhatFixUnderstanding WhatFix
Understanding WhatFix
 
Tech Recruitment Process
Tech Recruitment Process Tech Recruitment Process
Tech Recruitment Process
 
Jira Workshop
Jira WorkshopJira Workshop
Jira Workshop
 
Security@ecommerce
Security@ecommerceSecurity@ecommerce
Security@ecommerce
 
Understanding iis part2
Understanding iis part2Understanding iis part2
Understanding iis part2
 
Understanding iis part1
Understanding iis part1Understanding iis part1
Understanding iis part1
 
.Net framework
.Net framework.Net framework
.Net framework
 

Último

Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 

Último (20)

Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 

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" ... }

Notas del editor

  1. Programming ASP.NET Copyright © 2001-2002
  2. 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.
  3. Programming ASP.NET Copyright © 2001-2002 Types stored in session state using this model do NOT have to be serializable.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. 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.
  10. 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.
  11. 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).
  12. 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.