0% found this document useful (0 votes)
23 views

Faltu

The document discusses objects used for client-server communication in ASP.NET including the request, response, server, and application objects. It describes the collections, properties, and methods of each object.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Faltu

The document discusses objects used for client-server communication in ASP.NET including the request, response, server, and application objects. It describes the collections, properties, and methods of each object.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

The Mandvi Education Society

BBA, BCA AND SCIENCE COLLEGE


Subject: ASP.NET(505)
Unit4 Client Server Communication

4.1 Communication with Web Browser

Web browsers like internet explorer, chrome, fire fox etc.. and web
servers function together as a client-server system. Client-Server is a
standard method for designing applications where data is kept in server
computers and efficiently shared with any number of the clients on
request. All web browser function as clients that request information
from servers. Numerous web browser clients can request for
information from the same website. Requests can happen at all different
times or simultaneously. Client-server systems conceptually request for
all requests to the same site to be handled by one server, because the
volume of requests to web servers can grow very large, web servers are
often built as a distributed pool of server computers.

For websites popular in different countries around the world, webserver


pool is geographically distributed to improve the response time to web
browsers. If the server is closer to the requesting device (client), the time
it takes to deliver the content is faster than the server settled far away.
ASP.NET web application in order to communicate with web browser
and web server majorly make use of following objects.

1. Request Object
2. Response Object

P a g e 1 | 26
3. Session Object
4. Application Object
5. Server Object

Image1

4.2 Objects for Client Server Communication

4.2.1 Request Object

Request object is used to retrieve information from a user. It is an


instance of the System.Web.HttpRequest class. Request object’s
collections, properties and methods are described below:

Collection of Request Object

Collection Description
ClientCertificate It contains all the field values stored in the client
certificate.

P a g e 2 | 26
Cookies It contains all the cookie values sent in a HTTP
request.
Form It contains all the form (input) values from a web
form that uses the post method.
QueryString It contains all the variable values in a HTTP query
string.
ServerVariables It contains all the server variable values.
Table 1: Collection of Request Object

Properties of Request Object

Property Description
ApplicationPath It gets the virtual application root path
on the server.
Browser It gets or sets information about the
requesting client’s browser capabilities.
CurrentExecutionFilePath It requests the current execution path.
FilePath It gets the virtual path of the current
request.
HttpMethod It gets the HTTP data transfer method
(such as GET,POST or HEAD) used by the
client.
TotalBytes It gets the number of bytes in the current
input stream.

P a g e 3 | 26
UserAgent It gets the raw user agent string of the
client browser.
UserHostAddress It gets IP host Address of the remote
client.
Table : Properties of Request Object

Method of Request Object

Method Description
BinaryRead It performs a binary read of a specified
number of bytes from the current input
stream.
Equals(Object) It determines whether the specified object is
equal to the current object.
GetType It gets the type of the current instance.
MapimageCoordinates It maps an incoming image-field form
parameter to appropriate x-coordinate and
y-coordinate values.
MapPath(String) It maps the specified virtual path to a
physical path.
SaveAs It saves an HTTP request to disk.
ToString It returns a String the represents the current
object.

P a g e 4 | 26
ValidateInput It cause validation to occur for the collections
accessed through the cookies, form and
QueryString properties.
Table 3: Methods of Request Object

4.2.2 Response Object

Response object is used to provide output to the user from the server.
ASP.NET provides a class called HttpResponse which is defined in the
namespace called System.web. Response object’s collection, properties
and methods are described below:

Collection of Response Object

Collection Description
Cookies It sets a cookies value. If the cookie does not exist, it
will be created and take the value that is specified.
Table 4: Collection of Response Object

Properties of Response Object

Property Description
Buffer It specifies whether to buffer the page output or not.
CacheControl It sets whether a proxy server can cache the output
generated by ASP or not.
Charset It appends the name of a character set to the content
type header in the response object.
ContentType It sets the HTTP content for the response object.

P a g e 5 | 26
Expires It sets how long (in minutes) a page will be cached on a
browser before it expires.
ExpiresAbsolute It sets a data and time when a page cached on a
browser will expire.
IsClientConnected It indicates whether the client has disconnected from
the server.
Pics It appends a value to the PICS label response header.
Status It specifies the value of the status line returned by the
server.
Table 5: Properties of Response Object

Methods of Response Object

Method Description
AddHeader It adds a new HTTP header and a value to the HTTP
response.
AppendToLog It adds a string to the end of the server log entry.
BinaryWrite It writes data directly to the output without any
character conversion.
Clear It clears any buffered HTML output.
End It stops processing a script and returns the current
result.
Flush It sends buffered HTML output immediately.
Redirect It redirects the user to a different/provided URL
Write It writes a specified string to the output.
Table 6: Methods of Response

P a g e 6 | 26
4.2.3 Server Object

The ASP.NET Server object is used to access properties and methods of


the server. Server object’s properties and methods are described below:

Property Description
ScriptTimeout It sets or returns the maximum number of seconds a
script can run before it gets terminated.
Table 7: Properties of server object

Methods of Server Object

Method Description
CreateObject It creates an instance of an object.
Execute It executes an ASP file from inside another ASP file.
GetLastError() It returns an ASPError object that describes the error
condition occurred.
HTMLEncode It applies HTML encoding to a specified string.
MapPath It maps a specified path to a physical path.
Transfer It sends (transfers) all the information created in one
ASP file to a second ASP file.
URLEncode It applies URL encoding rules to a specified string.
Table 8: Methods of Server Object

4.2.4 Application Object:

An application on the web may consists of many ASP files that work
together to perform some task. The application object is used to bind
these ASP files together.

P a g e 7 | 26
The Application object is used to store, access and retrieve variables
from any page, same as the session object. The only difference is that
ALL users share ONE Application object AND with session there is ONE
session object for EACH user.

The Application object holds information that will be used by many ASP
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 be automatically reflected on
all pages.

The application object’s collections, methods and events are described


below:

Collections Of Application Object

Collection Description
Contents It contains all the items appended to the application
through a script command.
StaticObjects It contains all the objects appended to the application
with the HTML tag.
Table 9: collection of Application Object

Methods of Application Object

Method Description
Contents.Remove It deletes an item from the contents
collection.

P a g e 8 | 26
Contents.RemoveAll() It deletes all items from the contents
collection.
Lock It orevents other users from modifying the
variable in the Application object.
Unlock It enables other users to modify the variables
in the Application object (after it has been
locked using the Lock method)
Table 10: Methods of Application Object

Events for Application Object

Event Description
Application_OnEnd This event occurs when all user sessions are
over and the application ends.
Application_OnStart This event occurs before the new session is
created ( when the Application object is first
referenced).
Table 11: Events of Application Object

4.2.5 Session Object

The session object stores information about user session and can change
settings for a user session.

Variables stored in a session object hold information about one single


user, and are available to all ASP pages in one application. Common
information stored in session variable are id, name and preference. The

P a g e 9 | 26
server creates a new session object for every new user and destroys the
session object when the session expires.

The session object’s collections, properties, methods and events are


described below:

Collection of Session Object.

Collection Description
Contents It contains all the items appended to the session
by a script command.
StaticObjects It contains all the objects appended to the session
with the HTML tag.
Table 12: Collection of Session Object

Properties of session object

Property Description
CodePage It specifies the character set that is used while
displaying dynamic content.
LCID It sets or returns an integer that specifies a
location or region. Contents like date and time,
currency will be displayed according to that
location or region.
SessionID It returns a unique identification(ID) for each user.
The unique ID is generated by the server.

P a g e 10 | 26
Timeout It sets or returns the timeout period in minutes
for the session object in application.
Table 13: Properties of Session Object

Methods of Session Object

Method Description
Abandon It destroys a user session
Contents.Remove It deletes an item(one item) from the
contents collection.
Contents.RemoveAll() It deletes all items from the contents
collection.
Table 14: Methods of session object

Events of Session Object

Event Description
Session_OnEnd This event occurs when a session ends.
Session_OnStart This event occurs when a session stars.
Table 15: Events of Session Object

State Management Technique

The current value of all the controls and variables for the current user in
the current session is called the State. There needs to be some technique
to store the information between requests and to retrieve it when
required. ASP.NET includes several features that help you preserve data
by its State Management Capabilities. ASP.NET provides 2 options for
state management such as:

P a g e 11 | 26
1) Client-Based State Management
2) Server-Based State Management

1. Client-Side State Management

In Client-Side State Management Technique, the state related


information will directly get stored on the client-side. That specific
information will flow back and communicate with every request made by
the user.

Client-Side State Management Techniques are:

1. View State
2. Hidden Fields
3. Cookies
4. Query Strings

1. View State

View state is client side state management technique provided by


ASP.NET to store user’s information like sometimes the user needs to
store data temporarily after a post back. It stores data in the generated
HTML using hidden field not on the server.

View State provides page level client side state management which is as
long as the user is active on the current page, state is available and as the
user redirects to the next page and the current page state is lost. By
default view state is enabled for all server side controls of ASP.NET with
a property called EnableViewState set to true.

P a g e 12 | 26
Following is the example for view state to count how many times the
button is clicked:

ViewState Demo Count:

<asp:Label runat=”server” id=”lblcount” />

<asp:Button runat=”server” id=”Submit” onclick=”Submit_Click”


text=”show”>

Protected void Page_Load(object sender, EventArgs e)

if(IsPostBack)

if(ViewState[“count”] != null)

Int ViewstateVal = Convert.ToInt32(ViewState[“count”]) + 1;

lblcount.Text = ViewstateVal.ToString();

ViewState[“count”] = ViewstateVal.ToString();

Else

ViewState[“count”] = “1”;

P a g e 13 | 26
}

Protected void Submit_Click(object sender, EventArgs e)

lblcount.Text = ViewState[“count”].ToString();

Following is the example to set and get user information of view state.

//to set user information:

If(ViewState[“UserName”] != null)

lblName.Text = ViewState[“UserName”].ToString();

//To get user information

ViewState[“UserName”] = txtUserName.Text;

2.Hidden Fields

ASP.NET provides Hidden field is a control which is used to store small


amounts of data at client side. It stores one value for the variable and it is
preferred to use when a variable’s value is changed frequently.

Hidden field control is not displayed to the client and it is invisible on the
browser.

P a g e 14 | 26
Following is the example for hidden field is as follows:

If (HiddenField1.Value != null)

int num = convert.ToInt32(HiddenField1.Value) + 1;

HiddenField1.Value = num.ToString();

Label1.Text = num.ToString();

4.3 Cookies

“A cookie is a small file capable of storing user information”. Cookies do


not use server memory. “A small text file created by the client’s browser
and stored on the client hard disk by the browser is called Cookie”.
System.Web.HttpCookie namespace is required to create and access
cookies in ASP.NET web applications.

Whenever a user makes a request for a page the first time, the server
creates a cookie and sends it to the client along with the request of page
and the client browser receives that cookie and stores it on the client
machine either temporarily or permanently (persistent or non-
persistentce).

When the next time the user makes a request for the same site for the
same or another page, the browser checks for cookie for that site in the

P a g e 15 | 26
folder. If the cookie already exists it sends a request with the same
cookie, else that request is considered as a new request.

Cookie have following properties:

Property Description
Domain It is used to associate cookies to domain.
Secure To enable secure cookie to set true (HTTPs).
Value To manipulate individual cookie value.
Values To manipulate cookies with key/value pair.
Expires It is used to set expire data for the cookies.
Table 16: Properties of Cookies

Advantages of Cookie

1. It is clear text so user is able read it.


2. It helps us to store user preference information like Username,
Password, City and PhoneNo etc on the client machine.
3. It is easy way to maintain user’s information.
4. Cookies are fast accessing.

Disadvantages of Cookie

1. If user clear cookie information we can’t get it back again.


2. No security.
3. Each user request will have cookie information with page.

There are two types of Cookies:

4.3.1. Persistence Cookie:

P a g e 16 | 26
Cookies set with an expiry date time are called persistence cookies.
Persistence cookies are permanently stored until the time expires.
These remain on hard drive until you erase them or cookies get
expire.

Following is the syntax for creating persistence cookies:

HttpCookie ck = new HttpCookie(“Persistance”);

ck.Value = “This is A Persistence Cookie”;

//set expiry time.

ck.Expires = DateTime.Now.AddSeconds(10);

Response.Cookies.Add(ck);

4.3.2 Non-Persistence Cookie:

Non persistence cookies are temporarily stored on the user client


hard disk folder. It maintains user information as long as the user
access the same browser. When user closes the browser the cookie
will be discarded automatically. Non Persistence cookies are more
useful for public computers. Non-persistence cookie are stored in
RAM on the client and are destroyed when the browser is closed by
user.

Following is the syntax for creating Non-persistence cookies:

HttpCookie ck = new HttpCookie(“NonPersistence”);

ck.Value = “This is A Non Persistance cookie”;

P a g e 17 | 26
Response.Cookies.Add(ck);

Thus cookie is a small but an important part of ASP.NET. Cookie can


store user information, session and application. It can be created
permanently and temporarily and they work with browser request.

4.4 Query String

A query string is use to send data from one web form to another
through the URL. A query string consists of two parts, 1. Field and 2.
Value and each of pair separated by ampersand (&) symbol. The
?(question mark) symbol in a query string indicates the beginning of a
query string and it’s value. There is a limit on the Query string length.
Hence, Query strings cannot be used to send more than 100kb data.

Query string are clearly visible to the user, so sensitive or private data
such as a username and password should not be send through query
string, unless the data are encrypted. To retrieve the query string
value, Request object’s QueryString property is used.

Note: if you want to send large amounts of data (beyond 100kb) the
Request.QueryString cannot be used.

Syntax of Query String

Request.QueryString(variable) [(index)|.Count]

Parameter Description

P a g e 18 | 26
Variable Required. The name of the variable in the HTTP query
string to retrieve
Index Optional. Specifies one of multiple values for a variable.
From 1 to Request.QueryString(variable).count
Table 17: Parameters of Query String

Following is the example of query string:

Sender side code:

Coding for Query String

//On submit button click

protected void Button1_Click(object sender, EventArgs e)

Response.Redirect(“~/Contact.aspx?Name=”+ TextBox1.Text +
”&Age=” +TextBox2.Text);

Reciever Side code:

Coding for Query String

//Retrieving the values of query string

protected void Page_Load(object sender, EventArgs e)

Label2.Text = “Welcome” + Request.QueryString[“Name”];

Label3.Text = “Your Age is” + Request.QueryString[“Age”];

P a g e 19 | 26
}

Thus, QueryString are used to pass the data (limited data through
URL) from one page to another page.

2. Server Side State Management Techniques:

In this technique, the user state information is stored on the server.


Server-side state management techniques are:

1. Session Management and Variable scope


2. Application
3. User Profile
4. Cache

1. Session Management and Variable scope:

“The time duration for which the user interacts with the web application
is called session”. In ASP.NET session is a state that is used to store and
retrieve values of a user. In ASP.NET, Session in the instance of
HttpSessionState Class.

The server maintains the state of user’s information by using a session


ID. When user makes a request without a session ID, ASP.NET first
creates a session ID and then sends it with every request and response to
and for the same user.

ASP.NET Session Events:

P a g e 20 | 26
There are 2 types of events available in ASP.NET. We can handle both
session in a global.asax file.

1. Session_Start(): When the new session is initialized then the


session_start event is invoked.
2. Session_end(): When the session is expires then the Session_End
event is invoked.

ASP.NET Session Modes:

The session is stored in the following for ways in ASP.NET.

1. InProcMode: It is a default session mode and a value store in web


server memory (IIS). In this the session values are stored with
server start and it ends when the server is restarted.
2. State Server Mode: In this mode session data is stored in separate
server.
3. SQL Server Mode: In this session is stored in the database. It is a
secure mode.
4. Custom Mode: Generally, session data is stored in InProc, SQL
server, State server, etc. ASP.NET allows session data to be stored
with other new techniques developed by developer also.

Session Configuration

To configure the session management, we need to specify the settings in


the web.config file.

Typical settings in web.config looks like:

P a g e 21 | 26
<sessionState mode = “InProc”

stateConnectionString=”tcpip=127.0.0.1:42424”

sqlConnetionString=”Data Source=.\SQLEXPRESS;
Trusted_Connection=Yes;”

cookieless=”false”

timeout=”100”/>

Session Attributes are described as follows:

Attribute Description
Mode It specifies the type of session mode to be
used. It could be InProc, SQLServer and
StateServer
stateConnectionString It specifies the location of the server that is
handling the session data.
sqlConnectionString Is specifies the database connection string
that will store the session data.
Cookieless It specifies whether cookies are to be used to
identify sessions or session information are
to be appended in URL. It could be true or
false.
Timeout It specifies the time for which the session
should be active. Once the time is up, session
will be expired.
Table 18: Session Attributes

P a g e 22 | 26
Syntax for session object:

Session[“key”]=value

This stores the value in a session object and the “key” part is use to give
the value a name. This allows the value to be retrieved later on. To
retrieve a value, you can simply issue the below statement.

Session[“key”]

Following is the example for session:

Sender Side Code:

protected void btnLogin_Click(object sender, EventArgs e)

Session[“userId”] = txtUserId.Text;

Response.Redirect(“AdminHome.aspx”);

Receiver Side Code

Response.Write(Session[“UserId”].ToString());

2. Application:

ASP.NET provides application state through the HttpApplicationState


class as a way of storing global application-specific information that is
visible to the entire application. Application-state variables are global
variables for an ASP.NET application. Application-specific values are

P a g e 23 | 26
stored in applications state which are then managed by the server. Data
that are shared by multiple sessions and does not change very often are
stored into application-state variables. For example shared lists, default
user options, counters etc.

There are three events for Application state as follows:

1. Application_Start: This event begins when the domain started.


Void Application_Start(object sender, EventArgs e)
{
Application[“AppstartMessage”] = ”welcome to website”;
}
2. Applicaton_Error: This event manages the unhandled exception
error.
Void Application_Error(object sender, EventArgs e)
{
//write an unhandled error code exception
}
3. Application_End: This events is invoked when domain stops.
Void Application_End(object sender, EventArgs e)
{
Application[“AppEndMessage”] = “Application Closed”;
}

P a g e 24 | 26
3.User Profile:

ASP.NET provides a feature known as profile properties, which allows


you to store user-specific information. Session data is lost when the
visitor leaves the web page. User profile is use to persist all the user
information for a long time.

It is similar to session state but unlike session state, the profile data are
not lost when a user’s session expires. The profile properties feature
uses an ASP.NET profile, which is stored in a persistent format and
associated with an individual user. In this each user has its own profile
object.

4.Cache

Caching is a technique of storing frequently used information of user in


memory, so that, when the same information is needed by user next
time, it could directly retrieved from the memory instead of being
generation by the application. Caching is very important for performance
boosting in ASP.NET, as the pages and controls are dynamically
generated. It is especially important for data related transactions,
response time is very crucial.

Cache is stored on server side and it implements Page Caching and data
caching both. Cache is use to set expiration polices. Following is the
example of Cache expiration polices:

Response.Cache.SetExpiresTime(DateTime.Now.AddDays(1));

P a g e 25 | 26
Thus, the Client Server Communication system in ASP.NET Automatically
maintains records of login/logout time of the users and maintain both
online as well as offline messages. It tries to automate the entire process
with database integration.

P a g e 26 | 26

You might also like