Variables stored in the Session object are not discarded when the user browses from one page to another, within the same application. The object is destroyed when the user abandons [r]
(1)Session
(2)Exploring ASP.NET / Session / of 54
Review
To make HTML elements programmatically accessible, it is necessary to
indicate that an HTML element be parsed and treated as a server
control This can be done by adding a runat="server" attribute to the HTML element
The process of checking whether the user has filled up a form in the
right format, and has not left any fields blank, is called validation
The validation controls available are as follows:
RequiredFieldValidator: Helps in ensuring that a value is entered for a field CompareValidator: Checks if the value of a control is similar to the value of
another control
RangeValidator: Checks if the value entered in a control is in the specified
range of values
RegularExpressionValidator: Checks if the value entered fits the regular
expression that is specified
CustomValidator: The value entered is checked by a client-side or
server-side function written by the programmer
ValidationSummary: A list of all the validation errors occurring in all the
(3)Review Contd…
The Page object has a property called IsValid, that returns true if all
the validation tests are successful, and vice-versa
To disable client-side validation, the ClientTarget property can be set to
downlevel
Code Behind is a feature that enables the developer to write the code
(4)Exploring ASP.NET / Session / of 54
Objectives
Discuss the Global.asax file
Explain the events in the Global.asax file
Use the Application Object
Use the Server Object
(5)Global.asax File
Stored in Root Directory of application Defines boundary of application
Initialises application or session level variables Connects to databases
(6)Exploring ASP.NET / Session / of 54
Events in Global.asax
Events Description
Application_Start Fired when the first ASP.NET page in the
current application directory (or its sub-directories) is called
Application_End Fired when the last session of the application
ends Also fired when the web application is stopped, using the Internet Services Manger snap-in
Application_Begin Request
(7)Events in Global.asax Contd…
Events Description
Application_EndR equest
Fired every time a page request ends (that is every time the page executes on the browser)
Session_Start Fired every time a new session begins.
Session_End Fired when the session ends For the various
(8)Exploring ASP.NET / Session / of 54
Global.asax Example
Global.asax
<script language="C#" runat="server">
protected void Application_Start(Object sender, EventArgs e)
{ }
protected void Session_Start(Object sender, EventArgs e)
{
Response.Write( "Session Started <br>"); }
(9)Global.asax Example
protected void Application_BeginRequest(Object sender, EventArgs e)
{
Response.Write("<h1>Application Begins</h1>");
Response.Write ("Application request begins <br>");
}
protected void Application_EndRequest(Object sender, EventArgs e)
{
Response.Write ("Application request ends <br>");
(10)Exploring ASP.NET / Session / 10 of 54
Global.asax Example
protected void Session_End(Object sender, EventArgs e)
{
Response.Write("Session ended"); }
protected void Application_End (Object sender, EventArgs e)
(11)Test Global.asax
<html>
<title>Testing Global</title>
<script language="C#" runat="server">
void Page_Load(Object sender, EventArgs e) {
Response.Write ("Page Load event <br>"); }
(12)Exploring ASP.NET / Session / 12 of 54
(13)Application Object
Represents an instance of an ASP.NET application
Object[varName]
(14)Exploring ASP.NET / Session / 14 of 54
Application Object Example
void Application_Start(Object sender, EventArgs E) {
Application ["sessioncount"] = 0; }
<HTML>
<script Language ="C#" runat ="server" Debug = "true"> void Page_Load(Object Src, EventArgs E)
{
Response.Write (“Your visitor number is “ + Application ["sessioncount"]);
}
</script>
<form runat= "server" > </form>
(15)(16)Exploring ASP.NET / Session / 16 of 54
<html>
<script Language ="C#" runat ="server" Debug = "true"> void Page_Load(Object Src, EventArgs E)
{
Response.Write ("Your visitor number is :" + Application ["sessioncount"]);
}
</script>
<form runat= "server" > </form> </html>
Application Object Example
void Session_Start(Object sender, EventArgs e) {
Application["sessioncount"]=(Int32)Application["ses sioncount"] + 1;
(17)Application Object Output
Output after reopening the browser
(18)Exploring ASP.NET / Session / 18 of 54
Controlling Access
Application variables can be accessed and updated
by all the pages of an ASP.NET application
Since the variable retains the currently assigned
value, if a user changes the value of a variable, the value is changed for all the users of the application
To ensure that application-level variables are not
updated by more than one user simultaneously, the Application object makes use of the Lock() and
(19)Controlling Access Contd…
Application.Lock();
//…code to change the value of the application variables
……… …………
Application.UnLock();
The Lock method locks all the variables in a script Ensures that only the current user has control
over the page
(20)Exploring ASP.NET / Session / 20 of 54
Arrays
String [] job = new String [4]; job[0]= "Faculty";
job[1]= "Programmer"; job[2]= "Salesman"; job[3]= "Manager";
Application ["j"] = job;
Application-level arrays can be used to share common groups of information across the entire application
Typically, application-level arrays are used for information that is static
(21)Array.aspx
<HTML>
<script Language ="C#" runat ="server" > void Page_Load(Object Src, EventArgs E) { int i = 0; String[] k;
k = (String[])Application["j"]; for (i = 0; i<k.Length;i++)
{
Response.Write(k[i] + "<br>"); }
}
(22)Exploring ASP.NET / Session / 22 of 54
Server Object
Execute and Transfer HTMLEncode
URLEncode MapPath
Property Description
ScriptTimeo ut
Is used to specify the period for which a script can run on the server before it is terminated
MachineName Is used to get the machine name of the server
Server.property | method
(23)Execute Method
<%@ Page Debug ="true"%><html>
<script language="C#" runat="server"> void clicked (Object Src, EventArgs E) {Server.Execute (“Array.aspx");}
</script>
<form runat ="server">
<asp:button id = "btnClick" onclick = "clicked" Text =" Click me to transfer execution" runat = "server" />
</form>
(24)Exploring ASP.NET / Session / 24 of 54
(25)Transfer Method
Server.Transfer (“Array.aspx");
The Transfer() method is used to transfer the execution completely to the specified page
Unlike the Execute() method, the control is lost from the calling page when this method is executed
(26)Exploring ASP.NET / Session / 26 of 54
HTMLEncode Method
The HtmlEncode() method is used to apply
HTML encoding to a specified string
In case the HtmlEncode() method is not
specified, <H1> is interpreted by the browser as an HTML tag, and the text is displayed accordingly
The syntax of the HtmlEncode() method is:
(27)HTMLEncode Example
<%@ Page Debug ="true"%> <html>
<title>HtmlEncode</title>
<script language="C#" runat="server">
void Page_Load (Object Src, EventArgs E) {
Response.Write (Server.HtmlEncode("<H1> is an example of a Heading tag</H1>"));
}
</script>
(28)Exploring ASP.NET / Session / 28 of 54
HTMLEncode Output
Response.Write( Server.HtmlEncode("<H1> is an example of a Heading tag</H1>"));
(29)URLEncode Method
A URL can be used to send data from the client to a file
on the server
If the data contains non-alphanumeric characters such
as punctuation marks, quotation marks, or even blank spaces, the data needs to be encoded before it is sent to the server
The URLEncode() method of the Server object is used
to encode data that is passed to the server through a URL
The syntax is:
(30)Exploring ASP.NET / Session / 30 of 54
URLEncode Example
<%@ Page Debug ="true"%> <html>
<title>UrlEncode</title>
<script language="C#" runat="server"> void Page_Load(Object Src, EventArgs e) {
Response.Write(Server.UrlEncode ("http:// URLEncode.aspx"));
}
</script>
(31)URLEncode Method Contd…
<html>
<script language="C#" runat="server"> void Meclicked(Object Src, EventArgs e) {
string MyMessage = Server.UrlEncode ("This is my message to you");
Response.Redirect ("Array.aspx?MessageTB=" + MyMessage);
}
</script>
<form runat ="server">
(32)Exploring ASP.NET / Session / 32 of 54
URLEncode Method Contd…
When the code is executed, the page „Array.aspx‟ is called from the web server to process the information that is sent in the URL
The „Array.aspx‟ file can extract the data from the field MyMessage, which has been assigned a value
(33)MapPath Method
The MapPath() method is used by the server
to map a path to the information on the server
The method acts as an interface between the
virtual or relative directories on the web server and the physical directories on the server
The syntax for using the method is
(34)Exploring ASP.NET / Session / 34 of 54
<%@ Page Debug ="true"%> <html>
<script language="C#" runat="server">
void Page_Load (Object Src, EventArgs E) {
Response.Write (Server.MapPath("/Array.aspx"));
}
</script>
<form runat ="server"> </form>
</html>
MapPath Example
Note that the path of the virtual directory of the file „Array.aspx‟ is
(35)(36)Exploring ASP.NET / Session / 36 of 54
MapPath Example
<%@ Page Debug ="true"%> <html>
<title>MapPath-ServerVariables </title> <script language="C#" runat="server"> void Page_Load(Object Src, EventArgs e) {
Response.Write (Server.MapPath (Request.ServerVariables.Get ("PATH_INFO")));
}
</script>
(37)Session Object
Contains user specific information
Tracks and monitors user information in a session
Destroys object after session expiry
The Session object is used to store information about a user
This information is retained for the duration of the user session
Variables stored in the Session object are not discarded when the user browses from one page to another, within the same application
The object is destroyed when the user abandons the session, or the session
(38)Exploring ASP.NET / Session / 38 of 54
Using Variables
A session variable is different from an application
variable
A session variable is available only to a particular user
within a session
An application variable, on the other hand can be
accessed and modified by other users of the application
Session variables can be used to store values that are
(39)Using Variables Example
<html>
<title>Session Variable</title>
<script language="C#" runat="server">
void Page_Load(Object Sender, EventArgs e) {
Response.Write("<u><b><center>Logon authentication using Session
variables</center></b></u><br><br>"); }
void WritingSesVar(Object Sender, EventArgs e) {
Session["Name"] = txtUserName.Text;
(40)Exploring ASP.NET / Session / 40 of 54
Using Variables Contd…
lblMessage2.Text = ""; }
void ReadingSesVar(Object Sender, EventArgs e) {
lblMessage1.Text = "The value of name is " + Session ["Name"];
lblMessage2.Text = "The value of password is " + Session ["Password"];
}
void Clear(Object Sender, EventArgs e) {
(41)Using Variables Contd…
</script>
<form runat="server"> User name :
<asp:TextBox id = "txtUserName" runat="server" /> <br><br>
Password :
<input id="txtPassword" type="password" runat="server"> <br><br>
(42)Exploring ASP.NET / Session / 42 of 54
Using Variables Output
<br><br>
<asp:Label id = "lblMessage1" runat="server" /> <br><br>
<asp:Label id = "lblMessage2" runat="server" /> <br><br>
(43)Using Variables Modified
The value in a session variable can be read from another web page also The previous example is modified to display the values of the session
variables in another web page „SessionVariableRedirected.aspx‟ instead of the same page „SessionVariable1.aspx‟
The session variable is not declared or assigned value in the
„SessionVariableRedirected.aspx‟ page SessionVariable1.aspx
<html>
<script language="C#" runat="server">
void Page_Load(Object Sender, EventArgs e) {
Response.Write("<u><b><center>Logon authentication using Session variables</center></b></u><br><br>");
(44)Exploring ASP.NET / Session / 44 of 54
SessionVariable1.aspx Contd…
void WritingSesVar(Object Sender, EventArgs e) {
Session["Name"] = txtUserName.Text; Session["Password"] = txtPassword.Value; lblMessage.Text = "Session variables stored"; }
void ReadingSesVar(Object Sender, EventArgs E) {
Response.Redirect("SessionVariableRedirected.aspx"); }
</script>
<form runat="server"> User name :
<asp:TextBox id = "txtUserName" runat="server" /><br><br> Password :
(45)SessionVariableRedirected.aspx
<asp:button id="btnStoreVar" text="Store in Session Variables" onclick="WritingSesVar" runat="server" /> <asp:button id="btnReadVar" text="Read Session Variables" onclick="ReadingSesVar" runat="server" /> <br><br>
<asp:Label id = "lblMessage" runat="server" /><br><br>
</form> </html>
SessionVariableRedirected.aspx
<html>
<title>Redirected Page</title>
(46)Exploring ASP.NET / Session / 46 of 54
SessionVariableRedirected.aspx
void Page_Load(Object Sender, EventArgs E) {
Response.Write("<u><b><center>Logon authentication using Session variables</center></b></u><br><br>");
lblMessage1.Text = "User Name : " + (String)Session ["Name"];
lblMessage2.Text = "Password : " + (String)Session["Password"];
}
</script>
<form runat="server">
<asp:Label id = "lblMessage1" runat="server" /> <br><br> <asp:Label id = "lblMessage2" runat="server" /> <br><br> </form>
(47)(48)Exploring ASP.NET / Session / 48 of 54
Session Event and Properties
Property Description
SessionID Unique user session identifier
TimeOut User timeout
LCID Local identifier
IsNewSession Returns TRUE if the session has been created with
the current request
Item Name of a session value
Count Number of items in the session state collection
(49)Session Object Example
<HTML>
<script language="C#" runat="server"> void Page_Load (Object Src, EventArgs E) {
Response.Write("<b><u><center>Use of LCID</b></u></center><br>");
DateTime dt;
dt = DateTime.Now; int due = 500;
Response.Write ("Today's date is : " + dt.ToShortDateString() + "<br><br>");
Response.Write ("The total amount due is " + due.ToString ("C") ); }
(50)Exploring ASP.NET / Session / 50 of 54
(51)Session Object Example Modified
<HTML>
<title>Session – LCID French</title>
<script language="C#" runat="server"> void Page_Load(Object Src, EventArgs e) {
Response.Write("<b><u><center>Change of LCID </b> </u> </center> <br>");
Session.LCID =0x040C; DateTime dt;
dt = DateTime.Now; int due = 500;
(52)Exploring ASP.NET / Session / 52 of 54
Session Object Output
Response.Write ("The total amount due is : " + due.ToString ("C")) ;
}
(53)Summary
An ASP.NET application is a collection of all the ASP.NET pages, aspx
files, and various other files that are required to provide the essential functionality of the application
When an instance of the HttpApplication class is created, a few events,
such as, Application_Start, are fired The event-handlers for these events are stored in a file called Global.asax
The Application object is a built-in ASP.NET object that represents an
instance of the ASP.NET application
In ASP.NET, variables can have two levels of scope:
Page-Level Variables Object-level Variables
Object-level variables are of two types:
Application-level variables Session-level variables
To ensure that application-level variables are not updated by more
(54)Exploring ASP.NET / Session / 54 of 54
Summary Contd…
The Server object acts as an interface to the HTTP service, and
exposes properties and methods of the HTTP server
The Server object has many methods that are used to control various
features of the web server Some of these methods are:
Execute and Transfer() HTMLEncode()
UrlEncode() MapPath()
The Session object is used to store information about a user, that is