SlideShare a Scribd company logo
State Management




    http://www.rajpatsystems.com
View State
• One of the most common ways to store information is in
  view state.
• View state uses a hidden field that ASP.NET automatically
  inserts in the final, rendered HTML of a web page. It’s a
  perfect place to store information that’s used for multiple
  postbacks in a single web page.
• Web controls store most of their property values in view
  state, provided the control’s EnableViewState property is
  set to true (which is the default).
• View state isn’t limited to web controls. Your web page
  code can add bits of information directly to the view state
  of the containing page and retrieve it later after the page is
  posted back.
• The type of information you can store includes simple data
  types and your own custom objects.
                        http://www.rajpatsystems.com
•   The ViewState property of the page provides the current view state
    information. This property is an instance of the StateBag collection class.
    The StateBag is a dictionary collection, which means every item is stored
    in a separate “slot” using a unique string name.

// The this keyword refers to the current Page object. It's optional.
this.ViewState["Counter"] = 1;

•   This places the value 1 (or rather, an integer that contains the value 1) into
    the ViewState collection and gives it the descriptive name Counter. If
    currently no item has the name Counter, a new item will be added
    automatically. If an item is already stored under the name Counter, it will
    be replaced.
•   When retrieving a value, you use the key name. You also need to cast the
    retrieved value to the appropriate data type using the casting syntax.
•   This extra step is required because the ViewState collection stores all
    items as basic objects, which allows it to handle many different data types.

int counter;
counter = (int)this.ViewState["Counter"];
                                http://www.rajpatsystems.com
Making View State Secure
• <input    type="hidden" name="__VIEWSTATE"
  id="__VIEWSTATE”
  value="dDw3NDg2NTI5MDg7Oz4=" />
• The view state information is simply patched
  together in memory and converted to a
  Base64 string (which is a special type of string
  that’s always acceptable in an HTML
  document because it doesn’t include any
  extended characters).
                  http://www.rajpatsystems.com
Tamperproof View State
• If you want to make view state more secure, you have two choices.
• Use a hash code:
   – A hash code is sometimes described as a cryptographically strong
     checksum. The idea is that ASP.NET examines all the data in view state,
     just before it renders the final page.
   – It runs this data through a hashing algorithm (with the help of a secret
     key value). The hashing algorithm creates a short segment of data,
     which is the hash code.
   – This code is then added at the end of the view state data, in the final
     HTML that’s sent to the browser.
   – When the page is posted back, ASP.NET examines the view state data
     and recalculates the hash code using the same process. It then checks
     whether the checksum it calculated matches the hash code that is
     stored in the view state for the page.
   – If a malicious user changes part of the view state data, ASP.NET will
     end up with a new hash code that doesn’t match. At this point, it will
     reject the postback completely

                            http://www.rajpatsystems.com
• Hash codes are actually enabled by default, so if
  you want this functionality, you don’t need to
  take any extra steps.
• Hash codes are actually enabled by default, so if
  you want this functionality, you don’t need to
  take any extra steps.




                   http://www.rajpatsystems.com
Private View State
• If your view state contains some information you want to keep
  secret, you can enable view state encryption.
• You can turn on encryption for an individual page using the
  ViewStateEncryptionMode property of the Page directive.

<%@Page ViewStateEncryptionMode="Always" %>
Or you can set the same attribute in a configuration file:
<configuration>
<system.web>
<pages viewStateEncryptionMode="Always" />
...
</system.web>
</configuration>


                           http://www.rajpatsystems.com
• Either way, this enforces encryption. You have three choices for
  your view state encryption setting—always encrypt (Always), never
  encrypt (Never), or encrypt only if a control specifically requests it
  (Auto).
• The default is Auto, which means that the page won’t encrypt its
  view state unless a control on that page specifically requests it.
  (Technically, a control makes this request by calling the
  age.RegisterRequiresViewStateEncryption() method.)
• If no control calls this method to indicate it has sensitive
  information, the view state is not encrypted, thereby saving the
  encryption overhead.
• On the other hand, a control doesn’t have absolute power—if it
  calls   Page.RegisterRequiresViewStateEncryption()         and    the
  encryption mode is Never, the view state won’t be encrypted.
• Tip: Don’t encrypt view state data if you don’t need to do so. The
  encryption will impose a performance penalty, because the web
  server needs to perform the encryption and decryption with each
  postback.

                           http://www.rajpatsystems.com
Retaining Member Variables
•   The basic principle is to save all member variables to view state when the
    Page.PreRender event occurs and retrieve them when the Page.Load
    event occurs.
•   Remember, the Load event happens every time the page is created.
•   In the case of a postback, the Load event occurs first, followed by any
    other control events.
•   The logic in the Load and PreRender event handlers allows the rest of your
    code to work more or less as it would in a desktop application.
•   However, you must be careful not to store needless amounts of
    information when using this technique. If you store unnecessary
    information in view state, it will enlarge the size of the final page output
    and can thus slow down page transmission times.
•   Another disadvantage with this approach is that it hides the lowlevel
    reality that every piece of data must be explicitly saved and restored.
    When you hide this reality, it’s more likely that you’ll forget to respect it
    and design for it.


                               http://www.rajpatsystems.com
Storing Custom Objects
• You can store your own objects in view state just
  as easily as you store numeric and string types.
• To store an item in view state, ASP.NET must be
  able to convert it into a stream of bytes so that it
  can be added to the hidden input field in the
  page.
   – This process is called serialization. If your objects
     aren’t serializable (and by default they’re not), you’ll
     receive an error message when you attempt to place
     them in view state.

                      http://www.rajpatsystems.com
[Serializable]
public class Customer
{
    private string firstName;
    public string FirstName
    {
         get { return firstName; }
         set { firstName = value; }
    }
    private string lastName;
    public string LastName
    {
         get { return lastName; }
         set { lastName = value; }
    }
    public Customer(string firstName, string lastName)
    {
         FirstName = firstName;
         LastName = lastName;
    }
}


                                      http://www.rajpatsystems.com
• Because the Customer class is marked as serializable, it
   can be stored in view state:
// Store a customer in view state.
Customer cust = new Customer("Marsala", "Simons");
ViewState["CurrentCustomer"] = cust;
• Remember, when using custom objects, you’ll need to
   cast your data when you retrieve it from view state.
// Retrieve a customer from view state.
Customer cust;
cust = (Customer)ViewState["CurrentCustomer"];


                      http://www.rajpatsystems.com
Transferring Information Between
                  Pages
                     Cross-page posting.
                        Query string.
• Cross-Page Posting:
   – A cross-page postback is a technique that extends the postback
     mechanism.
   – The infrastructure that supports cross-page postbacks is a new
     property named PostBackUrl, which is defined by the
     IButtonControl interface and turns up in button controls such as
     ImageButton, LinkButton, and Button. To use cross-posting, you
     simply set PostBackUrl to the name of another web form.
   – When the user clicks the button, the page will be posted to that
     new URL with the values from all the input controls on the
     current page.


                         http://www.rajpatsystems.com
The Query String
• Pass information using a query string in the URL. This approach is
  commonly found in search engines. For example, if you perform a
  search on the Google website, you’ll be redirected to a new URL that
  incorporates your search parameters.
• Here’s an example:
   – http://www.google.ca/search?q=organic+gardening
• The advantage of the query string is that it’s lightweight and doesn’t
  exert any kind of burden on the server. However, it also has several
  limitations:
   – Information is limited to simple strings, which must contain URL-legal
     characters.
   – Information is clearly visible to the user and to anyone else who cares to
     eavesdrop on the Internet.
   – The enterprising user might decide to modify the query string and supply
     new values, which your program won’t expect and can’t protect against.
   – Many browsers impose a limit on the length of a URL (usually from 1KB to
     2KB). For that reason, you can’t place a large amount of information in
     the query string and still be assured of compatibility with most browsers.
                          http://www.rajpatsystems.com
http://www.rajpatsystems.com
URL Encoding
• With URL encoding, special characters are replaced by escaped
    character sequences starting with the percent sign (%), followed by
    a two-digit hexadecimal representation. For example, the &
    character becomes %26. The only exception is the space character,
    which can be represented as the character sequence %20 or the +
    sign.
• To performURL encoding, you use the UrlEncode() and UrlDecode()
    methods of the HttpServerUtility class.
string url = "QueryStringRecipient.aspx?";
url += "Item=" + Server.UrlEncode(lstItems.SelectedItem.Text) + "&";
url += "Mode=" _ chkDetails.Checked.ToString();
Response.Redirect(url);
• You can use the UrlDecode() method to return a URL-encoded
    string to its initial value.


                          http://www.rajpatsystems.com
Cookies
• Cookies are small files that are created on the client’s hard drive (or,
  if they’re temporary, in the web browser’s memory).
• They work transparently without the user being aware that
  information needs to be stored.
• Can be easily used by any page in your application and even be
  retained between visits, which allows for long-term storage.
• They suffer from some of the same drawbacks that affect query
  strings—namely, they’re limited to simple string information, and
  they’re easily accessible and readable if the user finds and opens
  the corresponding file. These factors make them a poor choice for
  complex or private information or large amounts of data.
• Before you can use cookies, you should import the System.Net
  namespace so you can easily work with the appropriate types



                            http://www.rajpatsystems.com
Set And Remove a Cookie
•    Both the Request and Response objects (which are provided through Page properties) provide a
     Cookies collection.
• The important trick to remember is that you retrieve cookies from the Request object, and you set
     cookies using the Response object.
• To set a cookie, just create a new HttpCookie object. You can then fill it with string information
     (using the familiar dictionary pattern) and attach it to the current web response.
// Create the cookie object.
HttpCookie cookie = new HttpCookie("Preferences");
// Set a value in it.
cookie["LanguagePref"] = "English";
// Add another value.
cookie["Country"] = "US";
// Add it to the current web response.
Response.Cookies.Add(cookie);
• A cookie added in this way will persist until the user closes the browser and will be sent with every
     request. To create a longer-lived cookie, you can set an expiration date.
// This cookie lives for one year.
cookie.Expires = DateTime.Now.AddYears(1);




                                       http://www.rajpatsystems.com
• You retrieve cookies by cookie name using the Request.Cookies
    collection.
HttpCookie cookie = Request.Cookies["Preferences"];
// Check to see whether a cookie was found with this name.
// This is a good precaution to take,
// because the user could disable cookies,
// in which case the cookie will not exist.
string language;
if (cookie != null)
{
language = cookie["LanguagePref"];
}
• The only way to remove a cookie is by replacing it with a cookie
    that has an expiration date that has already passed.
HttpCookie cookie = new HttpCookie("LanguagePref");
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);

                         http://www.rajpatsystems.com
Session State
• It allows you to store any type of data in memory on
  the server.
• The information is protected, because it is never
  transmitted to the client, and it’s uniquely bound to a
  specific session.
• Every client that accesses the application has a
  different session and a distinct collection of
  information.
• Session state is ideal for storing information such as the
  items in the current user’s shopping basket when the
  user browses from one page to another.

                      http://www.rajpatsystems.com
Session Tracking
• ASP.NET tracks each session using a unique 120-bit
  identifier.
• ASP.NET uses a proprietary algorithm to generate this
  value, thereby guaranteeing (statistically speaking) that the
  number is unique and it’s random enough that a malicious
  user can’t reverse-engineer or “guess” what session ID a
  given client will be using. This ID is the only piece of
  session-related information that is transmitted between
  the web server and the client.
• When the client presents the session ID, ASP.NET looks up
  the corresponding session, retrieves the objects you stored
  previously, and places them into a special collection so they
  can be accessed in your code. This process takes place
  automatically.
                       http://www.rajpatsystems.com
• For this system to work, the client must present the appropriate
  session ID with each request. You can accomplish this in two ways:
    – Using cookies: In this case, the session ID is transmitted in a special
      cookie (named ASP.NET_SessionId), which ASP.NET creates
      automatically when the session collection is used. This is the default,
      and it’s also the same approach that was used in earlier versions of
      ASP.
    – Using modified URLs: In this case, the session ID is transmitted in a
      specially modified (or managed) URL. This allows you to create
      applications that use session state with clients that don’t support
      cookies.
• Session state doesn’t come for free. Though it solves many of the
  problems associated with other forms of state management, it
  forces the server to store additional information in
• memory. This extra memory requirement, even if it is small, can
  quickly grow to performancedestroying levels as hundreds or
  thousands of clients access the site.
• In other words, you must think through any use of session state. A
  careless use of session state is one of the most common reasons
  that a web application can’t scale to serve a large number of clients.

                            http://www.rajpatsystems.com
Using Session State
• You can interact with session state using the
  System.Web.SessionState.HttpSessionState class, which
  is provided in an ASP.NET web page as the built-in
  Session object. The syntax for adding items to the
  collection and retrieving them is basically the same as
  for adding items to a page’s view state.
• For example, you might store a DataSet in session
  memory like this:
Session["InfoDataSet"] = dsInfo;
• You can then retrieve it with an appropriate conversion
  operation:
dsInfo = (DataSet)Session["InfoDataSet"];

                     http://www.rajpatsystems.com
• Session state is global to your entire application for the
  current user. However, session state can be lost in several
  ways:
• If the user closes and restarts the browser.
• If the user accesses the same page through a different
  browser window, although the session will still exist if a
  web page is accessed through the original browser window.
  Browsers differ on how they handle this situation.
• If the session times out due to inactivity.
• If your web page code ends the session by calling the
  Session.Abandon() method.
• In the first two cases, the session actually remains in
  memory on the web server, because ASP.NET has no idea
  that the client has closed the browser or changed windows.
  The session will linger in memory, remaining inaccessible,
  until it eventually expires.


                       http://www.rajpatsystems.com
http://www.rajpatsystems.com
It’s also a good practice to add a few session-
   friendly features in your application. For
   example, you could add a logout button to the
   page that automatically cancels a session
   using the Session.Abandon() method. This
   way, the user will be encouraged to terminate
   the session rather than just close the browser
   window, and the server memory will be
   reclaimed faster.

                  http://www.rajpatsystems.com

More Related Content

PPTX
State Management in ASP.NET
PPTX
Ch05 state management
PPTX
State management
PPTX
Chapter 8 part1
PPT
State management
PPT
jQuery Ajax
PPTX
Search engine optimization (seo) from Endeca & ATG
PPTX
Ajax and Jquery
State Management in ASP.NET
Ch05 state management
State management
Chapter 8 part1
State management
jQuery Ajax
Search engine optimization (seo) from Endeca & ATG
Ajax and Jquery

What's hot (18)

PDF
Data Binding
DOCX
Managing states
PPTX
State management
PPT
ASP.NET 12 - State Management
PPTX
PPTX
MySQL Performance Tips & Best Practices
PPTX
JSON and XML
PPTX
4. jsp
PPTX
Ajax
PPTX
What is Ajax technology?
PPT
Hibernate jj
PPTX
Ch06 ado.net fundamentals
PDF
Data Binding in Silverlight
PPT
Ajax Ppt
PPTX
Grid View Control CS
PPT
Mashup
PPTX
HTML 5
Data Binding
Managing states
State management
ASP.NET 12 - State Management
MySQL Performance Tips & Best Practices
JSON and XML
4. jsp
Ajax
What is Ajax technology?
Hibernate jj
Ch06 ado.net fundamentals
Data Binding in Silverlight
Ajax Ppt
Grid View Control CS
Mashup
HTML 5
Ad

Viewers also liked (6)

PDF
BIA 658 – Social Network Analysis - Final report Kanad Chatterjee
PDF
User Manual Tobii X120
PPTX
PDF
Social data & privacy seminar v1.0
PDF
Managing it security and data privacy security
PDF
Marketing analytics alpesh doshi social network analysis - using social gra...
BIA 658 – Social Network Analysis - Final report Kanad Chatterjee
User Manual Tobii X120
Social data & privacy seminar v1.0
Managing it security and data privacy security
Marketing analytics alpesh doshi social network analysis - using social gra...
Ad

Similar to State management 1 (20)

PPTX
State Management.pptx
PPTX
Introduction to ASP.Net Viewstate
PDF
Asp.net state management
PPTX
State management
PPTX
Managing state in asp.net
DOCX
State management
DOC
State management in asp
PPT
StateManagement in ASP.Net.ppt
PPS
05 asp.net session07
PPSX
05 asp.net session07
PPTX
81.pptx ajx fyjc semester paper 2 parrtens
PPTX
ASP.NET Lecture 2
PPT
Session viii(state mngtclient)
PPSX
ASP.Net Presentation Part3
PPTX
ASP.NET View State - Security Issues
PDF
state management asp.net
DOCX
High performance coding practices code project
PPTX
PPS
05 asp.net session07
PPTX
State Management.pptx
Introduction to ASP.Net Viewstate
Asp.net state management
State management
Managing state in asp.net
State management
State management in asp
StateManagement in ASP.Net.ppt
05 asp.net session07
05 asp.net session07
81.pptx ajx fyjc semester paper 2 parrtens
ASP.NET Lecture 2
Session viii(state mngtclient)
ASP.Net Presentation Part3
ASP.NET View State - Security Issues
state management asp.net
High performance coding practices code project
05 asp.net session07

Recently uploaded (20)

PPTX
Digestion and Absorption of Carbohydrates, Proteina and Fats
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Hazard Identification & Risk Assessment .pdf
PPTX
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
PPTX
Cell Types and Its function , kingdom of life
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PPTX
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
PDF
Classroom Observation Tools for Teachers
PPTX
History, Philosophy and sociology of education (1).pptx
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PDF
Trump Administration's workforce development strategy
PDF
What if we spent less time fighting change, and more time building what’s rig...
PDF
1_English_Language_Set_2.pdf probationary
PDF
Computing-Curriculum for Schools in Ghana
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
UNIT III MENTAL HEALTH NURSING ASSESSMENT
Digestion and Absorption of Carbohydrates, Proteina and Fats
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Supply Chain Operations Speaking Notes -ICLT Program
Hazard Identification & Risk Assessment .pdf
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
Cell Types and Its function , kingdom of life
A powerpoint presentation on the Revised K-10 Science Shaping Paper
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
Classroom Observation Tools for Teachers
History, Philosophy and sociology of education (1).pptx
Practical Manual AGRO-233 Principles and Practices of Natural Farming
Trump Administration's workforce development strategy
What if we spent less time fighting change, and more time building what’s rig...
1_English_Language_Set_2.pdf probationary
Computing-Curriculum for Schools in Ghana
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Final Presentation General Medicine 03-08-2024.pptx
UNIT III MENTAL HEALTH NURSING ASSESSMENT

State management 1

  • 1. State Management http://www.rajpatsystems.com
  • 2. View State • One of the most common ways to store information is in view state. • View state uses a hidden field that ASP.NET automatically inserts in the final, rendered HTML of a web page. It’s a perfect place to store information that’s used for multiple postbacks in a single web page. • Web controls store most of their property values in view state, provided the control’s EnableViewState property is set to true (which is the default). • View state isn’t limited to web controls. Your web page code can add bits of information directly to the view state of the containing page and retrieve it later after the page is posted back. • The type of information you can store includes simple data types and your own custom objects. http://www.rajpatsystems.com
  • 3. The ViewState property of the page provides the current view state information. This property is an instance of the StateBag collection class. The StateBag is a dictionary collection, which means every item is stored in a separate “slot” using a unique string name. // The this keyword refers to the current Page object. It's optional. this.ViewState["Counter"] = 1; • This places the value 1 (or rather, an integer that contains the value 1) into the ViewState collection and gives it the descriptive name Counter. If currently no item has the name Counter, a new item will be added automatically. If an item is already stored under the name Counter, it will be replaced. • When retrieving a value, you use the key name. You also need to cast the retrieved value to the appropriate data type using the casting syntax. • This extra step is required because the ViewState collection stores all items as basic objects, which allows it to handle many different data types. int counter; counter = (int)this.ViewState["Counter"]; http://www.rajpatsystems.com
  • 4. Making View State Secure • <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE” value="dDw3NDg2NTI5MDg7Oz4=" /> • The view state information is simply patched together in memory and converted to a Base64 string (which is a special type of string that’s always acceptable in an HTML document because it doesn’t include any extended characters). http://www.rajpatsystems.com
  • 5. Tamperproof View State • If you want to make view state more secure, you have two choices. • Use a hash code: – A hash code is sometimes described as a cryptographically strong checksum. The idea is that ASP.NET examines all the data in view state, just before it renders the final page. – It runs this data through a hashing algorithm (with the help of a secret key value). The hashing algorithm creates a short segment of data, which is the hash code. – This code is then added at the end of the view state data, in the final HTML that’s sent to the browser. – When the page is posted back, ASP.NET examines the view state data and recalculates the hash code using the same process. It then checks whether the checksum it calculated matches the hash code that is stored in the view state for the page. – If a malicious user changes part of the view state data, ASP.NET will end up with a new hash code that doesn’t match. At this point, it will reject the postback completely http://www.rajpatsystems.com
  • 6. • Hash codes are actually enabled by default, so if you want this functionality, you don’t need to take any extra steps. • Hash codes are actually enabled by default, so if you want this functionality, you don’t need to take any extra steps. http://www.rajpatsystems.com
  • 7. Private View State • If your view state contains some information you want to keep secret, you can enable view state encryption. • You can turn on encryption for an individual page using the ViewStateEncryptionMode property of the Page directive. <%@Page ViewStateEncryptionMode="Always" %> Or you can set the same attribute in a configuration file: <configuration> <system.web> <pages viewStateEncryptionMode="Always" /> ... </system.web> </configuration> http://www.rajpatsystems.com
  • 8. • Either way, this enforces encryption. You have three choices for your view state encryption setting—always encrypt (Always), never encrypt (Never), or encrypt only if a control specifically requests it (Auto). • The default is Auto, which means that the page won’t encrypt its view state unless a control on that page specifically requests it. (Technically, a control makes this request by calling the age.RegisterRequiresViewStateEncryption() method.) • If no control calls this method to indicate it has sensitive information, the view state is not encrypted, thereby saving the encryption overhead. • On the other hand, a control doesn’t have absolute power—if it calls Page.RegisterRequiresViewStateEncryption() and the encryption mode is Never, the view state won’t be encrypted. • Tip: Don’t encrypt view state data if you don’t need to do so. The encryption will impose a performance penalty, because the web server needs to perform the encryption and decryption with each postback. http://www.rajpatsystems.com
  • 9. Retaining Member Variables • The basic principle is to save all member variables to view state when the Page.PreRender event occurs and retrieve them when the Page.Load event occurs. • Remember, the Load event happens every time the page is created. • In the case of a postback, the Load event occurs first, followed by any other control events. • The logic in the Load and PreRender event handlers allows the rest of your code to work more or less as it would in a desktop application. • However, you must be careful not to store needless amounts of information when using this technique. If you store unnecessary information in view state, it will enlarge the size of the final page output and can thus slow down page transmission times. • Another disadvantage with this approach is that it hides the lowlevel reality that every piece of data must be explicitly saved and restored. When you hide this reality, it’s more likely that you’ll forget to respect it and design for it. http://www.rajpatsystems.com
  • 10. Storing Custom Objects • You can store your own objects in view state just as easily as you store numeric and string types. • To store an item in view state, ASP.NET must be able to convert it into a stream of bytes so that it can be added to the hidden input field in the page. – This process is called serialization. If your objects aren’t serializable (and by default they’re not), you’ll receive an error message when you attempt to place them in view state. http://www.rajpatsystems.com
  • 11. [Serializable] public class Customer { private string firstName; public string FirstName { get { return firstName; } set { firstName = value; } } private string lastName; public string LastName { get { return lastName; } set { lastName = value; } } public Customer(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } } http://www.rajpatsystems.com
  • 12. • Because the Customer class is marked as serializable, it can be stored in view state: // Store a customer in view state. Customer cust = new Customer("Marsala", "Simons"); ViewState["CurrentCustomer"] = cust; • Remember, when using custom objects, you’ll need to cast your data when you retrieve it from view state. // Retrieve a customer from view state. Customer cust; cust = (Customer)ViewState["CurrentCustomer"]; http://www.rajpatsystems.com
  • 13. Transferring Information Between Pages Cross-page posting. Query string. • Cross-Page Posting: – A cross-page postback is a technique that extends the postback mechanism. – The infrastructure that supports cross-page postbacks is a new property named PostBackUrl, which is defined by the IButtonControl interface and turns up in button controls such as ImageButton, LinkButton, and Button. To use cross-posting, you simply set PostBackUrl to the name of another web form. – When the user clicks the button, the page will be posted to that new URL with the values from all the input controls on the current page. http://www.rajpatsystems.com
  • 14. The Query String • Pass information using a query string in the URL. This approach is commonly found in search engines. For example, if you perform a search on the Google website, you’ll be redirected to a new URL that incorporates your search parameters. • Here’s an example: – http://www.google.ca/search?q=organic+gardening • The advantage of the query string is that it’s lightweight and doesn’t exert any kind of burden on the server. However, it also has several limitations: – Information is limited to simple strings, which must contain URL-legal characters. – Information is clearly visible to the user and to anyone else who cares to eavesdrop on the Internet. – The enterprising user might decide to modify the query string and supply new values, which your program won’t expect and can’t protect against. – Many browsers impose a limit on the length of a URL (usually from 1KB to 2KB). For that reason, you can’t place a large amount of information in the query string and still be assured of compatibility with most browsers. http://www.rajpatsystems.com
  • 16. URL Encoding • With URL encoding, special characters are replaced by escaped character sequences starting with the percent sign (%), followed by a two-digit hexadecimal representation. For example, the & character becomes %26. The only exception is the space character, which can be represented as the character sequence %20 or the + sign. • To performURL encoding, you use the UrlEncode() and UrlDecode() methods of the HttpServerUtility class. string url = "QueryStringRecipient.aspx?"; url += "Item=" + Server.UrlEncode(lstItems.SelectedItem.Text) + "&"; url += "Mode=" _ chkDetails.Checked.ToString(); Response.Redirect(url); • You can use the UrlDecode() method to return a URL-encoded string to its initial value. http://www.rajpatsystems.com
  • 17. Cookies • Cookies are small files that are created on the client’s hard drive (or, if they’re temporary, in the web browser’s memory). • They work transparently without the user being aware that information needs to be stored. • Can be easily used by any page in your application and even be retained between visits, which allows for long-term storage. • They suffer from some of the same drawbacks that affect query strings—namely, they’re limited to simple string information, and they’re easily accessible and readable if the user finds and opens the corresponding file. These factors make them a poor choice for complex or private information or large amounts of data. • Before you can use cookies, you should import the System.Net namespace so you can easily work with the appropriate types http://www.rajpatsystems.com
  • 18. Set And Remove a Cookie • Both the Request and Response objects (which are provided through Page properties) provide a Cookies collection. • The important trick to remember is that you retrieve cookies from the Request object, and you set cookies using the Response object. • To set a cookie, just create a new HttpCookie object. You can then fill it with string information (using the familiar dictionary pattern) and attach it to the current web response. // Create the cookie object. HttpCookie cookie = new HttpCookie("Preferences"); // Set a value in it. cookie["LanguagePref"] = "English"; // Add another value. cookie["Country"] = "US"; // Add it to the current web response. Response.Cookies.Add(cookie); • A cookie added in this way will persist until the user closes the browser and will be sent with every request. To create a longer-lived cookie, you can set an expiration date. // This cookie lives for one year. cookie.Expires = DateTime.Now.AddYears(1); http://www.rajpatsystems.com
  • 19. • You retrieve cookies by cookie name using the Request.Cookies collection. HttpCookie cookie = Request.Cookies["Preferences"]; // Check to see whether a cookie was found with this name. // This is a good precaution to take, // because the user could disable cookies, // in which case the cookie will not exist. string language; if (cookie != null) { language = cookie["LanguagePref"]; } • The only way to remove a cookie is by replacing it with a cookie that has an expiration date that has already passed. HttpCookie cookie = new HttpCookie("LanguagePref"); cookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(cookie); http://www.rajpatsystems.com
  • 20. Session State • It allows you to store any type of data in memory on the server. • The information is protected, because it is never transmitted to the client, and it’s uniquely bound to a specific session. • Every client that accesses the application has a different session and a distinct collection of information. • Session state is ideal for storing information such as the items in the current user’s shopping basket when the user browses from one page to another. http://www.rajpatsystems.com
  • 21. Session Tracking • ASP.NET tracks each session using a unique 120-bit identifier. • ASP.NET uses a proprietary algorithm to generate this value, thereby guaranteeing (statistically speaking) that the number is unique and it’s random enough that a malicious user can’t reverse-engineer or “guess” what session ID a given client will be using. This ID is the only piece of session-related information that is transmitted between the web server and the client. • When the client presents the session ID, ASP.NET looks up the corresponding session, retrieves the objects you stored previously, and places them into a special collection so they can be accessed in your code. This process takes place automatically. http://www.rajpatsystems.com
  • 22. • For this system to work, the client must present the appropriate session ID with each request. You can accomplish this in two ways: – Using cookies: In this case, the session ID is transmitted in a special cookie (named ASP.NET_SessionId), which ASP.NET creates automatically when the session collection is used. This is the default, and it’s also the same approach that was used in earlier versions of ASP. – Using modified URLs: In this case, the session ID is transmitted in a specially modified (or managed) URL. This allows you to create applications that use session state with clients that don’t support cookies. • Session state doesn’t come for free. Though it solves many of the problems associated with other forms of state management, it forces the server to store additional information in • memory. This extra memory requirement, even if it is small, can quickly grow to performancedestroying levels as hundreds or thousands of clients access the site. • In other words, you must think through any use of session state. A careless use of session state is one of the most common reasons that a web application can’t scale to serve a large number of clients. http://www.rajpatsystems.com
  • 23. Using Session State • You can interact with session state using the System.Web.SessionState.HttpSessionState class, which is provided in an ASP.NET web page as the built-in Session object. The syntax for adding items to the collection and retrieving them is basically the same as for adding items to a page’s view state. • For example, you might store a DataSet in session memory like this: Session["InfoDataSet"] = dsInfo; • You can then retrieve it with an appropriate conversion operation: dsInfo = (DataSet)Session["InfoDataSet"]; http://www.rajpatsystems.com
  • 24. • Session state is global to your entire application for the current user. However, session state can be lost in several ways: • If the user closes and restarts the browser. • If the user accesses the same page through a different browser window, although the session will still exist if a web page is accessed through the original browser window. Browsers differ on how they handle this situation. • If the session times out due to inactivity. • If your web page code ends the session by calling the Session.Abandon() method. • In the first two cases, the session actually remains in memory on the web server, because ASP.NET has no idea that the client has closed the browser or changed windows. The session will linger in memory, remaining inaccessible, until it eventually expires. http://www.rajpatsystems.com
  • 26. It’s also a good practice to add a few session- friendly features in your application. For example, you could add a logout button to the page that automatically cancels a session using the Session.Abandon() method. This way, the user will be encouraged to terminate the session rather than just close the browser window, and the server memory will be reclaimed faster. http://www.rajpatsystems.com