79
ASP.NET Intrinsic Objects Main Menu 1 of 79 ASP.NET Intrinsic Objects

Chapter 9 - ASP.NET Intrinsic Objects

Embed Size (px)

Citation preview

Page 1: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 1 of 79

ASP.NET Intrinsic Objects

Page 2: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 2 of 79

Objective

At the end of this chapter, you will be able to

understand the object model of ASP.NET.

You will also be able to understand how we can

work with the objects available in object model

through various methods and properties.

Page 3: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 3 of 79

Scope

ASP.NET Object Model

• Design Model

Request object

• Properties and Methods

• QueryString Collection

• Form Collection

• ServerVariables collection

Response object

• Properties and Methods

• Write Method

• Redirect Method

Page 4: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 4 of 79

Scope

Cookies

• Understanding Cookies

• Cookies Base Class

Server Object

• Properties and Methods

• ScriptTimeOut

• HtmlEncode and UrlEncode

• HtmlDecode and UrlDecode

Session Object

• Properties and Methods

• Session Variables

Page 5: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 5 of 79

Scope

Application Object

• Properties and Methods

• Application Variables

Global.asax

• Events in Global.asax

• Sequence of events

• Application and Session Events

Page 6: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 6 of 79

ASP.NET Object Model

Sending data based on simple decisions may either be dynamic or active.

A dynamic content is generated on the server and sent to client.

While active content interacts with the user in real time.

Visitors to the web site are passive receptors of information.

Their only control over the information path they follow is defined by the links they click in the pages.

Page 7: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 7 of 79

ASP.NET Object Model

Traditionally, a web browser communicates with

web server through forms, a method whereby

information was sent to a server side program.

The program could then examine this information

and produce a new HTML document to be sent back

to the client who has initiated the request.

Alternatively, the page might contain hyperlinks that

include information about the user’s selections.

Page 8: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 8 of 79

Design Model The ASP.NET is a lot more structured technology

than ASP.

Here the complete ancestral line of every single class/ Property can be traced back to its origin.

The ASP.NET intrinsic objects are available to the Page Class by virtue of inheritance from a namespace called “System.Web”.

Every intrinsic ASP.NET object maps to a class provided by System.Web namespace which supplies classes and interfaces that enable browser/server communication. System.

Page 9: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 9 of 79

Design Model

Web also includes classes for cookie manipulation, file transfer, exception information, and output cache control.

The ASP.NET core engine provides six built-in objects that we can use in our server programs.

These objects are made available to us in form of properties of the Page class.

These objects can be directly accessed with the Object name eg. Response.write(“Hello”), it is equivalent to writing Page.Response.Write(“Hello”)

Page 10: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 10 of 79

Design Model

The ASP.NET built-in objects have their own properties and methods.

There are some important concepts to note when using the model as offered by ASP.NET.

First, multiple applications can run on the same server.

An application consists of a set of script files, HTML documents, images etc. and all stored in the virtual directory.

This is called virtual mapping.

Page 11: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 11 of 79

Request Object

The Server is always passive in a client-server environment.

When the client sends a request for a URL, at this time the server traps the data sent by the client with help of the Request object and responds by sending the requested page to the client’s browser.

The Request object provides the developer all the information about the user’s request to the site or application on the server.

It enables type-safe browser to server communication.

Page 12: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 12 of 79

Request Object

Any information sent by the browser to the server can be retrieved by Request object.

The Request object’s Form collection is used to store the information provided by the user in a web page.

The Request objects provide various collections (such as QueryString, Form etc.), methods and properties.

A collection is a data structure, rather like an array (but it is more powerful), which can store values by linking each one to a unique key.

Page 13: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 13 of 79

Properties and Methods

Request object provides set of properties that store a

variety of information.

All the values are read-only, and the information is

just copy of the request made by the browser.

We will now discuss some of the properties.

Page 14: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 14 of 79

QueryString Collection

QueryString is a collection of QueryString variables.

It is populated when the method for a form is GET or the values are appended to the URL as a query string.

There are basically two ways that the browser can send specific information to the server.

The information can come from FORM section (<FORM> tag) on the page using POST method or can be appended directly to the end of URL as a query string using GET method.

Page 15: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 15 of 79

QueryString Collection

Let’s make an example

Design the form as shown below.

Page 16: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 16 of 79

QueryString Collection

Now click on the HTML view and set the method

attribute of the form tag to “Get” (it s Post by

default).

Set the visible property of the table to false in the

page load event by writing the following code.

Table1.visible=false

Write the following code in button1_Click event

Page 17: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 17 of 79

Dim usrName As String

Dim usrPwd As String

usrName = Request.QueryString("txtName")

usrPwd = Request.QueryString("txtPwd")

Table1.Rows(0).Cells(0).Text = "Name"

Table1.Rows(0).Cells(1).Text = "Password"

Table1.Rows(1).Cells(0).Text = usrName

Table1.Rows(1).Cells(1).Text = usrPwd

Table1.Visible = True

QueryString Collection

Page 18: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 18 of 79

QueryString Collection

Save and Run the project to get the following output.

Page 19: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 19 of 79

Form Collection

This is a second way of sending data from the

browser to the server.

Instead of using GET in the method attribute of

form, we can use POST method.

Using POST method, buries the information inside

the HTTP header rather than adding it to the URL as

a query string.

This is the default method which is used by VB.NET

web forms.

Page 20: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 20 of 79

Form Collection

Lets us see now with an example how we capture

the data using Form collection of Request object:

In the form that you created for the previous

example make the following changes:-

In the HTML view change the method back to

“Post”.

In the button1_click event write the following

code (please note that only the collection name has

changed)

Page 21: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 21 of 79

Dim usrName As String

Dim usrPwd As String

usrName = Request.Form("txtName")

usrPwd = Request.Form("txtPwd")

Table1.Rows(0).Cells(0).Text = "Name"

Table1.Rows(0).Cells(1).Text = "Password"

Table1.Rows(1).Cells(0).Text = usrName

Table1.Rows(1).Cells(1).Text = usrPwd

Table1.Visible = True

Form Collection

Page 22: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 22 of 79

Form Collection

Save and Run the project.

You will notice that the output is just the same except for the URL.

When this page is submitted, the names and values of the text boxes are encoded into the request header, and there is no sign of them in the browser’s address box.

This time in the second file (given below), the values of the request can’t be accessed through QueryString collection.

Page 23: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 23 of 79

ServerVariables Collection

ServerVariables collection exposes a collection of

various server variables, which are used to extract

information sent from the client.

This collection has little to do with the client

request, much of the information that we worked

with the other collections actually originates from it.

Any HTTP header sent by the client browser is

available in this collection and we can view

information through ASP.NET code like this:

Page 24: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 24 of 79

ServerVariables Collection variable =

Request.ServerVariables(“HeaderType”)

This variable now contains the value of the Header as passed by us in the ServerVariables collection as a parameter.

We can now either display this value or apply some business logic based on the information available.

The standard HTTP headers are automatically defined as members of the ServerVariables collection.

Page 25: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 25 of 79

ServerVariables Collection

For example if we want to know the method using which form data is sent to the server, we could use the following line of code:

<% =

Request.ServerVariables(“REQUEST_METHOD”)

%>

This will return the method either GET or POST, depending on how data were sent from the browser.

We can also use QUERY_STRING header to obtain the original unadulterated query string that was pass to the server from the client browser.

Page 26: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 26 of 79

ServerVariables Collection

There is a list available of the HTTP headers, which

are available in the ServerVariables collection.

Let’s understand this with help of an example.

Open a new web form and write the following code

in the Page_Load event.

Dim x As String

Response.Write("<table border=2>")

For Each x In Request.ServerVariables

Response.Write("<tr><td>")

Page 27: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 27 of 79

Response.Write("<br> " & x & "</td><td>“

&Request.ServerVariables(x))

Response.Write("</tr>")

Next

Response.Write("</table>")

Response.Write(Request.ServerVariables.Count)

Save and Run the project and all the ServerVariables

are displayed with their values.

ServerVariables Collection

Page 28: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 28 of 79

ServerVariables Collection

Page 29: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 29 of 79

Response Object

Response object is used to send information and the output of scripts to the browser.

It is also used to control the execution of the script.

The Response object handles all the data and messages that we want to send back to the browser.

Response object implements only one collection (Cookies).

There are other properties and methods available with the help of which we can manipulate with Response object.

Page 30: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 30 of 79

Write Method

The Write method inserts a string into the HTML stream that the browser receives.

Response.Write(“Welcome to site” &

strValue)

Let’s see this with the help of example that displays some text in a loop.

Open a new web form and write the following code in the Page_load event.

Dim x As Integer

Response.Write("<center>")

For x = 1 To 6

Page 31: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 31 of 79

Write Method Response.Write("<H" & x & ">")

Response.Write("Response")

Response.Write("</H>")

Next

Response.Write("</center>")

Save and run the project a text “Response” is displayed 6 times. But every time the output will be different as it will be displayed with the heading tag in the decrement order. The output of the above code will be as follows:

Page 32: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 32 of 79

Write Method

Page 33: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 33 of 79

Redirect Method

A particular useful example of Response object is redirect, which we can use to refer to other web page.

When the user loads a page that specifies a redirection, his or her browser loads a new page, which is been specified in the redirect method.

Depending on the contents of the ASP.NET file itself, the actual redirection can occur as soon as redirection line is interpreted by ASP.NET core engine.

Page 34: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 34 of 79

Redirect Method

One of the things that a client can receive is a redirection header, which tells the browser to get the information elsewhere.

The HTTP headers are already written to the client browser by the IIS.

We must do any HTTP header modification before writing page content because it must be done before IIS begins sending content.

Let us understand the working of the Response.Redirect method with help of an example.

Page 35: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 35 of 79

Redirect Method

Design a page as shown below:

Put both Radio Buttons in the same group by

providing same name in the GroupName property.

Page 36: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 36 of 79

Redirect Method

Write the following code in the button1_Click event

If RadioButton1.Checked = True Then

Response.Redirect("http://localhost/locat

ions/delhi.htm")

Else

Response.Redirect("http://localhost/locat

ions/mumbai.htm")

End If

Page 37: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 37 of 79

Redirect Method

Save and run the project. Select one of the options,

say “Delhi” and click on the button “Go…”.The

Delhi page will open in the browser window.

Page 38: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 38 of 79

Cookies

Cookie is a file used to store data on the client’s system.

The web server inserts small piece of information into these files.

In other words, a cookie is a packet of information sent by browser to the server with each request.

The cookie is stored as a file on the client machine, which means that it can be used to store information that is available the next time browser starts.

Data items within each cookie are available in the Cookies Collection.

Page 39: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 39 of 79

Cookies

You can access cookies in the same way you access

QueryString and Form collection in Request object.

Cookies are written using Response object and are

accessed through Request object in this case these

are read-only since the information they represent is

actually held on the client browser and not the

server.

Cookies can also be changed using Response object.

Page 40: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 40 of 79

Cookies Base Class

Cookies also find a representation in System.Web

namespace.

The hierarchy is as follows:

Let us understand this with an example:

Page 41: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 41 of 79

Cookies Base Class

Design the page as shown in the figure.

Page 42: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 42 of 79

Cookies Base Class

Write the following code in the Click event of btnCreate button control.

Dim MyCookie As New

HttpCookie("LastVisitedOn")

MyCookie.Value = CStr(DateTime.Now())

Response.Cookies.Add(MyCookie)

Write the following code in the Click event of btnFetch button control.

Dim i As Integer

Dim arr() As String

Dim CookieColl As HttpCookieCollection

Page 43: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 43 of 79

Dim Cookie As HttpCookie

CookieColl = Request.Cookies

arr = CookieColl.AllKeys

For i = 0 To arr.GetUpperBound(0)

Cookie = CookieColl(arr(i))

Response.Write("Cookie: " & Cookie.Name &

"<br>")

Response.Write("Value: " & Cookie.Value &

"<br>")

Next

Cookies Base Class

Page 44: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 44 of 79

Cookies Base Class

Save and run the project to see the following output.

Page 45: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 45 of 79

Cookies Base Class

In this example when you click on the “Create

Cookie” button, it creates a cookie by creating an

instance of “HttpCookie” class and passing the name

of cookie in its constructor.

After this we set the value of the cookie by setting

the “value” property of this class.

Finally the cookie is added to the cookies collection

using the “Response.Cookies.Add()”

method.

Page 46: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 46 of 79

Server object

The Server object provides a number of methods that are used to carry out routine tasks while processing the page.

Such as converting strings into the format for use in HTML, or creating instances of COM components on the Server.

The Server object is implemented in ASP.NET by the HttpServerUtility class which is found in System.Web namespace.

Let us understand some of the properties in details:

Page 47: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 47 of 79

ScriptTimeOut

ScriptTimeout property is set by default to 90

seconds, a long time for the user to be staring at the

screen waiting for something to happen.

We can read and change the timeout period using

ScriptTimeout property.

Given below is the way in which we can handle this

property.

<% Server.ScriptTimeout= 10 %>

Page 48: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 48 of 79

HTMLEncode and URLEncode

ASP.NET provides two very useful methods to encode your strings, which you wish to send to the server with the URL of the page.

Let’s take a look at an example.

We want to display the following string.

StrText = “This is a <this>” & name & “

to check error”;

To display this string as part of the page, rather then having it to execute on the server, we have to replace the angle brackets with an escape sequence that the browser can understand.

Page 49: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 49 of 79

HTMLEncode and URLEncode

Two escape sequences are &lt and &gt which produces < and > symbols.

We have a method in server object HtmlEncode, which takes a string of text and converts any illegal characters contained in it, to its appropriate HTML escape sequence.

For example to produce the text <table> on our page, without this string being interpreted as an opening table tag, we could use this method.

Response.Write(Server.HTMLEncode

(“This is example of <table> tag”))

Page 50: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 50 of 79

HTMLEncode and URLEncode

There is another method called URLEncode which is far more refined than this and does all the encoding and decoding of the string or the URL passes to it.

This method takes a string of information and converts it into URL-encode form rather than HTML.

All the spaces are replaced by + symbol and certain other characters which hold a special meaning to the QueryString are replaced by percent signs combined with their ANSI equivalents in hexadecimal.

Page 51: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 51 of 79

HTMLEncode and URLEncode

URLEncode can translate a string into a correct

format for use in a QueryString.

If we are creating hyperlinks in our code, we can use

URLEncode to ensure that they are correctly

formatted:

Response.Write(server.URLEncode

(“http//localhost/first/display.asp

x?color=blue”))

Page 52: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 52 of 79

HTMLDecode and URLDecode

These methods decode the encoded string or the

URL to its original form.

Let us understand this with help of an example.

Design the web form as shown.

Page 53: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 53 of 79

HTMLDecode and URLDecode

Write the following line in click event of Encode button

lblEncode.Text =

Server.UrlEncode(TextBox1.Text)

Write the following line in click event of Decode button

lblDecode.Text =

Server.UrlDecode(TextBox1.Text)

Save and run the project. Now try with various URLs.

Page 54: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 54 of 79

HTMLDecode and URLDecode

Page 55: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 55 of 79

Session Object

A session is said to begin when a user logs-on to a site and finishes when he logs-off.

Session is dedicated data storage for each user within an ASP.NET application.

It stores data in Key-value combinations.

A variable declared with session scope will remain visible to all the pages of a web site.

Each user will have a different set of session variable with them thus the state of the user can be maintained.

Page 56: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 56 of 79

Session Object

In ASP.NET, sessions can be maintained even

without cookies (though the default mode is still

with cookies – this is achieved with Cookieless

property of the session object).

Session state is maintained in ASP.NET with help of

HttpSessionState class which is found in

System.Web namespace.

Page 57: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 57 of 79

Session Variables

A session variable is declared and initialized as follows :

Session(“UsrName”) = txtName.Text

This declares a variable “UsrName” this variable takes the values of the textbox that accepts the name of the user.

This variable will hold a different value for each user.

This helps us in customizing the pages of our website according to the values entered by the user.

Here is an example:

Page 58: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 58 of 79

Session Variables

Design the Web form as shown

Write the following code in the Click of the button

Session("UsrName") = txtName.Text

Response.Redirect("WebForm2.aspx")

Page 59: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 59 of 79

Session Variables

Add another web form (as WebForm2.aspx) in the

project and write the following code in the

Page_Load event.

Response.Write("<H1> You are

welcome " & Session("UsrName") &

"</H1>")

Save and run the project.

Page 60: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 60 of 79

Session Variables

Enter your name in the text box (txtName) and click

on the button.This will fire the code in button1_click

event handler and store your name in the session

variable and redirect to another page.See that the

second page is able to access the session variable

value and customize accordingly.

Page 61: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 61 of 79

Application Object

This object is also used to maintain state in the web.

When you want a variable to be accessible to all the

page of your Web Site and to all the users, declare

the variable as an Application variable.

The difference between the Session and Application

object is that an Application variable is visible to all

the users i.e., there is only one set for all the users.

If one updates it, it will be updated for all others.

Page 62: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 62 of 79

Application Object

ASP.NET application state handling is implemented by the HttpApplicationState Class which is found in the System.Web namespace

An 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.

A separate instance is created for each ASP.NET application on a Web server.

A reference to each instance is then exposed through the intrinsic Application object.

Page 63: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 63 of 79

Application Variables

It is a variable, which is declared with an application

scope is visible throughout the web site.

Declaring an Application variable is very simple:

Application(“HitCounter”)=0

This code declares a variable named “HitCounter”.

Ideal place for declaration of such variable is

global.asax file in the Application_onStart event

Page 64: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 64 of 79

Application Variables

Updating an Application variable:

Application.Lock()

Application(“HitCounter”)=Applicati

on(“HitCounter”)+1

Application.Unlock()

Here we are Locking the variable so that we have an

exclusive access to it and after updating the lock is

released by unlock method.

Page 65: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 65 of 79

Global.asax

The Global.asax file, also known as the ASP.NET

application file, is a file that contains code for

responding to application-level events raised by

ASP.NET.

This file resides in the root directory of an

ASP.NET-based application.

At run time, Global.asax is parsed and compiled into

a dynamically generated .NET Framework class

derived from the HttpApplication base class.

Page 66: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 66 of 79

Global.asax

The Global.asax file itself is configured so that any direct URL request for it is automatically rejected, it is very interesting to know that external users cannot download or view the code written within it.

You can create a Global.asax file either in a WYSIWYG designer such as Visual Studio.NET or in a notepad.

The Global.asax file is optional.

If you do not define the file, the ASP.NET page framework assumes that you have not defined any application or session event handlers.

Page 67: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 67 of 79

Global.asax

When you save changes to an active Global.asax file, the ASP.NET page framework detects that the file has been changed.

It completes all current requests for the application, sends the Application_OnEnd event to any listeners, and restarts the application domain.

When the next incoming request from a browser arrives, the ASP.NET page framework re-parses and recompiles the Global.asax file and raises the Application_OnStart event.

Page 68: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 68 of 79

Application and Session Events in

Global.asax In addition to page and control events, the ASP.NET

page framework provides ways for you to work with events that can be raised when your application starts or stops or when an individual user's session starts or stops:

Application events are raised for all requests to an application.

Let us understand these events with help of an example which give you a greater understanding of the use and relevance of the Application and Session objects.

Page 69: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 69 of 79

Open the Global.asax file and click on “click here to switch to code view” hyperlink to go the code view.

Write the following line in Application_Start event.

Application ("hits") = 0

Write the following code in Session_start event.

Application.Lock()

Application("hits") =

Application("hits") + 1

Application.UnLock()

Application and Session Events in

Global.asax

Page 70: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 70 of 79

Now open a web form and write the following line

in Page_Load event.

Response.Write("<H1> HITS = " &

Application("hits"))

Save and run the project three times. You will notice

that the number of hits increase in each user session.

Application and Session Events in

Global.asax

Page 71: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 71 of 79

Application and Session Events in

Global.asax

Page 72: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 72 of 79

Summary

Key points covered in this chapter are:

• ASP.NET object model enables us to collect information passed with the request so that we can use it in the script of the page we write.

• The ASP.NET Object Model provides us with various intrinsic objects, which have their own properties and methods.

• In ASP.NET each object is implemented internally by a base class and all the properties and methods of the base class.

• There objects available are Request, Response, Server, Session and Application.

Page 73: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 73 of 79

Summary

• These objects run on the server and are programmed using methods, properties and collections.

• Request object is used to gain access to the HTTP request data elements supplied by a client.

• Any information send by the browser to the server can be retrieved by Request object.

• QueryString is a collection of QueryString variables.

• QueryString is populated when the method for a form is GET or the values are appended to the URL as a query string.

Page 74: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 74 of 79

Summary • There are basically two ways that the browser can send

specific information to the server, POST method and GET method.

• Appending the query string to the end of the URL is a way GET method works.

• In QueryString, the amount of data we can send with the URL is limited to 1000 characters, as specified by the HTTP protocol specification.

• Using POST method buries the information inside the HTTP header rather than adding it to the URL as a query string.

• ServerVariables collection exposes a collection of various server variables, which are used to extract information send from the client.

Page 75: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 75 of 79

Summary

• Response object is used to send information and the

output of scripts to the browser.

• Response object’s Write method inserts a string into the

HTML stream that the browser receives.

• Using Request.Redirect method we can send the user from

one page to another by giving the name of the page as a

parameter.

• A cookie is a packet of information sent by browser to the

server with each request.

• The server object provides a series of methods that are

used to carry out routines tasks while processing the page

Page 76: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 76 of 79

Summary

• HtmlEncode, which takes strings of text and converts any

illegal characters it contains to the appropriate HTML

escape sequence.

• URLEncode, but it takes a string of information and

converts it into URL-encode form rather than HTML.

• Session object is used to customize the pages according to

the data supplied by the user. It is implemented by using

Session variables.

• Each user has a unique SessionID.

• Every user has its own set of session variables.

Page 77: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 77 of 79

Summary • In ASP.NET session object can be implemented even

without using cookies by setting the Cookieless property of the Session Object (this property was not available in ASP).

• Application object is used to declare and use those variables or objects that would be used throughout the web site and across users.

• Global.asax file contains various event handles and is a central place where every request comes before going to any page in the site

• Global.asax is a file which is the first file to execute be it starting of your Application or a user session or when a request comes or when you want to authenticate the credentials of user.

Page 78: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 78 of 79

Self Assessment

Fill in the blanks

1. The ________ object provides all information about

user’s request to server.

2. _________ returns virtual path of current request.

3. The servervariable _________________ returns the

server address

4. ________ Property contains the length of time before a

page cached on a browser expires.

5. ___________ Method is used to provide file-location

information for use in scripts.

Page 79: Chapter 9 - ASP.NET Intrinsic Objects

ASP.NET Intrinsic Objects

Main Menu 79 of 79

Self Assessment

State True or False:

• HTMLEncode can translate a string into a correct format for use in a query string

• Status contains the code of HTTP status line returned by the server

• QueryString can be used with both GET and POST

• SCRIPT_NAME servervariable returns physical path to the script

• Response.Flush stops processing the page.

• Response.Redirect can be use to link the pages

• First event to be fired when you upload your site and access the first page is Application_start.