Sunteți pe pagina 1din 9

Cookies

1. Cookies can store only "string" datatype


2. They are stored at Client side
3. Cookie is non-secure since stored in text format at
client side
4. Cookies may or may not be individual for every
client
5. Due to cookies network traffic will increase.Size
of cookie is limited to 40 and number of cookies to be
used
is restricted to 20.
6. Only in few situations we can use cookies because
of no security
7. We can disable cookies
8. Since the value is string there is no security
9. We have persistent and non-persistent cookies

Session
1. Session can store any type of data because the
value is of datatype of "object"
2. These are stored at Server side
3. Session are secure because it is stored in binary
format/encrypted form and it gets decrypted at server
4. Session is independent for every client i.e
individual for every client
5. There is no limitation on size or number of
sessions to be used in an application
6. For all conditions/situations we can use sessions
7. we cannot disable the sessions.Sessions can be used
without cookies also(by disabling cookies)
8. The disadvantage of session is that it is a
burden/overhead on server
9. Sessions are called as Non-Persistent cookies
because its life time can be set manually

• The main difference between cookies and sessions is that cookies are stored in the user's
browser, and sessions are not. This difference determines what each is best used for.
• A cookie can keep information in the user's browser until deleted. If a person has a login and
password, this can be set as a cookie in their browser so they do not have to re-login to your
website every time they visit. You can store almost anything in a browser cookie.
• The trouble is that a user can block cookies or delete them at any time. If, for example, your
websites shopping cart utilized cookies, and a person had their browser set to block them,
then they could not shop at your website.
• Sessions are not reliant on the user allowing a cookie. They work instead like a token allowing
access and passing information while the user has their browser open. The problem with
sessions is that when you close your browser you also lose the session. So, if you had a site
requiring a login, this couldn't be saved as a session like it could as a cookie, and the user
would be forced to re-login every time they visit.

As far as my knowledge is concerned cookies are stored on client side where as sessions are server
variables. The storage limitations are also there (like IE restricts the size of cookie to be not more
than 4096 bytes). We can store only a string value in a cookie where as objects can be stored in
session variables. The client will have to accept the cookies in order to use cookies there is no need of
user's approval or confirmation to use Session variables cos they are stored on server. The other
aspect of this issue is cookies can be stored as long as we want(even for life time) if the user accepts
them but with session variables we can only store something in it as long as the session is not timed
out or the browser window is not closed which ever occurs first.

Coming to usage you can use both cookies and session in the same page.

We should go for cookies to store something that we want to know when the user returns to the web
page in future (eg. remember me on this computer check box on login pages uses cookies to
remember the user when he returns). Sessions should be used to remember something for that
particular browser session (like the user name to display on every page or where ever needed).

how to write and read cookies.

This eample code belongs to web site www.gotdotnet.com visit the following link for full example code
and demo.

http://samples.gotdotnet.com/quickstart/aspplus/doc/stateoverview.aspx

Protected Sub Page_Load(sender As Object e As EventArgs)


If Request.Cookies( preferences1 ) = Null Then
Dim cookie As New HttpCookie( preferences1 )
cookie.Values.Add( ForeColor black )
...
Response.AppendCookie(cookie)
End If
End Sub

Protected Function GetStyle(key As String) As String


Dim cookie As HttpCookie = Request.Cookies( preferences1 )
If cookie <> Null Then
Select Case key
Case ForeColor
Return(cookie.Values( ForeColor ))
Case ...
End Select
End If
Return( )
End Function

How to write and read session variables.

This example belongs to www.eggheadcafe.com visit the following link for quick summary and list of
FAQs on Session State.

http://www.eggheadcafe.com/articles/20021016.asp

Basic use of Session in ASP.NET (C#):

STORE:
DataSet ds = GetDataSet(whatever parameters);
Session[ mydataset )=ds;

RETRIEVE:
DataSet ds = (DataSet)Session[ mydataset ];

A cookie is an identifaction string stored by a server (who has a domain) in the browser of the user who
visits the server/domain.

A session is a unit of maybe variables, state, settings while a certain user is accessing a server/domain
in a specific time frame. All the session information is in the traditional model stored on the server (!)

Because many concurrent users can visit a server/domain at the same time the server needs to be able to
distinguish many different concurrent sessions and always assign the right session to the right user.
(And no user may "steal" another uses's session)

This is done through the cookie. The cookie which is stored in the browser and which should in this
case be a random combination like s73jsd74df4fdf (so it cannot be guessed) is sent on each request
from the browser to the server, and the server can assign and use the correct session for its answers
(page views)

The cookie allows the server to recognize the browser/user. The session allows the server to remember
information between different page views.

Cookie is a client side storage of your variables. It stored on client machine by browser physically.
It's scope is machine wide. Different users at same machine can read same cookie.
Because of this :

1. You should not store sensitive data on cookie.


2. You should not store data that belongs to one user account.
3. Cookie has no effect on server resources.
4. Cookie expires at specified date by you.
Session is a server side storage of your variables. Default, it stored on server's memory. But you can
configure it to store at SqlServer. It's scope is browser wide. Same user can run two or more browsers
and each browser has it's own session.
Because of this :

1. You can save sensitive data in session.


2. You should not save everything in session. it's waste of server resources.
3. After user closes browser, session timeout clears all information. (default is 20 minutes)

Application State

There are occasions when you need to define global variables in an


application that are available to all modules of that application. In ASP.NET,
it can be done by application state. You can directly add and remove items
to the application state. The HttpApplicationState object represents the
application state in ASP.NET. The HttpApplicationState object is created
when a client requests any URL resource from within an ASP.NET application
virtual directory. The reference to this object is exposed through the
Application object.

The properties of HttpApplicationState class are listed in Table 1.

Table 1. The HttpApplicationState class properties

Property Description
AllKeys Gets the access keys available in an application state collection
Contents Gets the reference to an application state object
Count Total number of objects in an application state collection
Item Gets an item from the collection
StaticObjects Gets objects declared by <object> tag
The HttpApplicationState class provides methods to add, remove, lock and
unlock items. Table 2 describes the HttpApplicationState class methods.

Table 2. The HttpApplicationState class methods

Method Description
Add Adds a new object to application state
Clear Removes all objects from an application state
Get Gets an application state object by name or index.
GetKey Gets an application state object name by index
Lock Locks an application state variable and make sure variable is not accessible by
other modules of an application until it is unlocked.
Unlock Unlocks a locked variable
Remove Removes an object from the collection
RemoveAll Removes all objects from a collection
RemoveAt Removes an object from the collection by using an index
RemoveAt Updates the value of an object in a collection

Adding, Updating, and Removing Items to an Application State

As we saw in Table 2, the HttpApplicationState class provides methods to


add and remove items to application state. It also provides Get and Set
methods that can be used to get an object and update the values of an
object.

The application state object is accessed through the Application object. The
Application object is available in all pages or all modules of an application.

OK, now let's add an item to application state. You can either use the Add
method or direct pass the item and its values. The following code snippet
adds two items to application state:

Application("ConnectionString") = connectionString
Application("Title") = "Job Board"

Once an item is added to an item state, it is available to all pages and


modules of the application. You can remove an item from an application
state by using the Remove method of Application. The following code snippet
removes the Title item:

Application.Remove("Title")
You can also use the Clear or RemoveAll method to remove all items from an
application state. The following code snippet removes all items from an
application state:

Application.RemoveAll()

Caution: Use application state to store variable cautiously. Since variables


are defined globally, these variables are available in the memory until the
application closes. Using large objects such as lists, images, and large data
may lead to some serious problems. Also use synchronization techniques to
avoid any deadlock situations and maintain the integrity of data.
Synchronization technique for application state is discussed in the following
section.

Locking and Unlocking Application State Items

All items added to the application state are available to all modules and
pages of an application. There may be cases when an item can be accessed
and updated by multiple users simultaneously, which may lead to data
integrity violation. Even using complex objects and updating simultaneously
may cause serious damage to the data and may lead to deadlocks or access
violations. For example, say a Web site has a counter, which advances when
a new users visits the site. Now say current value of counter is 100 and 2
users visit the site simultaneously. In this case each user will have 101.

The HttpApplicationState class provides Lock and Unlock methods that


provides a way to resolve this situation. The Lock method locks an item and
a locked item won't be available to other users until an item is not unlocked.
The following code snippet locks a counter, updates its value and unlocks it
when a user is done updating it.

Application.Lock()
Application("counter") += 1
Application.UnLock()

Caution: Locking and Unlocking application state items may degrade the
performance of an application.

Application Object in ASP.NET : A Beginner's View


Introduction
Application state is the server side state management technique, I have already mention the concept
of <a
href="http://www.dotnetspider.com/resources/36876-b-Cookies-ASP-NET-A-Beginner-s-View-
b.aspx">Cookies </a>, which is the client side state management.
Now in this hour we concentrate on the Application state.

What is a Application State


We can use application state for storing information in server memory. Application state is a data
repository that is available to all classes within an ASP.NET application.

Application state is stored in memory on the server and is faster than storing and retrieving data in a
database.Unlike session state, which is specific to a single user session, application state applies to all
users and sessions. Therefore, application state is a useful place to store small amounts of often-used
data that does not change from one user to another.

Application state is stored in an instance of the HttpApplicationState class. This class exposes a key-
value dictionary of objects.

Where the application state get stored

A single instance of an HttpApplicationState class is created the first time a client requests any URL
resource from within a particular ASP.NET application virtual directory.
Application state is stored in memory on the server, so a large amount of data in application state can
fill up server memory quickly. If the application is restarted, application state data is lost. Application
state is not shared between multiple servers Within a Web farm or between worker processes in a
Web garden.

To write a value to application state


We can store a value in session state. It is much faster than saving data on disk or database.

The following example shows you how to store values in Application state

Application["Message"] = "Dotnetspider for web


developers";

we can write same code in Global.asax, under Application_Start handler. The Application initialize from
here.
To read a value from application state
before accessing Application variable just check is it NULL

if (Application["Message"] != null)
{
txtName.Text = Application["Message"].ToString();
}

Now your txtName will contain "Dotnetspider for web developers" string.

Application state stores data typed as Object, you should cast the data to the appropriate type when
retrieving it.
see following example

if (Application["Yesterday"] != null)
{
DateTime dtYesterday = (DateTime)
Application["Yesterday"];
}

Application state variables can be accessed by multiple threads at the same time. Therefore, to
prevent invalid data, you must lock application state for writing by only one thread before setting
values.

In the code where you set the application variable,


call the HttpApplicationState..::.Lock method,

Set the application state value, and then call the HttpApplicationState..::.UnLock method to unlock the
application state, freeing it for other write requests.

The following code example shows how you can lock and unlock application state. The code increases
the PageRequestCount variable by 1 and then unlocks application state

Application.Lock();
Application["iCount"] = ((int)Application["iCount"])+1;
Application.UnLock();

Bold Features
Application has some bold features as follows

- Simple implementation
Application state is simple to use and consistent to .NET framework classes

- Scope
Because application state is accessible to all pages in an application, so only

single copy of data can be used any where.


- Faster
Application state has faster access than that of storing value in database.

while dealing with the Application state some you should following points in consideration
1. Volatility -
As we know the application state is stored in server memory, the data get lost if

the application is restarted or stopped.

2. Resources -
Storing large blocks of data in application state can fill up server memory, causing the server to page
memory to disk. You can use cache technique as an alternative to Application state for handling
large data.

This is short about the Application state.

Note:
The main difference between session and Application state is Session is specific for single
user where as Application is same for all user

S-ar putea să vă placă și