Upload
rudolf-joseph
View
218
Download
0
Embed Size (px)
Citation preview
Maintaining StateMaintaining State
Tools:Tools:1.1. Cookies Cookies
2.2. ViewstateViewstate
3.3. SessionSession
4.4. CacheCache
1. Cookies1. Cookies Small text files stored on user’s computerSmall text files stored on user’s computer
Useful for storing:Useful for storing: Date of last visitDate of last visit Unique user identifierUnique user identifier PreferencesPreferences etc. etc.
LimitationsLimitations Not secure – user can view, modify, deleteNot secure – user can view, modify, delete User can disableUser can disable
1. Cookies1. Cookies Write:Write:
Single value per cookie:Single value per cookie:• Response.Cookies[“Name”].Value = “Bart”;Response.Cookies[“Name”].Value = “Bart”;
Multiple values per cookieMultiple values per cookie• Response.Cookies[“Name”][“First”] = “Bart”;Response.Cookies[“Name”][“First”] = “Bart”;• Response.Cookies[“Name”][“Last”] = “Simpson”;Response.Cookies[“Name”][“Last”] = “Simpson”;
•
Read Read Request.Cookies[“Name”].Value;Request.Cookies[“Name”].Value; Request.Cookies[“Name”][“First”].Value;Request.Cookies[“Name”][“First”].Value;
1. Cookies1. Cookies
Expiration:Expiration: Default: when browser is closedDefault: when browser is closed
Response.Cookies[“CookieName”].Expires = Response.Cookies[“CookieName”].Expires = DateTime.Now.AddDays(180);DateTime.Now.AddDays(180);
Delete Cookie: set expiration to past (-1)Delete Cookie: set expiration to past (-1)
1. Cookies1. Cookies
Testing for cookieTesting for cookie Attempt to read a cookie that is not present:Attempt to read a cookie that is not present:
Error: Object reference not set to an instance of an object
Solution: Solution: If (Request.Cookies[“Name”] != null) {If (Request.Cookies[“Name”] != null) { //safe to read cookie //safe to read cookie
name = Request.Cookies[“Name”] .Value;name = Request.Cookies[“Name”] .Value;}}
1. Cookies1. Cookies
Benefits:Benefits: Persist between sessionsPersist between sessions Keep track of usernames, last visit, etc.Keep track of usernames, last visit, etc. Easy to useEasy to use
Drawbacks:Drawbacks: Client can blockClient can block Not secureNot secure
2. Viewstate2. Viewstate
Data in web controls automatically storedData in web controls automatically stored Encoded in hidden form fieldEncoded in hidden form field
May add to viewstate programmaticallyMay add to viewstate programmatically ViewState[“UserID”] = “333”;ViewState[“UserID”] = “333”;
Retrieve with same syntaxRetrieve with same syntax Returned datatype is objectReturned datatype is object
• Must convert Must convert int intUserID = Convert.ToInt32(ViewState["UserID"]);int intUserID = Convert.ToInt32(ViewState["UserID"]);
ViewStateViewState Benefits:Benefits:
Very convenientVery convenient Can access data even when controls hiddenCan access data even when controls hidden
DrawbackDrawback Difficult to transfer between pagesDifficult to transfer between pages Does not persist between sessionsDoes not persist between sessions
3. Sessions3. Sessions Data stored on serverData stored on server Unique to each userUnique to each user Uses cookie to associate with userUses cookie to associate with user
User must have cookies enabledUser must have cookies enabled
Create:Create: Session[“LastName”] = “Simpson”;Session[“LastName”] = “Simpson”;
DeleteDelete Session.Abandon; – Deletes the sessionSession.Abandon; – Deletes the session Session.Remove[“LastName”]; – removes itemsSession.Remove[“LastName”]; – removes items
SessionsSessions ExpirationExpiration
Default: 20 minutesDefault: 20 minutes Session.Timeout = 60;Session.Timeout = 60;
BenefitsBenefits SecureSecure
• Client cannot view, edit, deleteClient cannot view, edit, delete Automatic timeoutAutomatic timeout
DrawbacksDrawbacks Do not persistDo not persist Require cookiesRequire cookies Use server resourcesUse server resources
4. Cache4. Cache
Stored on serverStored on server ApplicationApplication
Often used to cache dataOften used to cache data Example: Example: XML Music
Store any type of data / objectStore any type of data / object Stored as type “object”Stored as type “object” Recast when retrievedRecast when retrieved
CacheCache
Add item to cache:Add item to cache: Cache.Insert(“key”, object, dependency, Cache.Insert(“key”, object, dependency,
absoluteExpiration, slidingExpiration) absoluteExpiration, slidingExpiration)
Example:Example: Cache.Insert(“cat30”, “apples”, null,Cache.Insert(“cat30”, “apples”, null,
DateTime.Now.AddSeconds(60), DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration)Cache.NoSlidingExpiration)
CacheCache
Retrieve:Retrieve:If (Cache[“cat30”] != null) {If (Cache[“cat30”] != null) {
string fruit = (string) Cache[“cat30”];string fruit = (string) Cache[“cat30”];
}}
CacheCache
Benefits:Benefits: SecureSecure Many expiration optionsMany expiration options Store any objectStore any object
Drawbacks:Drawbacks: ????
When to use each:When to use each:Cookies • Need data to persist across sessions
• Security not important
Viewstate • Data associated with page• Similar to hidden form field
Session • Secure• Associated with each user session
Cache • Secure• Share data across sessions• Control expiration
Example: output (source)