Session and Application
Session
A session is the time for which a particular user interacts with a web application. During a
session the unique identity of the user is maintained internally. A session ends if there is a
session timeout or if you end the visitor session in code.
Use of Session
Sessions helps to preserve data across successive accesses. These can be done on a per user
basis, via the use of session objects. Session objects give us the power to preserve user
preferences and other user information when browsing a web application.
Session object
A Session object stores information about, or change settings for a user session.
When we are working with an application on our computer, we open it, do some changes and
then we close it. This is much like a Session. The computer knows who we are. It knows when
we open the application and when we close it. However, on the internet there is one problem: the
web server does not know who we are and what we do, because the HTTP address doesn't
maintain state.
ASP solves this problem by creating a unique cookie for each user. The cookie is sent to the
user's computer and it contains information that identifies the user. This interface is called the
Session object.
The Session object stores information about, or change settings for a user session.
Variables stored in Session object hold information about one single user, and are available to all
pages in one application. Common information stored in session variables is name, id, and
preferences. The server creates a new Session object for each new user, and destroys the Session
object when the session expires.Session Start:
A session starts when:
+ A new user requests an ASP file, and the Global.asa file includes a Session_OnStart
lure
+ A value is stored in a Session variable ' a
+ A.user requests an ASP file, and the Global.asa file uses the
tag to instantiate an
object with session scope.
Session End
+ A session ends if a user has not requested or refreshed a page in the application for a
specified period. By default, this is 20 minutes.
+ If you want to set a timeout interval that is shorter or longer than the default, use the
Timeout property.
The main problem with sessions is WHEN they should end. We do not know if the user's last
request was the final one or not. So we do not know how long we should keep the session
"alive". Waiting too long for an idle session uses up resources on the server, but if the session is
deleted too soon the user has to start all over again because the server has deleted all the
information. Finding the right timeout interval can be difficult!
Session Type What it does [Example
SessionAbandon _‘Abandons (cancels) the current
session,
Session(“username”) ="abo”
(Initialize a session variable)
Delete an item from the session-
Session. Remove ssior
state collection. Session.Remove(““username”)
(Deletes the session _variable
| “username”
Session.RemoveAll _ Deletes all session state items
Session.Timeout=30 (If a user does
Set the timeout (in minutes) for NOT request a page of the ASP.NET
a session application within 30 minutes then the
session expires.)
Session. Timeout
Get the session ID (read only
Session.SessionID property of a session) for the
‘current session.
This is to check if the visitor’s
session was created with the
current request ie. has the
| visitor just entered the site. The
Session IsNewSession
131IsNewSession property is true
within the first page of the
ASP.NET application.
Store and Retrieve Session Vari
les
The most important thing about the Session object is that we can store variables in it.
The example below will set the Session variable username to "Abc" and the Session variable age
to "50":
Session ["usemame'
Session ["age"
"Abe"
‘When the value is stored in a session variable it can be reached from ANY page in the ASP
application:
Welcome <%Response. Write (Session ("username") %>
The line above returns: "Welcome Abc",
You can also store user preferences in the Session object, and then access that preference to
choose what page to return to the user.
The example below specifies a text-only version of the page if the user has a low screen
resolution:
‘<“%6lf Session ("screenres")="low" Then%>
This is the text version of the page
<%Else%>
This is the multimedia version of the page
<%End If%>
Remove Session Variables
The Contents collection contains all session variables.
It is possible to remove a session variable with the Remove method.
The example below removes the session variable "sale" if the value of the session variable "
‘age"
is lower than 18:
132<%
If Session.Contents ("age")<18 then
Session.Contents.Remove("sale")
End If
%>
To remove all variables in a session, use the RemoveAll method:
<%
Session.Contents.Removeall ()
%>
Steps of creating a s
(in asp.net)
1.
2.
-
4.
=
Open anew web site.
Take a Textbox & Button of name session.
‘Now right click on the root of the of solution explorer add new item after the add
global.aspx page
After taking the global page on the session start event we done the following coding
which shows in the snapshots.
On the click event of the button text box has the value of current Session.
The Snapshot of session as follows:
Add new item:
Sapeeenees peicrvet oaes
an * ee SDe SP.
a emcee
am = Seams
Gun ie eet
Hat eam.
At ot eset,
Howtos a ree
= pin
Bowe hee.
0 ate | Sheba
Sioa sits hdowe.
amen Bence tagan
ate D coy mese,
ae some
tow smn
cee 2 teen
som =
ome a tone
= a:
x
133Global.asax file(by default added in some studio editors):
LIE eeemgememnteeeneNNAS
Dada Powe a
“Foe
PY Sores,
a cod
Global page coding:
a
Fe TH tow Rot wate SA Diy Ta Tet he
“3
© sere abe
a
rt
a
zButton clicks event coding:
.. Qt arBo.
2" time debug:Value of the session will be start from 1 when we run from starting,Application
‘A group of ASP files that work together to perform some purpose is called an application.
Application state is stored in memory on the server and is faster than storing and retrieving
information 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.
we can use application state in two ways. We can add, access, or remove values from the
Contents collection directly through code. The HttpApplicationState class can be accessed at any
time during the life of an application. However, it is often useful to load application state data
when the application starts. To do so, you can put code to load application state into the
Application_Start method in the Global.asax file.
Alternatively, we can add objects to the StaticObjects collection via an
declaration in your Web application's Global.asax file. Application state defined in this way can
then be accessed from code anywhere in your application. The following example shows an
object declaration for an application state value:
We can access members of objects stored in application state without having to reference the
Application collection. The following code example shows how to reference a member of an
object defined in the StaticObjects collection of application state. Notice that the label identifier
defined in Global.asax is used as the variable name.
CH
Protected void Page_Load (Object sender, EventArgs e)
{
Label. Text = Mylnfo. Title;Application Lifeti
Application lifetime refers to the time span for which an application domain persists. This does
not mean that application lifetime is equivalent to the time span for which an application runs.
Infact, an application domain can shut down in several circumstances, including specific error
condition changes, or web Server shut-down. There-fore, an application’s runtime might require
a restart under the circumstances:
© Excess request in the queue
* Excess memory usage by an application
© Lengthy lifetime of the application
© Modification in the Web.config file
© Replacement of existing Dynamic Link Libraries(.dll files) or Web files
An application on the Web may consist of several ASP files that work together to perform some
purpose. The Application object is used to tie these files together.
The Application object is used to store and access variables from any page, just like the Session
object. The difference is that ALL users share ONE Application object (with Sessions there is
ONE Session object for EACH user).
The Application object holds information that will be used by many pages in the application (like
database connection information). The information can be accessed from any page. The
information can also be changed in one place, and the changes will automatically be reflected on
all pages.
Store and Retrieve Application Variables
Application variables can be accessed and changed by any page in an application,
You can create Application variables in "Global.asa" like this:
In the example above we have created two Application variables: "vartime” and “users
You can access the value of an Application variable like this:
There are
%
Response. Write (Application ("users")
%>
active connections.
Step for creating an application:
L
2.
=
4.
Open a new web site.
Take a Textbox & Button of name application.
‘Now right click on the root of the of solution explorer add new item after the add
global aspx page.
After taking the global page on the session start event we done the following coding
which shows in the snapshots.
On the click event of the button text box has the value of application
Add new item:
Add global page:Coding of global page:
Sn TF
eh 4.392 = a LASBSOD-4 ns 22 oe,
Snes se a. rw ieCoding of button’s click event:
On is time application running:
a |
Bie Pest ant maes emery methane
2 Pee
=
Value of application is one.‘When we run second time the output will be
a
os . same cm i hom |
Drm @ core | tae seen tn on i
4
—
Now the value of the application starts with 2. When we run I* time it is 1 now it 2 so value of
the application never start from the starting it will start from that value where we end the last
application.
ference between session and application:
1. Application state will be available to all users of the application when set
basically user A sets application variable "AppID" to “myApp"
User B retrieves application variable "ApplD" and reads_—“myApp"
Session state will only be available to a specific user of the ASP.net application
User A sets session variable "UserID" to ""
User B loads the — session variable "UserID". and _— receives null
User A loads the session variable "UserID" and receives "2",
2. The main difference is that application is common for the whole application and session is
different for different user.
3, Session State — Session State information is available to all pages opened by a _
during a single visit. Application State - Application State information is
142available to all__~—pages, regardless of |~= which user requests_ a
page.
4. Session variable are only available at the user level means no user can access the other user
session variables.
Application variable is available at application level means every user of the application can
access the same application variable.
€e
tet cary sae en nate Gath one
a (c=)
The value of both session and application is 1.
On 2" run the output will beThe value of the session will be remain same i.e. start with 1 and the value of appli
will increased by 1.Creating HotSpots In ASP.NET Application
Introduetion
In this article I am going to create HotSpots in ASP.NET Web Application by using an
ImageMap control. As we know some web pages commonly include complex graphics, where
different actions are taken depending on what part of the graphic is clicked. We're .NET
Developers so we have several tricks to implement the required design.
Before going to create HotSpots, we should know about the term "HotSpots" in ASP.NET web
development.
What is HotSpot
In ASP.NET, HotSpot is a small area of an Image which may produce some actions when
anyone click or move over that hotspot (area). Basically it's the part of graphics design which is
used for complex web page design. ASP.NET have several tricks to implement those type of
graphics design. Let's see the following three tricks which are commonly used to complete our
tasks related to hotspots.
+ Stacked Image
+ ImageButton Control
+ ImageMap Control
Let's see the following image which shows four rectangular hotspots on a single image.
We may see in Figure | where a single image is divided into four hotspot areas, ie. HotSpot 1,
2,3 and 4, even it's a single image but if we click on the area of HopSpot-I the others three areas
will not be affected. It means if we click on HotSpot-1 it produce the result for HotSpot-1 only
similarly if we click on HotSpot-2 it produce the result for HotSpot-2 only.
‘As we read above we have three ways to create hotspot in ASP.NET but inthis article am going
to explain more about the third one, that is by using ImageMap Control. But before going to
start it, let us do a quick recap about Stacked Image and ImageButton,
Stacked Image
Creating a single image by using a collection of various images together and positioned the
Particular part of image with different controls carefully which looks like one graphics where we
can handle the click event of each control separately.
Example:
Using Spritelmage is the best example of stacked images.
145ImageButton Control
When a ImageButton control is clicked, it provides the coordinates where the click a rate:
We can find out this co-ordinate on our server side code to determine what region was clicked.
will explain more about it in upcoming article.
Example:
Note:
This is a single image which looks like three buttons. If we put this image as a background of a
ImageButton so on click event we can identify that the clicked area is the part of "Home",
"About" or "Venue". This technique is flexible but tedious and error-prone. Now let's see about
the ImageMap Control.
Creating HotSpots using ImageMap Control
By using ImageMap control, we can define separate regions and give each one a unique name.
This approach is good either for small hotspots or large. The following are the advantages of
using ImageMap to create hotspots.
Advantages
« When user moves the mouse pointer over the images, it changes to hand only when the
user positioned over a defined region.
* The region of image which is not the part of any HotSpots, is not clickable as well as the
mouse pointer shows as default.
« It works well for the smallest hotspots as well.
Let's see the following code snippet for ImageMap,
But to define the clickable regions, we need to add HotSpots object to the ImageMap. HotSpots
property ASP.NET provides three types of HotSpots.
1. RectangleHotSpot
2. CireleHotSpot and
3. PolygonHotSpot
Note:
We can create a hotspot in any shape by using these three objects according to our requirement.
But the main challenges are to know the exact coordinates of hotspot.
Example:
Suppose we need to create a hotspot in rectangular shape, we must know the four coordinates:
Left, Top, Right and Bottom. See the following image in which I have created a hotspot of an
image in rectangular shape.
HotSpot
(200, 124)
We can see in the above figure, there a small rectangular area is showing so if we want to create
a hotspot over this rectangular area only, we need to define its four coordinates Top-Left,
Bottom-Left, Top-Right and Bottom-Right. So there is a big challenge to find out the exact
coordinate while creating a hotspot
How to Calculate Coordinates
we have several tools to find out the exact coordinates ofa hotspot. But | know about these only
+ Expression Web
+ Visual Studio ImageMap Designer
+ Microsoft PaintIf you're using Expression Web, once you tweaked the hotspots to perfection, you can see the
exact coordinate value in the source code. but if you're using Visual Studio ImageMap
Designer, it doesn't let you define regions visually. I am going to use MS Paint for this article.
Further we will see how to use MS Paint to find coordinates.
RectangularHotSpot
If we define a hotspot in rectangular shape then we can use "RectangleHotSpot" which accepts
four coordinates as top-left and bottom-right corners but there order of coordinates must be left,
top, right and bottom. Let's see the following code snippet in which I am using a
RectangleHotSpot inside the ImageMap control.
ImageMapDemo" runat="server" HotSpotMode="PostBack"
OnClick="ImageMapDemo Click" ImageUrl="~/Images/CoverPhoto.png”
The ImageMap control provides a server-side abstraction over the HTML and
tags, which define an image map. This ASP.NET ImageMap control renders itself as a
tag and its region as tag. Let's see the source code for above code snippet of
RectangleHotSpot
Rendered HTML Code
— >
Y
* title=
ImageMap control rendered into html tag. ©°°'dinates.
HotSpotObject is rendered into html tag.ASP.NET provides a class "RectangleHotSpot" which is a derived class of HotSpot class. The
following are the properties of RectangleHiotSpot.
Properties of RectangleHotSpot
+ PostBackValue: It is used to get or set name of the HotSpot object to pass the event data
when it is clicked.
+ NavigateUrl: Gets or sets the URL to navigate when it is clicked.
+ AlternateText
Gets or sets the alternate text to display for a HotSpot object in an ImageMap control
when the image is unavailable or renders to a browser that does not support images.
+ HotSpotMode: To get or set the behavior of a HotSpot object in an ImageMap control
when the HotSpot is clicked.
Note: This property can be set by using the following four enumeration values.
1. NotSet: HotSpotMode="NotSet"
The HotSpot uses the behavior set by the ImageMap control's HotSpotMode property. If
os iimeeeMap control does not define the behavior, the HotSpot objects navigate to a
2. Inactive: HotSpotMode="Inactive"
The HotSpot does not have any behavior.
3. Navigate- HotSpotMode="Navigate"
The HotSpot navigates to a URL.
4. PostBack -HotSpotMode="PostBack"
The HotSpot generates a postback to the server.
° LeftGets or sets the x-coordinate of the left side of the rectangular region defined by this
RectangleHotSpot object.
* Top
Gets or sets the y-coordinate of the top side of the rectangular region defined by this
RectangleHotSpot object.
+ Right
Gets or sets the y-coordinate of the top side of the rectangular region defined by this
RectangleHotSpot object.
+ Bottom
Gets or sets the y-coordinate of the bottom side of the rectangular region defined by this
RectangleHotSpot object.
CircleHotSpot
Ifwe need to define a hotspot in circular shape then we can use "CireleHotSpot” which accepts
three coordinates values as X-coordinate, Y-coordinate and the radius value. Let's see the
following code snippet in which | am using a CircleHotSpot inside the ImageMap control.
ernatelex: Polygon HotSpot
PostBackValu ‘MyCircle”
HotSpotMode="PostBack" />
Coordinates values
PolygonHotSpot
Let us see the following picture which shows how the rendered HTML looks for these three
HotSpots.= Rendered HTML Sorce Code for HotSpots
ing id “ImageNapDemo” src-"Inages/CoverPhoto.png” usenap-"#InageHaplmagetapdeno” style
width:500px; >
Vcmap ane TnageNapImagetapDemo" id-“ImagettapInageNapOemo’ >
weg re] crs "10,10,110, 60" href" javascript: _doPostsack(“ImagetapDemo’ ,°9")
ti
Rectangular HotSpot” alt “Rectangular Hotspot” »
aree[srape circle] coords "200, 120, 50"| href=" javascript: _doPostBack( "ImageMlapDemo", "1" )"
title: "Circular HotSpot” alt-"Circular HotSpot
2505 235,430" |href. “javascript:
PostBack "Tmay jemo',"2'}" title “Polygon HotSpot’ alt-"Polygon HotSpot
HotSpots Implementation in Web Application
‘Now I am going to create a demo application to show the real implementation of HotSpots. For
this article I am using Visual Studio 2012 as development tool and Microsoft Paint to calculate
the coordinates of hotspot.
Note: It's supportable from NET Framework 2.0
Step 1: Start your Visual Studio and create a new website. For this article 1 going to create an
Empty Website.
0G Hotspots - vicrasottVisua’ Studio
FUE _€DIT__ViEW WEBSITE BUILD DEBUG TEAM SQL TOOLS TEST ARCHITECTURE
Project From Existing Code...
Now select a project template as "ASP.NET Empty Web Sit—
amensn$$ > sence
l= Eel
oe
= &
= a
=
— ASP.NET Web Ste Razervt) Views OF
=
ASOT Web Se Razor) Vol
ASS NEY Oyama Cat Enter ust CE
Step 2: Now create three Web Pages, for this article I am going to create the pages whose names
are the following,
1. RectangleHotSpot.aspx
2. CircleHotSpot.aspx and
3. PolygonHotSpot.aspx
Because we are going create hotspot on images shown we should have some image on which we
will create hotspots. So for this article, | have taken three images inside the images folder. Now
our Solution Explorer will look like the following snapshot.
Solution Explorer pana ibd
@ e-20an +p
olution Explorer (Ctrl=:) a:
&) Solution ‘HotsPots' (1 project)
4 «Images
& CircleHotSpot.png
images
& PolygonHotSpot.png
a io
4D Citkerrespocuspr J
4D CircleHotSpotaspx.cs
4 @ PolygonHotSpot.aspx Web
D PolygonHotSpot.aspx.cs} pages
b 8) RectangleHotSpot.aspx
D Web.configStep 3:
Creating RectangleHotSpot
1.
2.
9
10.
14.
15.
16.
17.
18.
I have written the above code to create the rectangular hotspots. In this code I have taken two
RectangleHotSpots, first for facebook and second for twitter button, So if we move the mouse
‘over hotspot area, it show the name of area in tooltip.
If we click on hotspot, it will display some information related to that hotspot. So I have written
the following line of codes to perform some action when it is clicked.
1. protected void ImageMapDemo_Click(object sender, ImageMapEventArgs e)
2 {
3. var hostspotValue = e.PostBackValue;
4. var messageText = string Empty;
5.
6. switch (hostspotValue. ToLower())
7. {
8. case "facebook’
9. messageText = "You clicked on : " + "Twitter";;
13, break;
45414.
is)
16. divMessage.InnerHtm| = messageText;
7}
Now execute this page to see the output, and it will look like the following snapshot.
ORL MLEH ES
k
facebook RC cle el sieets
416, 100
EPUB erro ete)
Creating CircleHotSpot
‘Now we're going to create "CircleHotSpot”. So paste the following code inside the form tag of
"CircleHotSpot.aspx" page,
1.
2
3.
4.
5.
14,
15.
16.
17.
I have written the above code to create the circular hotspots. In this code
CircleHotSpots, first for facebook and second for twitter button,
hotspot area, it show the name of area in tooltip.
th Thave taken two
So if we move the mouse over
If we click on hotspot, it will display some information related to that hots,
ee pot. So I have written
the following lines of code to perform some action when it is clicked.
4551. protected void ImageMapDemo_Click(object sender, ImageMapEventArgs €)
ZI
3. var hostspotValue = e,PostBack Value;
4. var messageText = string. Empty;
3.
6. switch (hostspotValue.ToLower())
:
8. case "facebook":
9. messageText = "You clicked on : " + "Facebook<
/span>";
10. 7
i. case "twitter"
12, "You clicked on : " + " -
9.
10.
17.