+ All Categories
Home > Documents > Http:// ASP.NET Managing State Roberto Brunetti [email protected] Blog: blogs.devleap.com/rob.rss.

Http:// ASP.NET Managing State Roberto Brunetti [email protected] Blog: blogs.devleap.com/rob.rss.

Date post: 01-May-2015
Category:
Upload: geltrude-catalano
View: 216 times
Download: 0 times
Share this document with a friend
Popular Tags:
66
http://www.DevLeap.it http://www.DevLeap.it ASP.NET Managing State ASP.NET Managing State Roberto Brunetti Roberto Brunetti [email protected] [email protected] Blog: Blog: blogs.devleap.com/rob.rss blogs.devleap.com/rob.rss
Transcript
Page 1: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

ASP.NET Managing ASP.NET Managing StateState

Roberto BrunettiRoberto Brunetti

[email protected]@DevLeap.it

Blog: Blog: blogs.devleap.com/rob.rssblogs.devleap.com/rob.rss

Page 2: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Chi siamoChi siamo

• www.DevLeap.itwww.DevLeap.it• Un gruppo di 5 persone con tanta Un gruppo di 5 persone con tanta

voglia divoglia di• Studiare a fondo le tecnologieStudiare a fondo le tecnologie• Capire il “behind the scenes”Capire il “behind the scenes”• Implementare soluzioni realiImplementare soluzioni reali• Confrontarsi con le problematiche realiConfrontarsi con le problematiche reali• Sperimentare nuove ideeSperimentare nuove idee

Page 3: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Cosa FacciamoCosa Facciamo• SviluppoSviluppo• CorsiCorsi• ConferenzeConferenze• SeminariSeminari• MentoringMentoring• Analisi e disegno di progettoAnalisi e disegno di progetto• Auditing su realizzazioni proprie o di terze partiAuditing su realizzazioni proprie o di terze parti• Valutazione skill risorse umaneValutazione skill risorse umane• Non facciamo sviluppo direttamenteNon facciamo sviluppo direttamente

• (Supporto telefonico/via email a contorno di altri servizi: (Supporto telefonico/via email a contorno di altri servizi: mentoring)mentoring)

• Definizione di percorsi di crescita per team di Definizione di percorsi di crescita per team di svilupposviluppo

Page 4: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Html e HttpHtml e HttpLa dura veritàLa dura verità

Page 5: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

ClientClient ServerServer

Richiesta HTTPRichiesta HTTP

default.htmdefault.htm

IIS/ApacheIIS/Apache

Risposta HTTPRisposta HTTP

Request/Response HttpRequest/Response Http

Page 6: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

ClientClient ServerServer

Richiesta HTTPRichiesta HTTP

Active Server PagesActive Server Pagesengineengine

default.aspxdefault.aspx

IISIIS

JScriptJScriptVB / C#VB / C#EsecuzioneEsecuzione

ADO.NETADO.NET

Recupero risultatiRecupero risultati

Risposta HTTPRisposta HTTP

http://www.dcc.com/equipment/catalog_type.asp? http://www.dcc.com/equipment/catalog_type.asp? ProductType=rock+shoesProductType=rock+shoes

ASP: flusso dell’applicazioneASP: flusso dell’applicazione

Page 7: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

StatelessStateless

• Ogni richiesta è a se stanteOgni richiesta è a se stante• Non esistono informazioni di stato in Non esistono informazioni di stato in

HttpHttp• Per ogni richiesta dobbiamo Per ogni richiesta dobbiamo

preoccuparci di inviare il contenutopreoccuparci di inviare il contenuto• Ad esempio riempire i campi di un Ad esempio riempire i campi di un

form con le informazioni digitate form con le informazioni digitate dall’utentedall’utente

Page 8: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

StatelessStateless

• Ripresentare le informazioni digitateRipresentare le informazioni digitate

<INPUT <INPUT

TYPE=“TEXT” TYPE=“TEXT”

NAME=“txtNome” VALUE=<NAME=“txtNome” VALUE=<%=Request.QueryString(“txtNome”)%>%=Request.QueryString(“txtNome”)%>

>>

Page 9: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

ASP.NET Web FormASP.NET Web Form

<FORM action=“NomeRisorsa” <FORM action=“NomeRisorsa” METHOD=“POST”>METHOD=“POST”><INPUT TYPE=“Text” ID=“txtNome” <INPUT TYPE=“Text” ID=“txtNome”

runat=“server”>runat=“server”>

<INPUT TYPE=“Text” ID=“txtCognome”<INPUT TYPE=“Text” ID=“txtCognome”

runst=“server”>runst=“server”>

<INPUT TYPE=“Submit”><INPUT TYPE=“Submit”>

</FORM></FORM>

• I controlli mantengono lo statoI controlli mantengono lo stato

Page 10: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Mantengono lo stato ?Mantengono lo stato ?• I controlli server mantengono le I controlli server mantengono le

proprietà impostate fra round-tripproprietà impostate fra round-trip• Tramite un campo hiddenTramite un campo hidden

• __VIEWSTATE__VIEWSTATE• ProPro

• Meno plumbingMeno plumbing• Meno roundtrip verso i datiMeno roundtrip verso i dati

• ControContro• __VIEWSTATE occupa banda__VIEWSTATE occupa banda• E’ disabilitabileE’ disabilitabile

Page 11: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Demo 10Demo 10

• ViewStateViewState• View SourceView Source

• Modifica attributo al clickModifica attributo al click• Azzera: Cambia colore pulsanteAzzera: Cambia colore pulsante

• Disable su ControlloDisable su Controllo• Non tiene il bgcolorNon tiene il bgcolor

• Disable su PaginaDisable su Pagina• Non tiene il bgcolorNon tiene il bgcolor

Page 12: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Gestione dello statoGestione dello stato

Burocrazia ?Burocrazia ?

Intro/RealIntro/Real

Page 13: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Manage State ?Manage State ?

• Il Web è statelessIl Web è stateless• Mantenere lo stato delle informazioniMantenere lo stato delle informazioni

• ValoriValori• VariabiliVariabili• ProprietàProprietà

• Server-Side per riutilizzarli fra Server-Side per riutilizzarli fra richieste diverserichieste diverse

• Sulla stessa paginaSulla stessa pagina• Sull’intera applicazioneSull’intera applicazione

Page 14: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Manage StateManage State

• Server SideServer Side• Web.ConfigWeb.Config• Application Application • Session (se cookie andrebbe dopo)Session (se cookie andrebbe dopo)• CachingCaching

• Client/Server SideClient/Server Side• Cookie Cookie • Hidden FieldHidden Field• QueryStringQueryString• ViewStateViewState

Page 15: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Web.ConfigWeb.Config

• Può contenere valori CustomPuò contenere valori Custom• Connection StringConnection String• Informazioni Informazioni statichestatiche che prima si che prima si

mettevano in Application o su file esternimettevano in Application o su file esterni

• <appSettings><appSettings>• <add key=“cString” value=“.....” /><add key=“cString” value=“.....” />

• </appSettings></appSettings>

• Nel codiceNel codice• Using/Imports System.ConfigurationUsing/Imports System.Configuration• strConn = Configuration.AppSettings(“DSN”)strConn = Configuration.AppSettings(“DSN”)

Page 16: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Occhio al PublishOcchio al Publish

• Differenziare Test / ProduzioneDifferenziare Test / Produzione• Connessioni al DBConnessioni al DB• Email routingEmail routing• Log Log • Security Security • Etc Etc

• Exclude / Include da VS.NET Exclude / Include da VS.NET

Page 17: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Web.ConfigWeb.Config• Quando viene lettoQuando viene letto

• Alla partenza dell’applicazioneAlla partenza dell’applicazione• Quando è necessario ricompilare Quando è necessario ricompilare

• Dove viene mantenutoDove viene mantenuto• HashTable nell’HttpContextHashTable nell’HttpContext

• Come si accorge dei cambiamentiCome si accorge dei cambiamenti• Viene calcolato l’hash diViene calcolato l’hash di

• CreationTime + LastWriteTime + LenghtCreationTime + LastWriteTime + Lenght

• E memorizzato in un file esterno nella directory di E memorizzato in un file esterno nella directory di compilazionecompilazione

• Ad ogni richiesta viene fatta la verifica del valore Ad ogni richiesta viene fatta la verifica del valore dell’hashdell’hash

• Se non quadra viene rilettoSe non quadra viene riletto

Page 18: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

ApplicationApplication• Classe HttpApplicationStateClasse HttpApplicationState• Oggetto ApplicationOggetto Application• Esposto come proprietà diEsposto come proprietà di

• HttpContext e PageHttpContext e Page• Memoria condivisa per tutta l’applicazioneMemoria condivisa per tutta l’applicazione

• Indipendente dall’utenteIndipendente dall’utente• Accesso tramite Nome/ValoreAccesso tramite Nome/Valore• Non usarla per dati temporaneiNon usarla per dati temporanei

• Difficile impostare una scadenzaDifficile impostare una scadenza

• Da non confondere con la classe Da non confondere con la classe HttpApplication esposta come HttpApplication esposta come ApplicationInstance che rappresenta l’intera ApplicationInstance che rappresenta l’intera applicazione ASP.NET e non un’area di applicazione ASP.NET e non un’area di memoriamemoria

Page 19: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Session Session...Session Session...

• In ASP 1/2/3 le session In ASP 1/2/3 le session • Necessitano del supporto dei cookie sul Necessitano del supporto dei cookie sul

clientclient• Sono single-machine e non adatte a Sono single-machine e non adatte a

configurazione di load-balancingconfigurazione di load-balancing• Consumano molta RAMConsumano molta RAM

• In ASP.NET le sessionIn ASP.NET le session• Possono lavorare come prima oppurePossono lavorare come prima oppure• Non necessitare dei cookieNon necessitare dei cookie• Essere multi-machineEssere multi-machine• Appoggiarsi su DB o su uno State ServerAppoggiarsi su DB o su uno State Server

Page 20: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

SessionSession• Classe HttpSessionStateClasse HttpSessionState• Oggetto SessionOggetto Session• Esposto come proprietà diEsposto come proprietà di

• HttpContext e PageHttpContext e Page• Memoria condivisa per tutta l’applicazioneMemoria condivisa per tutta l’applicazione

• Dipendente dall’utenteDipendente dall’utente• Accesso tramite Nome/ValoreAccesso tramite Nome/Valore• Non usarla per dati temporaneiNon usarla per dati temporanei

• Difficile impostare una scadenzaDifficile impostare una scadenza

• Implementata dal modulo Implementata dal modulo System.Web.SessionState.SessionStateModulSystem.Web.SessionState.SessionStateModulee

Page 21: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Cos’èCos’èBrowserBrowser

ServerServer

BrowserBrowser SessionSession

SessionSession

CookieCookie

CookieCookie

URL SessURL Sess

URL SessURL Sess

ASPNET_WP.EXEASPNET_WP.EXE

HttpRuntimeHttpRuntimeClassClass Modulo XModulo X SessionSession HTTP HandlerHTTP Handler

Pagina1.aspxPagina1.aspx

HttpRuntimeHttpRuntimeClassClass Modulo XModulo X SessionSession HTTP HandlerHTTP Handler

Pagina2.aspxPagina2.aspx

ASP.NET worker thread 1ASP.NET worker thread 1

ASP.NET worker thread 2ASP.NET worker thread 2

Page 22: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Come si usaCome si usa

• Session(“nome”) = ValoreSession(“nome”) = Valore• Response.Write(Session(“nome”))Response.Write(Session(“nome”))• Non occorre definire le varibiliNon occorre definire le varibili

• Come nella vecchia versioneCome nella vecchia versione• Ma occhio a controllarne l’esistenza Ma occhio a controllarne l’esistenza

prima di utilizzarne un valoreprima di utilizzarne un valore• Oppure valorizzare tutte la var nel Oppure valorizzare tutte la var nel

Session_OnStartSession_OnStart

Page 23: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Configurazioni possibiliConfigurazioni possibili<sessionState mode=<sessionState mode="Off|"Off|InprocInproc||

StateServer|SQLServer"StateServer|SQLServer" cookieless=cookieless="true|"true|falsefalse""

timeout=timeout="number of minutes""number of minutes" stateConnectionString=stateConnectionString="tcpip=server:po"tcpip=server:port"rt" sqlConnectionString= sqlConnectionString="sql connection "sql connection string" string" /> />

• Off se non si usaOff se non si usa

Page 24: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Session senza CookieSession senza Cookie<sessionState <sessionState cookieless=“true"cookieless=“true" /> />

• Non necessita di cookie abilitati sul clientNon necessita di cookie abilitati sul client• Il cookie viene copiato nei vari Url linkati Il cookie viene copiato nei vari Url linkati

dalla paginadalla pagina• HttpHttp://xxx.com/3463287462764/pagina.aspx://xxx.com/3463287462764/pagina.aspx

• Utilizzabile in tutte le modalitàUtilizzabile in tutte le modalità• Session.ModeSession.Mode

• Gestiti dal filtro ISAPI ASPNET_FILTER.DLLGestiti dal filtro ISAPI ASPNET_FILTER.DLL

Page 25: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

In-process SessionIn-process Session

<sessionState mode=“InProc” cookieless="true|false" <sessionState mode=“InProc” cookieless="true|false" /> />

• Più velocePiù veloce

• Singolo Server – No Load BalancingSingolo Server – No Load Balancing

• Se ASPNET_WP crasha – Addio SessionSe ASPNET_WP crasha – Addio Session

BrowserBrowser

ASPNET_WPASPNET_WP

BrowserBrowser SessionSession

SessionSession

CookieCookie

CookieCookie

URL SessURL Sess

URL SessURL Sess

Page 26: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

<sessionState mode=“StateServer” cookieless="true|<sessionState mode=“StateServer” cookieless="true|false" false"

stateConnectionString="tcpip=server3:42424" stateConnectionString="tcpip=server3:42424" /> />

• ASPNET_STATE Può girare anche sullo stesso serverASPNET_STATE Può girare anche sullo stesso server

• Se ASPNET_WP crasha – Le Session sopravvivonoSe ASPNET_WP crasha – Le Session sopravvivono

• Più lento di InProcess – Più veloce di SQL Server SessionPiù lento di InProcess – Più veloce di SQL Server Session

• Load BalancingLoad Balancing

• Se crasha ASPNET_STATE – Addio Sessioni di tutti i serverSe crasha ASPNET_STATE – Addio Sessioni di tutti i server

BrowserBrowser

ASPNET_WPASPNET_WP

SERVER 2SERVER 2BrowserBrowserCookieCookie

CookieCookie

URL SessURL Sess

URL SessURL SessASPNET_STATEASPNET_STATE

SERVER 3SERVER 3

SessionSessionBrowserBrowser CookieCookieURL SessURL Sess

ASPNET_WPASPNET_WP

SERVER 1SERVER 1

SessionSession

SessionSession

Page 27: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

<sessionState mode=“SQLServer” cookieless="true|<sessionState mode=“SQLServer” cookieless="true|false" false"

sqlConnectionString=“ConnString” sqlConnectionString=“ConnString” /> />

• SQL può girare anche sullo stesso serverSQL può girare anche sullo stesso server

• Se ASPNET_WP crasha – Le Session sopravvivonoSe ASPNET_WP crasha – Le Session sopravvivono

• Metodo più lento ma più sicuro (se in cluster)Metodo più lento ma più sicuro (se in cluster)

• Load Balancing Load Balancing

BrowserBrowser

ASPNET_WPASPNET_WP

SERVER 2SERVER 2BrowserBrowserCookieCookie

CookieCookie

URL SessURL Sess

URL SessURL Sess

SessionSessionBrowserBrowser CookieCookie

URL SessURL Sess

ASPNET_WPASPNET_WP

SERVER 1SERVER 1

SessionSession

SessionSession

Sql Sql Server oServer o

Sql Sql ClusterCluster

Page 28: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

SQL Server SessionSQL Server Session

• %WinDir%\Microsoft.NET\Framework\vxxxx\%WinDir%\Microsoft.NET\Framework\vxxxx\InstallSQLState.sqlInstallSQLState.sql

• Per creare Database e Stored ProcedurePer creare Database e Stored Procedure• DataBase: ASPStateDataBase: ASPState• SP: Insert, Get, UpdateSP: Insert, Get, Update

• I dati vengono appoggiati al TEMPDBI dati vengono appoggiati al TEMPDB• Al Restart di SQL Server le Session vengono perseAl Restart di SQL Server le Session vengono perse• Possiamo modificare InstallSQLState per creare e Possiamo modificare InstallSQLState per creare e

appoggiare i dati su un altro DBappoggiare i dati su un altro DB

• Nella 1.1 InstallPersistSQLState.sqlNella 1.1 InstallPersistSQLState.sql

Page 29: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Per avere un ideaPer avere un idea

0

200

400

600

800

1000

1200

1400

ASP.NET InProc ASP.NET State Store ASP.NET SQL Store

Req

ues

ts/S

ec (

2P S

erve

r)

Page 30: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

HttpHandler e HttpModuleHttpHandler e HttpModule

ASPNET_WP.EXEASPNET_WP.EXE

HttpRuntimeHttpRuntimeClassClass Modulo 1Modulo 1 Modulo 2Modulo 2 PageHandlerPageHandler

Pagina1.aspxPagina1.aspx

HttpRuntimeHttpRuntimeClassClass Modulo 1Modulo 1 Modulo 2Modulo 2 PageHandlerPageHandler

Pagina2.aspxPagina2.aspx

ASP.NET worker thread 1ASP.NET worker thread 1

ASP.NET worker thread 2ASP.NET worker thread 2

Page 31: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

HttpHandler e HttpModuleHttpHandler e HttpModule

ASPNET_WP.EXEASPNET_WP.EXE

HttpRuntimeHttpRuntimeClassClass AuthentAuthent SessionSession PageHandlerPageHandler

Pagina1.aspxPagina1.aspx

HttpRuntimeHttpRuntimeClassClass AuthentAuthent PageHandlerPageHandler

Pagina2.aspxPagina2.aspx

ASP.NET worker thread 1ASP.NET worker thread 1

ASP.NET worker thread 2ASP.NET worker thread 2

Page 32: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

SessionStateModuleSessionStateModule

• Dopo aver letto la configurazione Dopo aver letto la configurazione relativa alle sessionirelativa alle sessioni

• Si abbona all’evento Si abbona all’evento AcquireRequestState, AcquireRequestState, ReleaseRequestState e EndRequest. ReleaseRequestState e EndRequest.

• Durante la gestione dell’ Durante la gestione dell’ AcquireRequestState recupera il AcquireRequestState recupera il SessionID ed i valori da inserire SessionID ed i valori da inserire nell’oggetto Sessionnell’oggetto Session

Page 33: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Session ConclusioneSession Conclusione• Non abbiamo più i problemi di ASP 3.0Non abbiamo più i problemi di ASP 3.0

• Nessun problema di COM AffinityNessun problema di COM Affinity• Load Balancing consentitoLoad Balancing consentito

• Detto questo, Detto questo, non usatele se non ne avete bisognonon usatele se non ne avete bisogno• Togliere l’HttpModule da Machine.ConfigTogliere l’HttpModule da Machine.Config

• Oppure <page enableSessionState=“false” />Oppure <page enableSessionState=“false” />• Togliere il modulo dal Web.ConfigTogliere il modulo dal Web.Config

• <httpModules><httpModules>• <remove name=“Session” /><remove name=“Session” />

• </httpModules></httpModules>• Oppure <page enableSessionState=“false” />Oppure <page enableSessionState=“false” />

• Disabilitare le session sulle pagine che non le utilizzanoDisabilitare le session sulle pagine che non le utilizzano• @Page EnableSessionState=“false”@Page EnableSessionState=“false”

• Se una pagina legge solamente i valori senza scriverliSe una pagina legge solamente i valori senza scriverli• @Page EnableSessionState=“readonly”@Page EnableSessionState=“readonly”

Page 34: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

CookieCookie

• Namespace System.WebNamespace System.Web• SempliceSemplice

• x = new HttpCookie(name,value)x = new HttpCookie(name,value)• Response.AppendCookie(x)Response.AppendCookie(x)

• If Request.Cookies(name) = Null / nullIf Request.Cookies(name) = Null / null• Stringa = Request.Cookies(name)Stringa = Request.Cookies(name)

• Da non confondere conDa non confondere con• System.Net.CookieSystem.Net.Cookie

Page 35: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Cookie multivalueCookie multivalue

• x = new HttpCookie(name)x = new HttpCookie(name)• x.Values.Add(“nome”, “valore”)x.Values.Add(“nome”, “valore”)• Response.AppendCookie(x)Response.AppendCookie(x)

• If Request.Cookies(name) = Null / nullIf Request.Cookies(name) = Null / null• Stringa = Stringa =

Request.Cookies(name).Values(“nome”)Request.Cookies(name).Values(“nome”)

• Usare il meno possibile gli oggetti ->Usare il meno possibile gli oggetti ->

Page 36: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Passare da variabile localePassare da variabile locale

• x = new HttpCookie(name)x = new HttpCookie(name)• x.Values.Add(“nome”, “valore”)x.Values.Add(“nome”, “valore”)• Response.AppendCookie(x)Response.AppendCookie(x)

• HttpCookie x = HttpCookie x = Request.Cookies(name)Request.Cookies(name)

• If If xx = Null / null = Null / null• Stringa =Stringa =xx.Values(“nome”).Values(“nome”)

Page 37: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Cookie MemberCookie Member• DomainDomain

• Dominio da associare al cookieDominio da associare al cookie• ExpiresExpires

• DateTime per la scadenza.DateTime per la scadenza.• HasKeysHasKeys

• True se ha subkeysTrue se ha subkeys• ItemItem

• Shortcut per HttpCookie.Values[ key ]Shortcut per HttpCookie.Values[ key ]• Per compatibilità con ASP 3.0Per compatibilità con ASP 3.0

• NameName• Legge/Imposta il nome del cookieLegge/Imposta il nome del cookie

• Path Path • Path da associare al cookiePath da associare al cookie

• SecureSecure• Legge/Imposta l’invio sicuro (su Https)Legge/Imposta l’invio sicuro (su Https)

• ValueValue• Valore del cookie single-valueValore del cookie single-value

• ValuesValues• Collection nome/valore contenuto nel cookieCollection nome/valore contenuto nel cookie

Page 38: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Cookie WarningsCookie Warnings

• Usare Https perUsare Https per• Criptare il traffico di username e passwordCriptare il traffico di username e password• Criptare i cookie persistenti su discoCriptare i cookie persistenti su disco

• RedirectFromLoginPage(..., True)RedirectFromLoginPage(..., True)

• Su tutto il sito per evitare che il cookie di login Su tutto il sito per evitare che il cookie di login passi in chiaropassi in chiaro

• Occhio ai tag IMG e HREFOcchio ai tag IMG e HREF• Negare l’accesso Http a tutte le parti protette per Negare l’accesso Http a tutte le parti protette per

essere sicuriessere sicuri

• Se il sito ha una parte protetta Https si deve Se il sito ha una parte protetta Https si deve stare attentistare attenti• Path=qualcosa per inviarlo solo a tali directoryPath=qualcosa per inviarlo solo a tali directory• Altrimenti viene inviato anche per le richieste http Altrimenti viene inviato anche per le richieste http

verso le altre sezioni del sitoverso le altre sezioni del sito

Page 39: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Manage StateManage State

• Per Roundtrip su stessa paginaPer Roundtrip su stessa pagina• Campi HiddenCampi Hidden

• Li conosciamoLi conosciamo

• ViewStateViewState

Page 40: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

VIEWSTATEVIEWSTATE• Proprietà della classe ControlProprietà della classe Control• Contiene le informazioni di stato dei Contiene le informazioni di stato dei

controllicontrolli• Dictionary della classe StateDictionary della classe State• Si trasforma in un campo hiddenSi trasforma in un campo hidden

• Dopo Base64 Encoding Dopo Base64 Encoding • __VIEWSTATE__VIEWSTATE

• Per default è null o emptyPer default è null o empty• I valori possono essere letti e scritti anche I valori possono essere letti e scritti anche

da codiceda codice• ViewState[“xxx”] = “ABC”ViewState[“xxx”] = “ABC”

Page 41: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

ViewState nella sequenza ViewState nella sequenza eventieventi

Page/ Page/ ControlControl

InitInit

VIEWSTATEVIEWSTATE

LoadLoadUpdateUpdate

input fieldinput field

ValidationValidationPage_LoadPage_LoadEvents:Events:

_Change_Change_Click_Click

VIEWSTATEVIEWSTATE

SaveSaveRenderRender DisposeDispose

PreRenderPreRender

Page 42: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

ViewStateViewState

• LoadViewStateLoadViewState• SaveViewStateSaveViewState• Metodi implementati dalla classe baseMetodi implementati dalla classe base• Sono OverridableSono Overridable• Filtri per i valori più comuniFiltri per i valori più comuni

• String, Int, Boolean, Array, ArrayList, String, Int, Boolean, Array, ArrayList, HashTableHashTable

• Possiamo scriverci filtri per nostri tipiPossiamo scriverci filtri per nostri tipi• Che devono essere serializzatiChe devono essere serializzati

Page 43: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

ViewState VS ...ViewState VS ...• HiddenHidden

• E’ un campo hiddenE’ un campo hidden• CookieCookie

• Non necessita di cookie abilitatiNon necessita di cookie abilitati• Il viewstate serve per singola paginaIl viewstate serve per singola pagina

• SessionSession• Le session sono pesanti, soprattutto su DBLe session sono pesanti, soprattutto su DB• Il viewstate serve per singola paginaIl viewstate serve per singola pagina

• ApplicationApplication• Non è specifica per utentiNon è specifica per utenti• Il viewstate serve per singola paginaIl viewstate serve per singola pagina

• CacheCache• Il viewstate serve per singola paginaIl viewstate serve per singola pagina• La Cache è temporaneaLa Cache è temporanea• La vediamo fra un attimoLa vediamo fra un attimo

Page 44: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

ViewState Property/MethodViewState Property/Method• EnableViewStateEnableViewState

• Per pagina o controlloPer pagina o controllo• IsTrackingViewStateIsTrackingViewState

• True mentre il controllo scrive nella StateBagTrue mentre il controllo scrive nella StateBag• ViewStateIgnoreCaseViewStateIgnoreCase

• True = StateBag Case insensitiveTrue = StateBag Case insensitive• HasChildViewStateHasChildViewState• ClearChildViewStateClearChildViewState• Load/SaveLoad/Save• TrackViewStateTrackViewState

• Monitorizza le modifiche al viewstate per Monitorizza le modifiche al viewstate per salvarle nella StateBagsalvarle nella StateBag

Page 45: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

ViewState SicuroViewState Sicuro• DefaultDefault

• Base64 Encoding: Come se fosse in chiaro Base64 Encoding: Come se fosse in chiaro • <pages enableViewStateMac="true“<pages enableViewStateMac="true“• Disabilitabile anche da Machine / Web.ConfigDisabilitabile anche da Machine / Web.Config

• Non da codiceNon da codice

• Controllo integrità Controllo integrità • Machine.Config machineKey per algoritmo di Machine.Config machineKey per algoritmo di

hashhash• SHA1SHA1• MD5MD5

• CriptingCripting• Machine.Config machineKeyMachine.Config machineKey

• 3DES3DES

Page 46: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

CriptingCripting

““VIEWSTATE”VIEWSTATE”

decriptionKeydecriptionKey

““ETATSWEIV”ETATSWEIV”

ResponseResponse

ClientClient

““ETATSWEIV”ETATSWEIV”

RequestRequest

decriptionKeydecriptionKey

““VIEWSTATE”VIEWSTATE”

SaveViewStateSaveViewState ClientClient

LoadViewStateLoadViewState

Page 47: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Controllo IntegritàControllo Integrità

VIEWVIEW validationKeyvalidationKey

VIEWVIEW HashHash

ResponseResponse

ClientClient

VIEWVIEW HashHash

HashHash HashHash

RequestRequest

VIEWVIEW validationKeyvalidationKey

==

HashHash

HashHash

Page 48: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Hash e CriptHash e Cript

• Machine.ConfigMachine.Config• validationKeyvalidationKey

• Per controllo signaturePer controllo signature

• decriptionKeydecriptionKey• Per chiave di criptaggioPer chiave di criptaggio

• Se single-serverSe single-server• autogenerate va benissimoautogenerate va benissimo

• Se Load-BalancingSe Load-Balancing• Devono essere uguali in tutti i Devono essere uguali in tutti i

machine.config dei server in questionemachine.config dei server in questione

Page 49: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

ViewState PerformanceViewState Performance• ServerServer

• Disabilitabile per pagina o controlloDisabilitabile per pagina o controllo• @Page EnableViewState = “false” ...@Page EnableViewState = “false” ...• <asp:TextBox EnableViewState = <asp:TextBox EnableViewState =

“false” ...“false” ...

• Disabilitabile da Web.ConfigDisabilitabile da Web.Config• <pages enableViewState="true“<pages enableViewState="true“

• Disabilitabile da Machine.ConfigDisabilitabile da Machine.Config• <pages enableViewState="true“<pages enableViewState="true“

• Da CodiceDa Codice• Page.EnableViewState = falsePage.EnableViewState = false• Control.EnableViewState = falseControl.EnableViewState = false

Page 50: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

ViewState PerformanceViewState Performance

• Ancora ServerAncora Server• Usare solo i 6 filtri di defaultUsare solo i 6 filtri di default

• Oggetti custom serializzabiliOggetti custom serializzabili• Molto alto il costo di serializzazioneMolto alto il costo di serializzazione

• Non consuma risorse server (RAM, DISCO)Non consuma risorse server (RAM, DISCO)• Non criptarlo per maggiori performanceNon criptarlo per maggiori performance

• ClientClient• E’ un campo hiddenE’ un campo hidden• Se troppo grande lentezza nel passaggio dei datiSe troppo grande lentezza nel passaggio dei dati• Tracing per controllare il peso dei singoli Tracing per controllare il peso dei singoli

controllicontrolli

Page 51: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

CachingCaching

Occhio alla pronunciaOcchio alla pronuncia

IntroIntro

Page 52: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

CachingCaching

• Il miglior modo di ottimizzare il Il miglior modo di ottimizzare il codice ècodice è

• Non eseguirlo !!!Non eseguirlo !!!• Se i dati non cambiano in un arco di Se i dati non cambiano in un arco di

tempo perchè rieseguire le query ?tempo perchè rieseguire le query ?• Il codice statico è molto più veloce Il codice statico è molto più veloce

del codice dinamicodel codice dinamico• Torniamo a FrontPage Torniamo a FrontPage

• Mai ! Mai ! magari a DreamWeaver magari a DreamWeaver

Page 53: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Caching di Pagine e ControlliCaching di Pagine e Controlli• Implementato da Implementato da

System.Web.Caching.OutputCacheMSystem.Web.Caching.OutputCacheModuleodule

ASPNET_WP.EXEASPNET_WP.EXE

HttpRuntimeHttpRuntimeClassClass OutputCacheOutputCache SessionSession HTTP HandlerHTTP Handler

Pagina1.aspxPagina1.aspx

HttpRuntimeHttpRuntimeClassClass OutputCacheOutputCache HTTP HandlerHTTP Handler

Pagina2.aspxPagina2.aspx

ASP.NET worker thread 1ASP.NET worker thread 1

ASP.NET worker thread 2ASP.NET worker thread 2

CacheCache

Page 54: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Page Output CachingPage Output Caching

• La pagina viene eseguita la prima voltaLa pagina viene eseguita la prima volta• Viene cachata Viene cachata • E recuperata dalla cache per le richieste E recuperata dalla cache per le richieste

successivesuccessive

• Direttiva di cache per la paginaDirettiva di cache per la pagina• <%@ OutputCache Duration=“10” <%@ OutputCache Duration=“10”

VaryByParams=“none” %>VaryByParams=“none” %>

• Oppure da codiceOppure da codice• Response.Cache.SetExpires(DateTime.NoResponse.Cache.SetExpires(DateTime.No

w.AddSeconds(10))w.AddSeconds(10))

Page 55: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Cache LocationCache Location

• <%@OutputCache Location= “ “ %><%@OutputCache Location= “ “ %>• ServerServer• ClientClient• DownstreamDownstream• PublicPublic• NoneNone

• Da codiceDa codice• Response.Cache.SetCacheabilityResponse.Cache.SetCacheability

• HttpCacheability.ServerHttpCacheability.Server• HttpCacheability.ClientHttpCacheability.Client• ........

Page 56: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Direttiva OutputCacheDirettiva OutputCache

• La pagina potrebbe essere diversa in La pagina potrebbe essere diversa in base al QueryString o alla POSTbase al QueryString o alla POST

• VaryByParamVaryByParam• Cacha n copie della pagina in base ai Cacha n copie della pagina in base ai

parametri HTTP GET / POSTparametri HTTP GET / POST• Indicare i parametri da considerare separati Indicare i parametri da considerare separati

da “;”da “;”• Supporta * (per tutti i parametri)Supporta * (per tutti i parametri)• Esempio Esempio VaryByParam=“TipoCorso; SedeCorso”VaryByParam=“TipoCorso; SedeCorso”

• Parametro obbligatorioParametro obbligatorio• Impostarlo a ‘none’Impostarlo a ‘none’

Page 57: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Oppure OutputCacheOppure OutputCache

• VaryByHeaderVaryByHeader• Cache le pagine in base agli header HTTPCache le pagine in base agli header HTTP• Sempre stringa con “;”Sempre stringa con “;”• Esempio LOGON_USEREsempio LOGON_USER

• VaryByCustomVaryByCustom• Su tipo di browser – ‘Browser’Su tipo di browser – ‘Browser’• EstensibileEstensibile• Sempre stringa “;”Sempre stringa “;”

Page 58: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

VaryByCustom EsempioVaryByCustom Esempio• VaryByCustom=“Preferenze”VaryByCustom=“Preferenze”• VBVBPublic Overrides Function GetVaryByCustomString(context as HttpContext, arg as Public Overrides Function GetVaryByCustomString(context as HttpContext, arg as

String) as StringString) as String

Select Case argSelect Case arg

Case “Preferenze”Case “Preferenze”

Return(“Preferenze=“ & Request.Cookies(“Pref”)Return(“Preferenze=“ & Request.Cookies(“Pref”)

Case ...Case ...

End SelectEnd Select

End FunctionEnd Function

• C#C#public override string GetVaryByCustomString(HttpContext context, string arg ) {public override string GetVaryByCustomString(HttpContext context, string arg ) {

switch (arg) {switch (arg) {

case “Preferenze”case “Preferenze”

Return(“Preferenze=“ & Request.Cookies(“Pref”);Return(“Preferenze=“ & Request.Cookies(“Pref”);

case ...case ...

}}

} }

Page 59: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Partial CachingPartial Caching

• Non è detto che si voglia sempre Non è detto che si voglia sempre cachare tutta la paginacachare tutta la pagina

• Sensato cachare solo le parti comuniSensato cachare solo le parti comuni• Partial Page CachingPartial Page Caching

• Consente di cachare User ControlConsente di cachare User Control• Ognuno con criteri diversiOgnuno con criteri diversi• La sintassi è identicaLa sintassi è identica• Attributo VaryByControlAttributo VaryByControl• Estensibile con ProprietàEstensibile con Proprietà

Page 60: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Caching APICaching API

Occhio alla pronunciaOcchio alla pronuncia

IntroIntro

Page 61: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Cache APICache API• Classe CacheClasse Cache• Namespace Namespace System.Web.CachingSystem.Web.Caching• Oggetto CacheOggetto Cache

• Esposto da Page.ResponseEsposto da Page.Response

• Memoria condivisa per tutta l’applicazioneMemoria condivisa per tutta l’applicazione• Indipendente dall’utenteIndipendente dall’utente• Accesso tramite Nome/ValoreAccesso tramite Nome/Valore• Usarla per dati temporaneiUsarla per dati temporanei• Gli item usati “poco” vengono rimossiGli item usati “poco” vengono rimossi

• Supporta la notifica di rimozione tramite il Supporta la notifica di rimozione tramite il Delegate CacheItemRemovedCallBackDelegate CacheItemRemovedCallBack

Page 62: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Un esempioUn esempio• Cache.Add o Cache.InsertCache.Add o Cache.Insert

((NomeNome

ValoreValore

DependencyDependency

TimeTime

TimeSpanTimeSpan

PriorityPriority

PriorityDecayPriorityDecay

CallBackCallBack

))

Page 63: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Cache DependencyCache Dependency

• Dependency da fileDependency da file• New CacheDependencyNew CacheDependency

• Da File/Directory (Array di File o Directory)Da File/Directory (Array di File o Directory)• Iniziare ad un DateTime specificoIniziare ad un DateTime specifico

• Da un altro elemento in cacheDa un altro elemento in cache• Da un array di elementi in cacheDa un array di elementi in cache• Da un’altra dependencyDa un’altra dependency

• Ms-help://MS.NETFrameworkSDK/cpreMs-help://MS.NETFrameworkSDK/cpref/html/frlrfSystemWebCachingCachef/html/frlrfSystemWebCachingCacheDependencyClassctorTopic.htmDependencyClassctorTopic.htm

Page 64: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Cache RemovedCallBackCache RemovedCallBack

private static CacheItemRemovedCallback onRimoz =null;private static CacheItemRemovedCallback onRimoz =null;

onRimoz = new onRimoz = new CacheItemRemovedCallBack(this.RemovedCallBack);CacheItemRemovedCallBack(this.RemovedCallBack);

Cache.Insert(“xx”,”xx”, null, d, t, null, null, onRimoz);Cache.Insert(“xx”,”xx”, null, d, t, null, null, onRimoz);

public void RemovedCallback(String strX, Object O, public void RemovedCallback(String strX, Object O, CacheItemRemovedReason R) CacheItemRemovedReason R)

{{

// Codice per ricreare l’elemento// Codice per ricreare l’elemento

Accesso al DB Accesso al DB

Cache.Insert(.....)Cache.Insert(.....)

}}

Page 65: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

Altre InformazioniAltre Informazioni

• Dove posso ottenere maggiori Dove posso ottenere maggiori informazioniinformazioni• www.DevLeap.itwww.DevLeap.it• www.asp.netwww.asp.net

• Developer resourcesDeveloper resources• Microsoft Visual Studio.NETMicrosoft Visual Studio.NET• Microsoft .NET Framework SDKMicrosoft .NET Framework SDK• Microsoft Developer NetworkMicrosoft Developer Network

Page 66: Http:// ASP.NET Managing State Roberto Brunetti Roberto@DevLeap.it Blog: blogs.devleap.com/rob.rss.

http://www.DevLeap.ithttp://www.DevLeap.it

ASP.NET Managing StateASP.NET Managing State

I vostri feedback sono importantiI vostri feedback sono importanti•ScrivetemiScrivetemi

Grazie della partecipazione– A presto

[email protected]


Recommended