Nav Raj Vinady - Net Centric Computing Note
Nav Raj Vinady - Net Centric Computing Note
Nav Raj Vinady - Net Centric Computing Note
Introduction
1. HTTP Protocol
1>HTTP is the foundation of data communication for the in the World Wide Web
2> HTTP functions as a request-response protocol in the client-server computing Model. In HTTP, a web
browser for example, acts as a client, while an application running on a computer hosting a website
functions as a server. The client submits an HTTP request message to the server. The server, which stores
content, or provides resources, such as HTML files or performs other functions on behalf of the client,
returns a response message to the client. A response contains completion status information about the
request and may contain any content requested by the client in its message body.
It is a stateless protocol, you send request and it responds does not maintain any state. To maintain the
state, we can use
A static web page (sometimes called a flat page) is a web page that is delivered to the user exactly as
stored, in contrast to dynamic web pages which are generated by a web application.
Consequently a static web page displays the same information for all users, from all contexts, subject to
modern capabilities of a web server to negotiate content-type or language of the document where such
versions are available and the server is configured to do so.
Static web pages are often HTML documents stored as files in the file system and made available by the
web server over HTTP.
Advantages
Disadvantages
Any personalization or interactivity has to run client-side (ie. in the browser), which is restricting.
Maintaining large numbers of static pages as files can be impractical without automated tools.
A dynamic web page is a kind of web page that has been prepared with recent information, for each
individual viewing. It changes with the time. For ex. News content, events. The content of the site
changes when the user logs in and logs out. Page contents are displayed according to the location of the
user. In facebook, you can see suggestions to add friends since it knows your friends and those are mostly
friend of your friends. Facebook gets updated with recent feeds etc.
1>Client-Side Scripting
Using client-side scripting to change interface behaviors within a specific web page, in response to mouse
or keyboard actions or at specified timing events. In this case the dynamic behavior occurs within the
presentation.
Client-Side scripting languages like JavaScript or Actionscript, used for DHTML and Flash technologies
respectively, are frequently used to play with the media types (sound, animations, changing text, etc.) of
the presentation
The Client-side content is generated on the user's computer. The web browser retrieves a page from the
server, then processes the code embedded in the page (often written in JavaScript) and displays the
retrieved page's content to the user.
2>Server-Side Scripting
A program running on the web server (server-side scripting) is used to change the web content on various
web pages, or to adjust the sequence of or reload of the web pages. Server responses may be determined
by such conditions as data in a posted HTML form, parameters in the URL, the type of browser being
used, the passage of time, or a database or server state.
Such web pages are often created with the help of server-side languages such as ASP, PHP, JSP etc.
Ajax is a web development technique for dynamically interchanging content with the server-side, without
reloading the web page. Google Maps is an example of a web application that uses Ajax techniques and
database.
Disadvantages
Search engines work by creating indexes of published HTML web pages that were, initially, "static".
With the advent of dynamic web pages, often created from a private database, the content is less visible.
Unless this content is duplicated in some way (for example, as a series of extra static pages on the same
site), a search may not find the information it is looking for. It is unreasonable to expect generalized web
search engines to be able to access complex database structures, some of which in any case may be
secure.
Introduction to ASP
Microsoft Active Server Pages (ASP) is a server-side scripting technology. ASP is a technology that
Microsoft created to ease the development of interactive Web applications.
Using server side scripting language like ASP we can manage the content of any page and such dynamic
code ( or content ) for the web browsers can be generated based on various conditions we set in our ASP
program.
ASP engine finishes its job of processing the code and then send the codes to users browser. From this
point on words till again the page request comes back to server, there is no control of ASP on the page. So
we should not expect ASP to perform some tasks which are likely to happen at the client browser end.
This will be clear when we discuss some of the task and where ( client or server side ) the task is to be
completed and which script will take care of it.
ASP provides solutions for transaction processing and managing session state. Asp is one of the most
successful language used in web development.
Debugging is an unavoidable part of any software development process, and the debugging tools
for ASP have been minimal. Most ASP programmers
resort to embedding temporary Response. Write statements in their code to trace the progress of
its execution.
can only be held by using the ASP Session object. And you have to implement additional code if
you, for example, want to identify a user.
Introduction to ASP.NET
ASP.NET Overview
Some point that gives the quick overview of ASP.NET.
ASP.NET provides services to allow the creation, deployment, and execution of Web
Applications and Web Services
Like ASP, ASP.NET is a server-side technology
Web Applications are built using Web Forms. ASP.NET comes with built-in Web Forms
controls, which are responsible for generating the user interface. They mirror typical HTML
widgets like text boxes or buttons. If these controls do not fit your needs, you are free to create
your own user controls.
Web Forms are designed to make building web-based applications as easy as building Visual
Basic applications
Advantages of ASP.NET
1. Separation of Code from HTML
To make a clean sweep, with ASP.NET you have the ability to completely separate layout and
business logic. This makes it much easier for teams of programmers and designers to collaborate
efficiently. This makes it much easier for teams of programmers and designers to collaborate
efficiently.
5. State management
To refer to the problems mentioned before, ASP.NET provides solutions for session and
application state management. State information can, for example, be kept in memory or stored in
a database. It can be shared across Web farms, and state information can be recovered, even if the
server fails or the connection breaks down.
ASP.NET Architecture
ASP.NET is based on the fundamental architecture of .NET Framework.
1. At the bottom of the Architecture is Common Language Runtime. NET Framework common
language runtime resides on top of the operating system services. The common language runtime
loads and executes code that targets the runtime. This code is therefore called managed code. The
runtime gives you, for example, the ability for cross-language integration.
2. .NET Framework provides a rich set of class libraries. These include base classes, like
networking and input/output classes, a data class library for data access, and classes for use by
programming tools, such as debugging services. All of them are brought together by the Services
Framework, which sits on top of the common language runtime.
3. ADO.NET is Microsoft ActiveX Data Object (ADO) model for the .NET Framework. ADO.NET
is not simply the migration of the popular ADO model to the managed environment but a
ADO.NET is intended specifically for developing web applications. This is evident from its two
major design principles:
1. Disconnected Datasets In ADO.NET, almost all data manipulation is done outside the
context of an open database connection.
2. Effortless Data Exchange with XMLDatasets can converse in the universal data format of
the Web, namely XML.
4. The 4th layer of the framework consists of the Windows application model and, in parallel, the
Web application model.
The Web application model-in the slide presented as ASP.NET-includes Web Forms and Web
Services.
ASP.NET comes with built-in Web Forms controls, which are responsible for generating the user
interface. They mirror typical HTML widgets like text boxes or buttons. If these controls do not
fit your needs, you are free to create your own user controls.
Web Services brings you a model to bind different applications over the Internet. This model is
based on existing infrastructure and applications and is therefore standard-based, simple, and
adaptable.
Web Services are software solutions delivered via Internet to any device. Today, that means Web
browsers on computers, for the most part, but the device-agnostic design of .NET will eliminate
this limitation.
5. One of the obvious themes of .NET is unification and interoperability between various
programming languages. In order to achieve this; certain rules must be laid and all the languages
must follow these rules. In other words we can not have languages running around creating their
own extensions and their own fancy new data types. CLS(Common Language Specification) is
the collection of the rules and constraints that every language (that seeks to achieve .NET
compatibility) must follow.
6. The CLR and the .NET Frameworks in general, however, are designed in such a way that code
written in one language can not only seamlessly be used by another language. Hence ASP.NET
can be programmed in any of the .NET compatible language whether it is VB.NET, C#, Managed
C++ or JScript.NET.
Execution Process
The conversion in turn can be CPU-specific and optimized. The intermediate language provides a
hardware abstraction layer.
The runtime manages the code when it is compiled into MSIL the code is therefore called managed code.
network web server. HTTPS connections are often used for payment transactions on the World Wide Web
and for sensitive transactions in corporate information systems
It is an integral part of Windows Server family of products, as well as certain editions of Windows XP,
Windows Vista and Windows 7. IIS is not turned on by default when Windows is installed.
IIS Features
The architecture of IIS 7 is modular. Modules, also called extensions, can be added or removed
individually so that only modules required for specific functionality have to be installed. IIS 7 includes
native modules as part of the full installation. These modules are individual features that the server uses to
process requests and include the following:
HTTP modules – Used to perform tasks specific to HTTP in the request-processing pipeline,
such as responding to information and inquiries sent in client headers, returning HTTP
errors, and redirecting requests.
Security modules – Used to perform tasks related to security in the request-processing pipeline,
such as specifying authentication schemes, performing URL authorization, and filtering requests.
Prohibits file listing.
Content modules – Used to perform tasks related to content in the request-processing pipeline,
such as processing requests for static files, returning a default page when a client does not specify
a resource in a request, and listing the contents of a directory. We can set the default file names in
IIS.
Caching modules – Used to perform tasks related to caching in the request-processing pipeline,
such as storing processed information in memory on the server and using cached content in
subsequent requests for the same resource.
Logging and Diagnostics modules – Used to perform tasks related to logging and diagnostics in
the request-processing pipeline, such as passing information and processing status to HTTP.sys
for logging, reporting events, and tracking requests currently executing in worker processes.
As in IIS 6.0, a site contains all the content, both static and dynamic, that is associated with that site.
However, each site must contain at least one application, which is named the root application. And each
application (including the root application) must contain at least one virtual directory, which is named the
root virtual directory. These objects work together to form the site.
The following sections explain sites, applications, virtual directories, and their related configurations in
more detail.
Sites
A site is a container for applications and virtual directories, and you can access it through one or more
unique bindings.
The binding includes two attributes important for communication: the binding protocol and the binding
information. The binding protocol defines the protocol over which communication between the server
and client occurs. The binding information defines the information that is used to access the site. For
example, the binding protocol of a Web site can be either HTTP or HTTPS, and the binding information
is the combination of IP address, port, and optional host header.
A site may contain more than one binding if the site requires different protocols or binding information.
In earlier versions of IIS, only the HTTP and HTTPS protocols were supported. For example, a Web site
might have had both an HTTP binding and an HTTPS binding when sections of the site required secure
communication over HTTPS(for example when you do transactions online, credit card information
sharing) .
Applications
An application is a group of files that delivers content or provides services over protocols, such as HTTP.
When you create an application in IIS, the application's path becomes part of the site's URL.
In IIS 7, each site must have an application which is named the root application, or default application.
However, a site can have more than one application. For example, you might have an online commerce
Web site that has several applications, such as a shopping cart application that lets users gather items
during shopping and a login application that allows users to recall saved payment information when they
make a purchase.
Virtual Directories
A virtual directory is a directory name (also referred to as path) that you specify in IIS and map to a
physical directory on a local or remote server. The directory name then becomes part of the application's
URL, and users can request the URL from a browser to access content in the physical directory, such as a
Web page or a list of additional directories and files. If you specify a different name for the virtual
directory than the physical directory, it is more difficult for users to discover the actual physical file
structure on your server because the URL does not map directly to the root of the site.
In IIS 7, each application must have a virtual directory, which is named the root virtual directory, and
which maps the application to the physical directory that contains the application's content. However, an
application can have more than one virtual directory. For example, you might use a virtual directory when
you want your application to include images from another location in the file system, but you do not want
to move the image files into the physical directory that is mapped to the application's root virtual
directory.
By default, IIS uses configuration from Web.config files in the physical directory to which the virtual
directory is mapped, as well as in any child directories in that physical directory.
Optionally, when you need to specify credentials and a method to access the virtual directory, you can
specify values for the username, password, and logonMethod attributes.
The ASP Response object is used to send output to the user from the server. Its collections, properties,
and methods are described below:
Collections
Cookies
The Cookies collection is used to set or get cookie values. If the cookie does not exist, it will be created,
and take the value that is specified.
Syntax
Response.Cookies(name)[(key)|.attribute]=value
variablename=Request.Cookies(name)[(key)|.attribute]
Parameter Description
Name Required. The name of the cookie
Value Required for the Response.Cookies command. The value of the cookie
Attribute Optional. Specifies information about the cookie. Can be one of the following
parameters:
Examples
The "Response.Cookies" command is used to create a cookie or to set a cookie value:
<%
Response.Cookies("firstname")="Alex"
%>
In the code above, we have created a cookie named "firstname" and assigned the value "Alex" to it.
It is also possible to assign some attributes to a cookie, like setting a date when a cookie should expire:
Output:
Firstname=Alex
A cookie can also contain a collection of multiple values. We say that the cookie has Keys.
In the example below, we will create a cookie-collection named "user". The "user" cookie has Keys that
contains information about a user:
<%
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>
The code below reads all the cookies your server has sent to a user. Note that the code checks if a cookie
has Keys with the HasKeys property:
<html>
<body>
<%
dim x,y
Output:
firstname=Alex
user:firstname=John
user:lastname=Smith
user:
country=Norway
user:
age=25
Properties
1. Buffer
The Buffer property specifies whether to buffer the output or not. When the output is buffered, the server
will hold back the response to the browser until all of the server scripts have been processed, or until the
script calls the Flush or End method.
Note: If this property is set, it should be before the <html> tag in the .asp file
Syntax
response.Buffer[=flag]
Parameter Description
Flag A boolean value that specifies whether to buffer the page output or not.
False indicates no buffering. The server will send the output as it is processed. False
is default for IIS version 4.0 (and earlier). Default for IIS version 5.0 (and later) is
true.
True indicates buffering. The server will not send output until all of the scripts on the
page have been processed, or until the Flush or End method has been called.
Examples
Example 1
In this example, there will be no output sent to the browser before the loop is finished. If buffer was set to
False, then it would write a line to the browser every time it went through the loop.
Example 2
<%response.Buffer=true%>
<html>
<body>
<p>I write some text, but I will control when
the text will be sent to the browser.</p>
<p>The text is not sent yet. I hold it back!</p>
<p>OK, let it go!</p>
<%response.Flush%>
</body>
</html>
Example 3
<%response.Buffer=true%>
<html>
<body>
<p>This is some text I want to send to the user.</p>
<p>No, I changed my mind. I want to clear the text.</p>
<%response.Clear%>
</body>
</html>
2. ContentType
The ContentType property sets the HTTP content type for the response object.
Syntax
response.ContentType[=contenttype]
Parameter Description
For a full list of content types, see your browser documentation or the HTTP
specification.
If an ASP page has no ContentType property set, the default content-type header would be:
content-type:text/html
<%response.ContentType="text/HTML"%>
<%response.ContentType="image/GIF"%>
<%response.ContentType="image/JPEG"%>
<%response.ContentType="text/plain"%>
This example will open an Excel spreadsheet in a browser (if the user has Excel installed):
<%response.ContentType="application/vnd.ms-excel"%>
<html>
<body>
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
</tr>
</table>
</body>
</html>
3. Expires
The Expires property sets how long (in minutes) a page will be cached on a browser before it expires. If a
user returns to the same page before it expires, the cached version is displayed.
Syntax
response.Expires[=number]
Parameter Description
Example 1
The following code indicates that the page will never be cached:
<%response.Expires=-1%>
Example 2
The following code indicates that the page will expire after 1440 minutes (24 hours):
<%response.Expires=1440%>
4. ExpiresAbsolute
he ExpiresAbsolute property sets a date and time when a cached page on a browser will expire. If a user
returns to the same page before this date/time, the cached version is displayed.
Syntax
response.ExpiresAbsolute[=[date][time]]
Parameter Description
If this parameter is not specified, the page will expire at the specified time on the day
that the script is run.
Time Specifies the time at which the page will expire.
If this parameter is not specified, the page will expire at midnight of the specified
day.
Examples
The following code indicates that the page will expire at 4:00 PM on October 11, 2012:
5. Status
The Status property specifies the value of the status line returned by the server.
Tip: Use this property to modify the status line returned by the server.
Syntax
response.Status=statusdescription
statusdescription A three-digit number and a description of that code, like 404 Not Found.
Note: Status values are defined in the HTTP specification.
Examples
<%
ip=request.ServerVariables("REMOTE_ADDR")
if ip<>"194.248.333.500" then
response.Status="401 Unauthorized"
response.Write(response.Status)
response.End
end if
%>
Methods
1.Clear
Note: This method does not clear the response headers, only the response body.
Syntax
response.Clear
Examples
<%
response.Buffer=true
%>
<html>
<body>
<p>This is some text I want to send to the user.</p>
<p>No, I changed my mind. I want to clear the text.</p>
<%
response.Clear
%>
</body>
</html>
Output:
(nothing)
2.End
The End method stops processing a script, and returns the current result.
Syntax
Response.End
Examples
<html>
<body>
<p>I am writing some text. This text will never be
<%
Response.End
%>
finished! It's too late to write more!</p>
</body>
</html>
Output:
3. Flush
Syntax
Response.Flush
Example
<%
Response.Buffer=true
%>
<html>
<body>
<p>I write some text, but I will control when the
text will be sent to the browser.</p>
<p>The text is not sent yet. I hold it back!</p>
<p>OK, let it go!</p>
<%
Response.Flush
%>
</body>
</html>
Output:
4. Redirect
Syntax
Response.Redirect URL
Parameter Description
Examples
<%
Response.Redirect "http://cloudfactory.com"
%>
5. Write
Syntax
Response.Write variant/variable
Parameter Description
Examples
Example 1
<%
Response.Write "Hello World"
%>
Output:
Hello World
Output:
John
Example 3
<%
Response.Write("Hello<br />World")
%>
Output:
Hello
World
Request Object
When a browser asks for a page from a server, it is called a request. The Request object is used to get
information from a visitor. Its collections, properties, and methods are described below:
Collections
1.Cookies(Refer to Response Object)
2.Form
The Form collection is used to retrieve the values of form elements from a form that uses the POST
method.
Syntax
Request.Form(element)[(index)|.Count]
Parameter Description
Element Required. The name of the form element from which the collection is to retrieve
values
Example 1
You can loop through all the values in a form request. If a user filled out a form by specifying two values
- Blue and Green - for the color element, you could retrieve those values like this:
Output:
Blue
Green
Example 2
firstname=John&lastname=Dove&color=Red
Hi, <%=Request.Form("firstname")%>.
Your favorite color is <%=Request.Form("color")%>.
Output:
3.QueryString:
The QueryString collection is used to retrieve the variable values in the HTTP query string.
The HTTP query string is specified by the values following the question mark (?), like this:
The line above generates a variable named txt with the value "this is a query string test".
Query strings are also generated by form submission, or by a user typing a query into the address bar of
the browser.
Note: If you want to send large amounts of data (beyond 100 kb) the Request.QueryString cannot be
used.
Syntax
Request.QueryString(variable)[(index)|.Count]
Parameter Description
Variable Required. The name of the variable in the HTTP query string to retrieve
Examples
Example 1
http://www.w3schools.com/test/names.asp?n=John&n=Susan
John
Susan
Example 2
http://cloudfactory.com/names.asp?name=John&age=30
name=John&age=30
Hi, <%=Request.QueryString("name")%>.
Your age is <%= Request.QueryString("age")%>.
Output:
4. ServerVariables:
Syntax
Request.ServerVariables (server_variable)
Parameter Description
Server Variables
Variable Description
ALL_HTTP Returns all HTTP headers sent by the client. Always prefixed with
HTTP_ and capitalized
APPL_MD_PATH Returns the meta base path for the application for the ISAPI DLL
APPL_PHYSICAL_PATH Returns the physical path corresponding to the meta base path
AUTH_TYPE The authentication method that the server uses to validate users
CERT_FLAGS bit0 is set to 1 if the client certificate is present and bit1 is set to 1 if the
cCertification authority of the client certificate is not valid
CERT_KEYSIZE Returns the number of bits in Secure Sockets Layer connection key size
GATEWAY_INTERFACE Returns the revision of the CGI specification used by the server
HTTP_ACCEPT_LANGUAGE Returns a string describing the language to use for displaying content
HTTP_REFERER Returns a string containing the URL of the page that referred the request
to the current page using an <a> tag. If the page is redirected,
HTTP_REFERER is empty
HTTP_USER_AGENT Returns a string describing the browser that sent the request
HTTPS Returns ON if the request came in through secure channel or OFF if the
request came in through a non-secure channel
HTTPS_KEYSIZE Returns the number of bits in Secure Sockets Layer connection key size
INSTANCE_META_PATH The meta base path for the instance of IIS that responds to the request
LOGON_USER Returns the Windows account that the user is logged into
PATH_TRANSLATED A translated version of PATH_INFO that takes the path and performs
any necessary virtual-to-physical mapping
QUERY_STRING Returns the query information stored in the string following the question
mark (?) in the HTTP request
REMOTE_ADDR Returns the IP address of the remote host making the request
SERVER_NAME Returns the server's host name, DNS alias, or IP address as it would
appear in self-referencing URLs
SERVER_PORT Returns the port number to which the request was sent
SERVER_PROTOCOL Returns the name and revision of the request information protocol
SERVER_SOFTWARE Returns the name and version of the server software that answers the
request and runs the gateway
Examples
You can loop through all of the server variables like this:
<%
for each x in Request.ServerVariables
response.write(x & "<br />")
next
%>
The following example demonstrates how to find out the visitor's browser type, IP address, and more:
<html>
<body>
<p>
<b>You are browsing this site with:</b>
<%Response.Write(Request.ServerVariables("http_user_agent"))%>
</p>
<p>
<b>Your IP address is:</b>
<%Response.Write(Request.ServerVariables("remote_addr"))%>
</p>
<p>
<b>The DNS lookup of the IP address is:</b>
<%Response.Write(Request.ServerVariables("remote_host"))%>
</p>
<p>
Properties
TotalBytes
The TotalBytes property is a read-only property that returns the total number of bytes the client sent in the
body of the request.
Syntax
varbytes=Request.Totalbytes
Example
The following code sets the variable a equal to the total number of bytes sent in the body of the request:
<%
dim a
a=Request.TotalBytes
%>
Server Object
The ASP Server object is used to access properties and methods on the server. Its properties and methods
are described below:
Properties
ScriptTimeOut
The ScriptTimeout property sets or returns the maximum number of seconds a script can run before it is
terminated.
Parameter Description
NumSeconds The maximum number of seconds a script can run before the server terminates it.
Default is 90 seconds
Examples
Example 1
<%
Server.ScriptTimeout=200
%>
Example 2
<%
response.write(Server.ScriptTimeout)
%>
Methods
1.CreateObject
Note: Objects created with this method have page scope. They are destroyed when the server are finished
processing the current ASP page. To create an object with session or application scope, you can either use
the <object> tag in the Global.asa file, or store the object in a session or application variable.
Syntax
Server.CreateObject(progID)
Part Description
<%
Set adrot=Server.CreateObject("MSWC.AdRotator")
%>
Example 2
An object stored in a session variable is destroyed when the session ends. However, you can also destroy
the object by setting the variable to Nothing or to a new value:
<%
Session("ad")=Nothing
%>
or
<%
Session("ad")="a new value"
%>
Example 3
You cannot create an instance of an object with the same name as a built-in object:
<%
Set Application=Server.CreateObject("Application")
%>
2. Execute
The Execute method executes an ASP file from inside another ASP file. After executing the called .asp
file, the control is returned to the original .asp file.
Syntax
Server.Execute(path)
Parameter Description
Example
File1.asp:
<%
response.write("I am in File 1!<br />")
File2.asp:
<%
response.write("I am in File 2!<br />")
%>
Output:
I am in File 1!
I am in File 2!
I am back in File 1!
Also look at the Server.Transfer method to see the difference between the Server.Execute and
Server.Transfer methods.
3.GetLastError
The GetLastError method returns an ASPError object that describes the error condition that occurred.
By default, a Web site uses the file \iishelp\common\500-100.asp for processing ASP errors. You can
either use this file, or create your own. If you want to change the ASP file for processing the 500;100
custom errors you can use the IIS snap-in.
Note: A 500;100 custom error will be generated if IIS encounters an error while processing either an ASP
file or the application's Global.asa file.
Note: This method is available only before the ASP file has sent any content to the browser.
Syntax
Server.GetLastError()
Examples
Example 1
In the example an error will occur when IIS tries to include the file, because the include statement is
missing the file parameter:
Example 2
In this example an error will occur when compiling the script, because the "next" keyword is missing:
Example 3
In this example an error will occur because the script attempts to divide by 0:
<%
dim i,tot,j
i=0
tot=0
j=0
for i=1 to 10
tot=tot+1
next
tot=tot/j
%>
4. MapPath
Syntax
Server.MapPath(path)
Parameter Description
Path Required. A relative or virtual path to map to a physical path. If this parameter starts
with / or \, it returns a path as if this parameter is a full virtual path. If this parameter
doesn't start with / or \, it returns a path relative to the directory of the .asp file being
processed
Examples
Example 1
Output:
c:\inetpub\wwwroot\script\test.asp
c:\inetpub\wwwroot\script\script\test.asp
c:\inetpub\wwwroot\script\test.asp
c:\inetpub\wwwroot\script
c:\inetpub\wwwroot
c:\inetpub\wwwroot
Example 2
How to use a relative path to return the relative physical path to the page that is being viewed in the
browser:
<%
response.write(Server.MapPath("../"))
%>
or
<%
response.write(Server.MapPath("..\"))
%>
5. Transfer
The Transfer method sends (transfers) all the state information (all application/session variables and all
items in the request collections) created in one ASP file to a second ASP file.
When the second ASP page completes its tasks, it will NOT return to the first ASP page (like the Execute
method).
Note: The Transfer method is an efficient alternate for the Response.Redirect. A redirect forces the Web
server to handle an extra request while the Server.Transfer method transfers execution to a different ASP
page on the server, and avoids the extra round trip.
Syntax
Server.Transfer(path)
Path Required. The location of the ASP file to which control should be transferred
Example
File1.asp:
<%
response.write("Line 1 in File 1<br />")
Server.Transfer("file2.asp")
response.write("Line 2 in File 1<br />")
%>
File2.asp:
<%
response.write("Line 1 in File 2<br />")
response.write("Line 2 in File 2<br />")
%>
Output:
Line 1 in File 1
Line 1 in File 2
Line 2 in File 2
Application Object
An application on the Web may consists 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.
The Application object is initialized by IIS when the first .asp page from within the given virtual directory
is requested. It remains in the server's memory until either the web service is stopped or the application is
explicitly unloaded from the web server
The Application object's collections, methods, and events are described below:
The Contents collection contains all the items appended to the application/session through a script
command.
Tip: To remove items from the Contents collection, use the Remove and RemoveAll methods.
Syntax
Application.Contents(Key)
Parameter Description
Example 1
Notice that both name and objtest would be appended to the Contents collection:
<%
Application("name")="Harry"
Set Application("objtest")=Server.CreateObject("ADODB.Connection")
%>
Example 2
<%
for each x in Application.Contents
Response.Write(x & "=" & Application.Contents(x) & "<br />")
next
%>
or:
<%
For i=1 to Application.Contents.Count
Response.Write(i & "=" & Application.Contents(i) & "<br />")
Next
%>
Example 3
<%
Application("date")="2001/05/05"
Application("author")="Michael"
Output:
date=2001/05/05
author= Michael
2.StaticObjects
The StaticObjects collection contains all the objects appended to the application/session with the HTML
<object> tag.
Syntax
Application.StaticObjects(Key)
Parameter Description
Example 1
<%
for each x in Application.StaticObjects
Response.Write(x & "<br />")
next
%>
Example 2
In Global.asa:
In an ASP file:
<%
for each x in Application.StaticObjects
Response.Write(x & "<br />")
next
%>
MsgBoard
AdRot
Methods
1. Contents.Remove
Syntax
Application.Contents.Remove(name|index)
Parameter Description
Example 1
<%
Application("test1")=("First test")
Application("test2")=("Second test")
Application("test3")=("Third test")
Application.Contents.Remove("test2")
Output:
test1=First test
test3=Third test
Example 2
<%
Application("test1")=("First test")
Application("test2")=("Second test")
Application("test3")=("Third test")
Application.Contents.Remove(2)
Output:
test1=First test
test3=Third test
2.Contents.RemoveAll
The Contents.RemoveAll method deletes all items from the Contents collection.
Syntax
Application.Contents.RemoveAll()
<%
Application.Contents.RemoveAll()
%>
Lock Method
The Lock method prevents other users from modifying the variables in the Application object (used to
ensure that only one client at a time can modify the Application variables).
Unlock Method
The Unlock method enables other users to modify the variables stored in the Application object (after it
has been locked using the Lock method).
Syntax
Application.Lock
Application.Unlock
Example
The example below uses the Lock method to prevent more than one user from accessing the variable
visits at a time, and the Unlock method to unlock the locked object so that the next client can increment
the variable visits:
<%
Application.Lock
Application("visits")=Application("visits")+1
Application.Unlock
%>
Events
Application_OnEnd
Application_OnStart
Application_OnStart Event
The Application_OnStart event occurs before the first new session is created (when the Application object
is first referenced).
Note: Referencing to a Session, Request, or Response objects in the Application_OnStart event script will
cause an error.
Application_OnEnd Event
The Application_OnEnd event occurs when the application ends (when the web server stops).
Syntax
<script language="vbscript" runat="server">
Sub Application_OnStart
...
End Sub
Sub Application_OnEnd
...
End Sub
</script>
Examples
Global.asa:
Sub Application_OnEnd()
Application("totvisitors")=Application("visitors")
Sub Application_OnStart
Application("visitors")=0
End Sub
Sub Session_OnStart
Application.Lock
Application("visitors")=Application("visitors")+1
Application.UnLock
End Sub
Sub Session_OnEnd
Application.Lock
Application("visitors")=Application("visitors")-1
Application.UnLock
End Sub
</script>
<html>
<head>
</head>
<body>
<p>
There are <%response.write(Application("visitors"))%>
online now!
</p>
</body>
</html>
The Global.asa file is an optional file that can contain declarations of objects, variables, and methods that
can be accessed by every page in an ASP application.
All valid browser scripts (JavaScript, VBScript, JScript, PerlScript, etc.) can be used within Global.asa.
Application events
Session events
<object> declarations
TypeLibrary declarations
the #include directive
Session Object
When you are working with an application on your computer, you open it, do some changes and then you
close it. This is much like a Session. The computer knows who you are. It knows when you open the
application and when you close it. However, on the internet there is one problem: the web server does not
know who you are and what you 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 a Session object hold information about one single user, and are available to all pages
in one application. Common information stored in session variables are name, id, and preferences. The
server creates a new Session object for each new user, and destroys the Session object when the session
expires.
The Session object's collections, properties, methods, and events are described below:
Collections
1.Contents
The Contents collection contains all the items appended to the session through a script command.
Tip: To remove items from the Contents collection, use the Remove and RemoveAll methods.
Syntax
Session.Contents(Key)
Example 1
Notice that both name and objtest would be appended to the Contents collection:
<%
Session("name")="Hege"
Set Session("objtest")=Server.CreateObject("ADODB.Connection")
%>
Example 2
<%
for each x in Session.Contents
Response.Write(x & "=" & Session.Contents(x) & "<br />")
or:
<%
For i=1 to Session.Contents.Count
Response.Write(i & "=" & Session.Contents(i) & "<br />")
Next
%>
Example 3
<%
Session("name")="Hege"
Session("date")="2001/05/05"
Output:
name=Hege
date=2001/05/05
2. StaticObjects
The StaticObjects collection contains all the objects appended to the session with the HTML <object>
tag.
Syntax
Session.StaticObjects(Key)
Parameter Description
Example 1
<%
for each x in Session.StaticObjects
Response.Write(x & "<br />")
next
%>
In Global.asa:
In an ASP file:
<%
for each x in Session.StaticObjects
Response.Write(x & "<br />")
next
%>
Output:
MsgBoard
AdRot
Properties
1.CodePage
The CodePage property specifies the character set that will be used when displaying dynamic content.
Syntax
Session.CodePage(=Codepage)
Parameter Description
Codepage Defines a code page (character set) for the system running the script engine
Examples
<%
Response.Write(Session.CodePage)
%>
Output:
1252
The LCID property sets or returns an integer that specifies a location or region. Contents like date, time,
and currency will be displayed according to that location or region.
Syntax
Session.LCID(=LCID)
Parameter Description
Examples
<%
response.write("<p>")
response.write("Default LCID is: " & Session.LCID & "<br />")
response.write("Date format is: " & date() & "<br />")
response.write("Currency format is: " & FormatCurrency(350))
response.write("</p>")
Session.LCID=1036
response.write("<p>")
response.write("LCID is now: " & Session.LCID & "<br />")
response.write("Date format is: " & date() & "<br />")
response.write("Currency format is: " & FormatCurrency(350))
response.write("</p>")
Session.LCID=3079
response.write("<p>")
response.write("LCID is now: " & Session.LCID & "<br />")
response.write("Date format is: " & date() & "<br />")
response.write("Currency format is: " & FormatCurrency(350))
response.write("</p>")
Session.LCID=2057
response.write("<p>")
response.write("LCID is now: " & Session.LCID & "<br />")
response.write("Date format is: " & date() & "<br />")
response.write("Currency format is: " & FormatCurrency(350))
response.write("</p>")
%>
Output:
3.SessionID
The SessionID property returns a unique id for each user. The unique id is generated by the server.
Syntax
Session.SessionID
Examples
<%
Response.Write(Session.SessionID)
%>
Output:
772766038
4. TimeOut
The Timeout property sets or returns the timeout period for the Session object for this application, in
minutes. If the user does not refresh or request a page within the timeout period, the session will end.
Syntax
Session.Timeout[=nMinutes]
Parameter Description
nMinutes The number of minutes a session can remain idle before the server terminates it.
Default is 20 minutes
Examples
<%
response.write("<p>")
response.write("Default Timeout is: " & Session.Timeout)
Session.Timeout=30
response.write("<p>")
response.write("Timeout is now: " & Session.Timeout)
response.write("</p>")
%>
Output:
Timeout is now: 30
Methods
1.Abandon
Note: When this method is called, the current Session object is not deleted until all of the script on the
current page have been processed. This means that it is possible to access session variables on the same
page as the call to Abandon, but not from another Web page.
Syntax
Session.Abandon
Examples
File1.asp:
<%
Session("name")="Hege"
Session.Abandon
Response.Write(Session("name"))
%>
Output:
Hege
File2.asp:
<%
Response.Write(Session("name"))
%>
Output:
2. Contents.Remove
Syntax
Session.Contents.Remove(name|index)
Parameter Description
Example 1
<%
Session("test1")=("First test")
Session("test2")=("Second test")
Session("test3")=("Third test")
Session.Contents.Remove("test2")
Output:
test1=First test
test3=Third test
Example 2
<%
Session("test1")=("First test")
Session("test2")=("Second test")
Session("test3")=("Third test")
Session.Contents.Remove(2)
Output:
3.Contents.RemoveAll
The Contents.RemoveAll method deletes all items from the Contents collection.
Syntax
Session.Contents.RemoveAll()
Example:
<%
Session.Contents.RemoveAll()
%>
Events
Session_OnStart Event
Session_OnEnd Event
The Session_OnEnd event occurs when the session ends (abandoned or times out).
Client-Side Example
<html>
<body>
<script type=”text/vbscript”>
Document.write(“Hello World!”)
</script>
</body>
</html>
Variables
Declaring variables in ASP is simple, especially since all variables are of Variant type. What does this
mean to you? You don't have to declare if your variable is an integer, string, or object. You just declare it,
and it has the potential to be anything. To declare a variable in ASP/VBScript we use the Dim statement.
In ASP/VBScript, it is possible not to declare variables at all. A variable can appear in the program,
though it has never been declared. It is called default declaring. Variable in this case will be of Variant
type.
The variable value will be kept in memory for the life span of the current page and will be released from
memory when the page has finished executing. To declare variables accessible to more than one ASP file,
declare them as session variables or application variables.
Contstants
Constants just as variables are used to store information. The main difference between constants and
variables is that constant value can not be changed in the process of running program. If we attempt to re-
assign the value of the constant we'll get a run time error.
It can be mathematic constants, passwords, paths to files, etc. By using a constant you "lock in" the value
which prevents you from accidentally changing it. If you want to run a program several times using a
different value each time, you do not need to search throughout the entire program and change the value
at each instance. You only need to change it at the beginning of the program where you set the initial
value for the constant.
To declare a constant in VBScript we use the Const keyword. Have a look at the following example:
Conditional Statements
The If Statement is a way to make decisions based on a variable or some other type of data. For example,
you might have a script that checks if Boolean value is true or false or if variable contains number or
string value.
Use the if statement to execute a statement if a logical condition is true. Use the optional else clause to
execute a statement if the condition is false. The syntax for If statement looks as follows:
if condition then
statements_1
else
Condition can be any expression that evaluates to true or false. If condition evaluates to true, statements_1
are executed; otherwise, statements_2 are executed. statement_1 and statement_2 can be any statement,
including further nested if statements.
You may also compound the statements using elseif to have multiple conditions tested in sequence. You
should use this construction if you want to select one of many sets of lines to execute.
if condition_1 then
statement_1
[elseif condition_2 then
statement_2]
...
[elseif condition_n_1 then
statement_n_1]
[else
statement_n]
end if
Let's have a look at the examples. The first example decides whether a student has passed an exam with a
pass mark of 57
<%@ language="vbscript"%>
<%
Dim Result
Result = 70
Next example use the elseif variant on the if statement. This allows us to test for other conditions if the
first one wasn't true. The program will test each condition in sequence until:
It finds one that is true. In this case it executes the code for that condition.
It reaches an else statement. In which case it executes the code in the else statement.
It reaches the end of the if ... elseif ... else structure. In this case it moves to the next statement
after the conditional structure.
<%@ language="vbscript"%>
<%
Dim Result
Result = 70
The Select statements work the same as if statements. However the difference is that they can check for
multiple values. Of course you do the same with multiple if..else statements, but this is not always the
best approach.
The Select statement allows a program to evaluate an expression and attempt to match the expression's
value to a case label. If a match is found, the program executes the associated statement. The syntax for
the Select statement as follows:
The program first looks for a case clause with a label matching the value of expression and then transfers
control to that clause, executing the associated statements. If no matching label is found, the program
looks for the optional Case Else clause, and if found, transfers control to that clause, executing the
associated statements. If no Case Else clause is found, the program continues execution at the statement
following the end of Select. Use break to prevent the code from running into the next case automatically.
<%@ language="vbscript">
<%
Dim Flower
Flower = "rose"
ASP performs several types of repetitive operations, called "looping". Loops are set of instructions used
to repeat the same block of code till a specified condition returns false or true depending on how you need
it. To control the loops you can use counter variable that increments or decrements with each repetition of
the loop.
The two major groups of loops are For..Next and Do..Loop. The For...Next statements are best used when
you want to perform a loop a specific number of times. The Do...Loop statements are best used to perform
a loop an undetermined number of times. In addition, you can use the Exit keyword within loop
statements.
For...Next loops are used when you want to execute a piece of code a set number of times. The syntax
is as follows:
The For statement specifies the counter variable and its initial and finite values. The Next statement
increases the counter variable by one. Optional the Step keyword allows to increase or decrease the
counter variable by the value you specify.
<%
For i = 0 to 10 Step 2 'use i as a counter
response.write("The number is " & i & "<br />")
Next
%>
The preceding example prints out even numbers from 0 to 10, the <br> tag puts a line break in between
each value.
Next example generates a multiplication table 2 through 9. Outer loop is responsible for generating a list
of dividends, and inner loop will be responsible for generating lists of dividers for each individual
number:
<%
response.write("<h1>Multiplication table</h1>")
response.write("<table border=2 width=50%")
response.write("</tr>")
Next 'repeat the code and move on to the next value of i
response.write("</table>")
%>
The For Each...Next loop is similar to a For...Next loop. Instead of repeating the statements a specified
number of times, the For Each...Next loop repeats the statements for each element of an array (or each
item in a collection of objects).
The following code snippet creates drop-down list where options are elements of an array:
<%
Dim bookTypes(7) 'creates first array
bookTypes(0)="Classic"
bookTypes(1)="Information Books"
bookTypes(2)="Fantasy"
bookTypes(3)="Mystery"
bookTypes(4)="Poetry"
bookTypes(5)="Humor"
bookTypes(6)="Biography"
bookTypes(7)="Fiction"
'Now let's call the sub and print out our lists on the screen
Call createList(bookTypes) 'takes bookTypes array as an argument
Call createList(arrcars) 'takes arrCars array as an argument
%>
The Do...Loop is another commonly used loop after the For...Next loop. The Do...Loop statement repeats
a block of statements an indefinite number of times. The statements are repeated either while a condition
is True or until a condition becomes True. The syntax looks as follows:
Do [While|Until] condition
statements
Loop
Do
statements
Loop [While|Until] condition
In this case the code inside this loop will be executed at least one time. Have a look at the examples:
The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less
than, or equal to 10. i will increase by 1 each time the loop runs.
<%
Dim i 'use i as a counter
i = 0 'assign a value to i
Now let's consider a more useful example which creates drop-down lists of days, months and years. You
can use this code for registration form, for example.
<%
'creates an array
Dim month_array(11)
month_array(0) = "January"
month_array(1) = "February"
month_array(2) = "March"
month_array(3) = "April"
month_array(4) = "May"
month_array(5) = "June"
month_array(6) = "July"
month_array(7) = "August"
month_array(8) = "September"
month_array(9) = "October"
month_array(10) = "November"
month_array(11) = "December"
Dim i
response.write("<select name=""day"">" & vbCrLf)
i=1
response.write("<select name=""year"">")
i = 1900
Do Until i = 2005
response.write("<option value=" & i & ">" & i & "</option>" & vbCrLf)
i=i+1
Loop
response.write("</select>")
%>
Note: Make sure the condition in a loop eventually becomes false; otherwise, the loop will never
terminate.
The Exit keyword alters the flow of control by causing immediate exit from a repetition structure. You
can use the Exit keyword in different situations, for example to avoid an endless loop. To exit the
For...Next loop before the counter reaches its finite value you should use the Exit For statement. To exit
the Do...Loop use the Exit Do statement.
<%
response.write("<p><strong>Example of using the Exit For statement:</strong><p>")
For i = 0 to 10
If i=3 Then Exit For
response.write("The number is " & i & "<br />")
Next
i=5
Do Until i = 10
i=i-1
response.write("The number is " & i & "<br />")
If i < 10 Then Exit Do
Loop
%>
The VBScript arrays are 0 based, meaning that the array element indexing starts always from 0. The 0
index represents the first position in the array, the 1 index represents the second position in the array, and
so forth.
There are two types of VBScript arrays - static and dynamic. Static arrays remain with fixed size
throughout their life span. To use static VBScript arrays you need to know upfront the maximum number
of elements this array will contain. If you need more flexible VBScript arrays with variable index size,
then you can use dynamic VBScript arrays. VBScript dynamic arrays index size can be
increased/decreased during their life span.
Static Arrays
Let's create an array called 'arrCars' that will hold the names of 5 cars:
<%
'Use the Dim statement along with the array name
'to create a static VBScript array
'The number in parentheses defines the array‟s upper bound
Dim arrCars(4)
arrCars(0)="BMW"
arrCars(1)="Mercedes"
arrCars(2)="Audi"
arrCars(3)="Bentley"
arrCars(4)="Mini"
<%
'we use the VBScript Array function along with a Dim statement
'to create and populate our array
Dim arrCars
arrCars = Array("BMW","Mercedes","Audi","Bentley","Mini") 'each element must be separated by a
comma
'again we could loop through the array and print out the values
For i=0 to 4
response.write arrCars(i) & "<br>"
Next
%>
Dynamic Arrays
<%
Dim arrCars
arrCars = Array()
%>
In order to use this array you need to use the ReDim statement to define the array‟s upper bound:
<%
Dim arrCars
arrCars = Array()
Redim arrCars(27)
%>
If in future you need to resize this array you should use the Redim statement again. Be very careful with
the ReDim statement. When you use the ReDim statement you lose all elements of the array. Using the
keyword PRESERVE in conjunction with the ReDim statement will keep the array we already have and
increase the size:
<%
Dim arrCars
arrCars = Array()
Redim arrCars(27)
Redim PRESERVE arrCars(52)
%>
Multidimensional Arrays
Arrays do not have to be a simple list of keys and values; each location in the array can hold another
array. This way, you can create a multi-dimensional array.
The most commonly used are two-dimensional arrays. You can think of a two-dimensional array as a
matrix, or grid, with width and height or rows and columns. Here is how you could define two-
dimensional array and display the array values on the web page:
'arrCars(col,row)
arrCars(0,0) = "BMW"
arrCars(1,0) = "2004"
arrCars(2,0) = "45.000"
arrCars(0,1) = "Mercedes"
arrCars(1,1) = "2003"
arrCars(2,1) = "57.000"
arrCars(0,2) = "Audi"
arrCars(1,2) = "2000"
arrCars(2,2) = "26.000"
'The UBound function will return the 'index' of the highest element in an array.
For i = 0 to UBound(arrCars, 2)
Response.Write("<TR><TD>#" & i & "</TD>")
Response.Write("<TD>" & arrCars(0,i) & "</TD>")
Response.Write("<TD>" & arrCars(1,i) & "</TD>")
Response.Write("<TD>" & arrCars(2,i) & "</TD></TR>")
Next
Response.Write("</TABLE>")
%>
Next
Next
Functions and procedures provide a way to create re-usable modules of programming code and avoid
rewriting the same block of code every time you do the particular task. If you don't have any
functions/procedures in your ASP page, the ASP pages are executed from top to bottom, the ASP parsing
engine simply processes your entire file from the beginning to the end. VBScript functions and
procedures, however, are executed only when called, not inline with the rest of the code. A function or
procedure can be reused as many times as required, thus saving you time and making for a less clustered
looking page.
You can write functions in ASP similar to the way you write them in Visual Basic. It is good
programming practice to use functions to modularize your code and to better provide reuse. To declare a
subroutine (a function that doesn‟t return a value, starts with the Sub keyword and ends with End Sub),
you simply type:
A function differs from a subroutine in the fact that it returns data, start with Function keyword and end
with End Function. Functions are especially good for doing calculations and returning a value. To declare
a function, the syntax is similar:
Have a look at the code for a procedure that is used to print out information on the page:
Now let's consider how to call the sub. There are two ways:
<%
'the first method
Call GetInfo("Mr. O'Donnel","555-5555",20)
'the second one
GetInfo "Mr. O'Donnel","555-5555",20
%>
In each example, the actual argument passed into the subprocedure is passed in the corresponding
position. Note that if you use the Call statement, the arguments must be enclosed in parentheses. If you do
not use call, the parentheses aren't used.
Now let's look at the code for a function that takes an integer value and returns the square of that value.
Also included is code to call the function.
<%
Function Square(num)
Square = num * num
end function
The great advantage of ASP is possibility to respond to user queries or data submitted from HTML forms.
You can process information gathered by an HTML form and use ASP code to make decisions based off
this information to create dynamic web pages. In this tutorial we will show how to create an HTML form
and process the data.
Before you can process the information, you need to create an HTML form that will send information to
your ASP page. There are two methods for sending data to an ASP form: POST and GET. These two
types of sending information are defined in your HTML form element's method attribute. Also, you must
specify the location of the ASP page that will process the information.
Below is a simple form that will send the data using the POST method. Information sent from a form with
the POST method is invisible to others and has no limits on the amount of information to send. Copy and
paste this code and save it as "form.html".
<html>
<head>
<title>Process the HTML form data with the POST method</title>
</head>
<body>
<form method="POST" action="process.asp" name="form1">
<table width="70%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>name:</td>
<td colspan="2"><input type="text" name="name"></td>
</tr>
<tr>
<td>email:</td>
<td colspan="2"><input type="text" name="email"></td>
</tr>
<tr>
<td>comments:</td>
<td colspan="2"><textarea name="comment" cols="40" rows="5"></textarea></td>
</tr>
<tr>
<td> </td>
<td colspan="2"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
Next, we are going to create our ASP page "process.asp" that will process the data. In our example we
decided to send data with the POST method so to retrieve the information we can use the ASP
'Request.From' command. Copy and paste this code and save it in the same directory as "form.html".
<body>
<%
'declare the variables that will receive the values
Dim name, email, comment
'receive the values sent from the form and assign them to variables
'note that request.form("name") will receive the value entered
'into the textfield called name
name=Request.Form("name")
email=Request.Form("email")
comment=Request.Form("comment")
Note: If you want to process the information sent through an HTML form with the GET method you
should use the 'Request.QueryString' command . In the preceding example you should replace all
instances of Form with QueryString. But remember that the data sent from a form with the GET method
is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of
information to send.
The Dictionary object is used to store information in name/value pairs (referred to as key and item). The
Dictionary object might seem similar to Arrays, however, the Dictionary object is a more desirable
solution to manipulate related data.
The following example creates a Dictionary object, adds some key/item pairs to it, and retrieves the item
value for the key gr:
<%
Dim d
Set d=Server.CreateObject("Scripting.Dictionary")
d.Add "re","Red"
d.Add "gr","Green"
d.Add "bl","Blue"
d.Add "pi","Pink"
Response.Write("The value of key gr is: " & d.Item("gr"))
%>
Output:
Properties
1.CompareMode
The CompareMode property sets or returns the comparison mode for comparing keys in a Dictionary
object.
Syntax
DictionaryObject.CompareMode[=compare]
Parameter Description
2.Count
The Count property returns the number of key/item pairs in the Dictionary object.
Syntax
DictionaryObject.Count
Example
<%
dim d
set d=Server.CreateObject("Scripting.Dictionary")
d.Add "n","Norway"
d.Add "i","Italy"
d.Add "s","Sweden"
Response.Write("The number of key/item pairs: " & d.Count)
set d=nothing
%>
Output:
3. Item
The Item property sets or returns the value of an item in a Dictionary object.
Syntax
DictionaryObject.Item(key)[=newitem]
Parameter Description
Example
<%
Dim d
Set d=Server.CreateObject("Scripting.Dictionary")
d.Add "re","Red"
d.Add "gr","Green"
d.Add "bl","Blue"
d.Add "pi","Pink"
Response.Write("The value of key pi is: " & d.Item("pi"))
%>
Output:
4. Key
The Key property sets a new key value for an existing key value in a Dictionary object.
Syntax
DictionaryObject.Key(key)=newkey
Parameter Description
Example
<%
Dim d
Set d=Server.CreateObject("Scripting.Dictionary")
d.Add "re","Red"
d.Add "gr","Green"
d.Add "bl","Blue"
d.Add "pi","Pink"
d.Key("re")="r"
Response.Write("The value of key r is: " & d.Item("r"))
Output:
Methods
1.Add
Syntax
DictionaryObject.Add(key,item)
Parameter Description
Example
<%
Dim d
Set d=Server.CreateObject("Scripting.Dictionary")
d.Add "re","Red"
d.Add "gr","Green"
d.Add "bl","Blue"
d.Add "pi","Pink"
Response.Write("The value of key gr is: " & d.Item("gr"))
%>
Output:
The value of key gr is: Green
2. Exists
The Exists method returns a Boolean value that indicates whether a specified key exists in the Dictionary
object. It returns true if the key exists, and false if not.
Syntax
DictionaryObject.Exists(key)
Parameter Description
Example
<%
dim d
set d=Server.CreateObject("Scripting.Dictionary")
d.Add "n","Norway"
d.Add "i","Italy"
d.Add "s","Sweden"
if d.Exists("n")=true then
Response.Write("Key exists!")
else
Response.Write("Key does not exist!")
end if
set d=nothing
%>
Output:
Key exists!
3.Items
The Items method returns an array of all the items in a Dictionary object.
Syntax
DictionaryObject.Items
Example
<%
dim d,a,i
set d=Server.CreateObject("Scripting.Dictionary")
d.Add "n","Norway"
d.Add "i","Italy"
d.Add "s","Sweden"
Response.Write("<p>Item values:</p>")
a=d.Items
for i=0 to d.Count-1
Response.Write(a(i))
Response.Write("<br />")
next
4.Keys
The Keys method returns an array of all the keys in a Dictionary object.
Syntax
DictionaryObject.Keys
Example
<%
dim d,a,i
set d=Server.CreateObject("Scripting.Dictionary")
d.Add "n","Norway"
d.Add "i","Italy"
d.Add "s","Sweden"
Response.Write("<p>Key values:</p>")
a=d.Keys
for i=0 to d.Count-1
Response.Write(a(i))
Response.Write("<br />")
next
set d=nothing
%>
Output:
Key values:
n
i
s
5.Remove
The Remove method removes one specified key/item pair from the Dictionary object.
Syntax
DictionaryObject.Remove(key)
key Required. The key associated with the key/item pair to remove
Example
<%
dim d,a,i
set d=Server.CreateObject("Scripting.Dictionary")
d.Add "n","Norway"
d.Add "i","Italy"
d.Add "s","Sweden"
d.Remove("n")
Response.Write("<p>Key values:</p>")
a=d.Keys
for i=0 to d.Count-1
Response.Write(a(i))
Response.Write("<br />")
next
set d=nothing
%>
Output:
Key values:
i
s
6.RemoveAll
The Remove method removes all the key/item pairs from a Dictionary object.
Syntax
DictionaryObject.RemoveAll
Example
<%
dim d,a,i
set d=Server.CreateObject("Scripting.Dictionary")
d.Add "n","Norway"
d.Add "i","Italy"
d.Add "s","Sweden"
d.RemoveAll
FileSystemObject Object
The FileSystemObject object is used to access the file system on a server.This object can manipulate files,
folders, and directory paths. It is also possible to retrieve file system information with this object.The
following code creates a text file (c:\test.txt) and then writes some text to the file:
<%
dim fs,fname
set fs=Server.CreateObject("Scripting.FileSystemObject")
set fname=fs.CreateTextFile("c:\test.txt",true)
fname.WriteLine("Hello World!")
fname.Close
set fname=nothing
set fs=nothing
%>
The FileSystemObject object's properties and methods are described below:
Properties
Drives
The Drives property returns a collection of all Drive objects on the computer.
Methods
1.BuildPath
Syntax
[newpath=]FileSystemObject.BuildPath(path,name)
Example
<%
dim fs,path
set fs=Server.CreateObject("Scripting.FileSystemObject")
path=fs.BuildPath("c:\mydocuments","test")
response.write(path)
set fs=nothing
%>
Output:
c:\mydocuments\test
2.CopyFile
The CopyFile method copies one or more files from one location to another.
Syntax
FileSystemObject.CopyFile source,destination[,overwrite]
Parameter Description
destination Required. Where to copy the file or files (wildcards cannot be used}
overwrite Optional. A Boolean value that specifies whether an existing file can be overwritten.
True allows existing files to be overwritten and False prevents existing files from
being overwritten. Default is True
Example
<%
dim fs
set fs=Server.CreateObject("Scripting.FileSystemObject")
fs.CopyFile "c:\mydocuments\web\*.htm","c:\webpages\"
set fs=nothing
%>
3.CopyFolder
Syntax
FileSystemObject.CopyFolder source,destination[,overwrite]
Parameter Description
destination Required. Where to copy the folder or folders (wildcards cannot be used)
overwrite Optional. A Boolean value that indicates whether an existing folder can be
overwritten. True allows existing folders to be overwritten and False prevents
existing folders from being overwritten. Default is True
Examples
<%
'copy all the folders in c:\mydocuments\web
'to the folder c:\webpages
dim fs
set fs=Server.CreateObject("Scripting.FileSystemObject")
fs.CopyFolder "c:\mydocuments\web\*","c:\webpages\"
set fs=nothing
%>
<%
'copy only the folder test from c:\mydocuments\web
'to the folder c:\webpages
dim fs
set fs=Server.CreateObject("Scripting.FileSystemObject")
fs.CopyFolder "c:\mydocuments\web\test","c:\webpages\"
set fs=nothing
%>
4.CreateFolder
5.CreateTextFile
The CreateTextFile method creates a new text file in the current folder and returns a TextStream object
that can be used to read from, or write to the file.
FolderObject.CreateTextFile(filename[,overwrite[,unicode]])
Parameter Description
Overwrite Optional. A Boolean value that indicates whether an existing file can be overwritten.
True indicates that the file can be overwritten and False indicates that the file can not
be overwritten. Default is True
Unicode Optional. A Boolean value that indicates whether the file is created as a Unicode or
an ASCII file. True indicates that the file is created as a Unicode file, False indicates
that the file is created as an ASCII file. Default is False
6.DeleteFile
Note: An error will occur if you try to delete a file that doesn't exist.
Syntax
FileSystemObject.DeleteFile(filename[,force])
Parameter Description
filename Required. The name of the file or files to delete (Wildcards are allowed)
force Optional. A Boolean value that indicates whether read-only files will be deleted.
True indicates that the read-only files will be deleted, False indicates that they will
not be deleted. Default is False
Example
<%
dim fs
Set fs=Server.CreateObject("Scripting.FileSystemObject")
fs.CreateTextFile("c:\test.txt",True)
if fs.FileExists("c:\test.txt") then
fs.DeleteFile("c:\test.txt")
end if
set fs=nothing
%>
7.DeleteFolder
Note: An error will occur if you try to delete a folder that does not exist.
Syntax
FileSystemObject.DeleteFolder(foldername[,force])
Parameter Description
foldername Required. The name of the folder or folders to delete (Wildcards are allowed)
force Optional. A Boolean value that indicates whether read-only folders will be deleted.
True indicates that read-only folders will be deleted, False indicates that they will
not be deleted. Default is False
8.GetFile
The GetFile method returns a File object for the specified path.
Syntax
FileSystemObject.GetFile(path)
Parameter Description
Example
<%
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.GetFile("c:\test\test.htm")
Response.Write("The file was last modified on: ")
Response.Write(f.DateLastModified)
set f=nothing
set fs=nothing
%>
Output:
The file was last modified on 01/01/20 4:23:56 AM
9.MoveFile
The MoveFile method moves one or more files from one location to another.
Syntax
FileSystemObject.MoveFile source,destination
Parameter Description
source Required. The path to the file/files to be moved. Can contain wildcard characters in
destination Required. Where to move the file/files. Cannot contain wildcard characters
Example
<%
dim fs
set fs=Server.CreateObject("Scripting.FileSystemObject")
fs.MoveFile "c:\web\*.gif","c:\images\"
set fs=nothing
%>
10.OpenTextFile
The OpenTextFile method opens a specified file and returns a TextStream object that can be used to
access the file.
Syntax
FileSystemObject.OpenTextFile(fname,mode,create,format)
Parameter Description
create Optional. Sets whether a new file can be created if the filename does not exist. True
indicates that a new file can be created, and False indicates that a new file will not be
created. False is default
Example
<%
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.OpenTextFile(Server.MapPath("testread.txt"),8,true)
The following code creates a text file (c:\test.txt) and then writes some text to the file (the variable f is an
instance of the TextStream object):
<%
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.CreateTextFile("c:\test.txt",true)
f.WriteLine("Hello World!")
f.Close
set f=nothing
set fs=nothing
%>
To create an instance of the TextStream object you can use the CreateTextFile or OpenTextFile methods
of the FileSystemObject object, or you can use the OpenAsTextStream method of the File object.
Properties
Property Description
AtEndOfLine Returns true if the file pointer is positioned immediately before the end-of-line
marker in a TextStream file, and false if not
AtEndOfStream Returns true if the file pointer is at the end of a TextStream file, and false if not
Column Returns the column number of the current character position in an input stream
Example:
<%
dim fs,f,t,x
set fs=Server.CreateObject("Scripting.FileSystemObject")
set t=fs.OpenTextFile("c:\test.txt",1,false)
do while t.AtEndOfLine<>true
x=t.Read(1)
loop
t.close
Response.Write("The last character is: " & x)
%>
Output:
The last character of the first line in the text file is: !
Methods
1.Close
2. Read
The Read method reads a specified number of characters from a TextStream file and returns the result as a
string.
Syntax
TextStreamObject.Read(numchar)
Parameter Description
Example
<%
dim fs,f,t,x
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.CreateTextFile("c:\test.txt")
f.write("Hello World!")
f.close
set t=fs.OpenTextFile("c:\test.txt",1,false)
x=t.Read(5)
t.close
3.ReadAll
4.ReadLine
The ReadLine method reads one line from a TextStream file and returns the result as a string.
Syntax
TextStreamObject.ReadLine
Example
<%
dim fs,f,t,x
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.CreateTextFile("c:\test.txt")
f.writeline("Line 1")
f.writeline("Line 2")
f.writeline("Line 3")
f.close
set t=fs.OpenTextFile("c:\test.txt",1,false)
x=t.ReadLine
t.close
Response.Write("The first line in the file ")
Response.Write("contains this text: " & x)
%>
Output:
The first line in the file contains this text: Line 1
5.Write
Note: This method write text to the TextStream file with no spaces or line breaks between each string.
Syntax
TextStreamObject.Write(text)
Parameter Description
Example
<%
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.CreateTextFile("c:\test.txt",true)
f.write("Hello World!")
f.write("How are you today?")
f.close
set f=nothing
set fs=nothing
%>
The file test.txt will look like this after executing the code above:
6.WriteLine
The WriteLine method writes a specified text and a new-line character to a TextStream file.
Syntax
TextStreamObject.WriteLine(text)
Parameter Description
text Optional. The text to write to the file. If you do not specify this parameter, a new-
line character will be written to the file
Example
<%
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.CreateTextFile("c:\test.txt",true)
f.WriteLine("Hello World!")
f.WriteLine("How are you today?")
f.WriteLine("Goodbye!")
f.close
set f=nothing
set fs=nothing
%>
Hello World!
How are you today?
Goodbye!
To work with the properties and methods of the File object, you will have to create an instance of the File
object through the FileSystemObject object. First; create a FileSystemObject object and then instantiate
the File object through the GetFile method of the FileSystemObject object or through the Files property
of the Folder object.
The following code uses the GetFile method of the FileSystemObject object to instantiate the File object
and the DateCreated property to return the date when the specified file was created:
Example
<%
Dim fs,f
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set f=fs.GetFile("c:\test.txt")
Response.Write("File created: " & f.DateCreated)
set f=nothing
set fs=nothing
%>
Properties
Property Description
DateCreated Returns the date and time when a specified file was created
DateLastAccessed Returns the date and time when a specified file was last accessed
DateLastModified Returns the date and time when a specified file was last modified
ParentFolder Returns the folder object for the parent of the specified file
ShortName Returns the short name of a specified file (the 8.3 naming convention)
ShortPath Returns the short path of a specified file (the 8.3 naming convention)
Methods
Method Description
OpenAsTextStream Opens a specified file and returns a TextStream object to access the file
Regardless of your level of experience, you will encounter programmatic errors, or bugs, that will prevent
your server-side scripts from working correctly. For this reason, debugging, the process of finding and
correcting scripting errors, is crucial for developing successful and robust ASP applications, especially as
the complexity of your application grows. Various tools like Visual Studio can be used to debug ASP
Applications.
The Microsoft Script Debugger is a powerful debugging tool that can help you quickly locate bugs and
interactively test your server-side scripts. You can do the following things using the features of Microsoft
Script Debugger:
Enabling Debugging
Before you can begin debugging your server-side scripts, you must first configure your Web server to
support ASP debugging.
After enabling Web server debugging, you can use either of the following methods to debug your scripts:
Open Script Debugger and use it to run and debug your ASP server-side scripts.
Use Internet Explorer to request an .asp file. If the file contains a bug or an intentional statement to
halt execution, Script Debugger will automatically start, display your script, and indicate the
source of the error.
Scripting Errors
While debugging your server-side scripts you might encounter several types of errors. Some of these
errors can cause your scripts to execute incorrectly, halt the execution of your program, or return incorrect
results.
Syntax Errors
A syntax error is a commonly encountered error that results from incorrect scripting syntax. For example,
a misspelled command or an incorrect number of arguments passed to a function generates an error.
Syntax errors can prevent your script from running.
Runtime Errors
Run-time errors occur after your script commences execution and result from scripting instructions that
attempt to perform impossible actions. For example, the following script contains a function that divides a
variable by zero (an illegal mathematical operation) and generates a run-time error:
Function Findanswer(x)
'This statement generates a run-time error.
Findanswer = x/0
End Function
</SCRIPT>
Bugs that result in run-time errors must be corrected for your script to execute without interruption.
Logical Errors
Just-In-Time(JIT) Debugging
When a run-time error interrupts execution of your server-side script, the Microsoft Script Debugger
automatically starts, displays the .asp file with a statement pointer pointing to the line that caused the
error, and generates an error message. With this type of debugging, called? Just-In-Time (JIT) debugging,
your computer suspends further execution of the program. You must correct the errors with an editing
program and save your changes before you can resume running the script.
Breakpoint Debugging
When an error occurs and you cannot easily locate the source of the error, it is sometimes useful to preset
a breakpoint. A breakpoint suspends execution at a specific line in your script. You can set one or many
different breakpoints in Microsoft Script Debugger before a suspect line of script and then use the
debugger to inspect the values of variables or properties set in the script. After you correct the error, you
can clear your breakpoints so that your script can run uninterrupted.
To set a breakpoint, open your script with Script Debugger, select a line of script where you want to
interrupt execution, and from the Debug menu choose Toggle Breakpoint. Then use your Web browser
to request the script again. After executing the lines of script up to the breakpoint, your computer starts
the Script Debugger, which displays the script with a statement pointer pointing to the line where you set
the breakpoint.
In certain cases, you may want to enable the Script Debugger Break at Next Statement if the next
statement that runs is not in the .asp file that you are working with. For example, if you set Break at Next
Statement in an .asp file residing in an application called Sales, the debugger will start when you run a
script in any file in the Sales application, or in any application for which debugging has been enabled. For
this reason, when you set Break at Next Statement, you need to be aware that whatever script statement
runs next will start the debugger.
You can also add breakpoints to your server-side scripts written in VBScript by inserting
a Stop statement at a location before a questionable section of server-side script. For example, the
following server-side script contains aStop statement that suspends execution before the script calls a
custom function:
VBScript
<%
intDay = Day(Now())
lngAccount = Request.Form("AccountNumber")
dtmExpires = Request.Form("ExpirationDate")
The ASPError object was implemented in ASP 3.0 and is available in IIS5 and later.
The ASPError object is used to display detailed information of any error that occurs in scripts in an ASP
page.
Note: The ASPError object is created when Server.GetLastError is called, so the error information can
only be accessed by using the Server.GetLastError method.
The ASPError object's properties are described below (all properties are read-only):
Properties
Property Description
ASPDescription Returns a detailed description of the error (if the error is ASP-related)
Category Returns the source of the error (was the error generated by ASP? By a scripting
language? By an object?)
Column Returns the column position within the file that generated the error
File Returns the name of the ASP file that generated the error
Line Returns the line number where the error was detected
Number Returns the standard COM error code for the error
Error Handling
Handling errors is achieved by using the On Error Resume Next statement. It simply tells the ASP
interpreter to continue the execution of the ASP Script if there is an error instead of throwing an exception
and stopping the execution.
To trap and handle the errors, we need to use the Err Object and its properties
Handle_Error(Err.Description)
Err.Clear
End If
%>
%>
Error handling allows you to display friendly error messages for the end users and the same time it helps
you debug the asp application.
The ASP Browser Capabilities component creates a BrowserType object that determines the type,
capabilities and version number of a visitor's browser.
When a browser connects to a server, a User Agent header is also sent to the server. This header contains
information about the browser.
The BrowserType object compares the information in the header with information in a file on the server
called "Browscap.ini".
If there is a match between the browser type and version number in the header and the information in the
"Browsercap.ini" file, the BrowserType object can be used to list the properties of the matching browser.
If there is no match for the browser type and version number in the Browscap.ini file, it will set every
property to "UNKNOWN".
Syntax
<%
Set MyBrow=Server.CreateObject("MSWC.BrowserType")
%>
The example below creates a BrowserType object in an ASP file, and displays some of the capabilities of
your browser:
Example
<html>
<body>
<%
Set MyBrow=Server.CreateObject("MSWC.BrowserType")
%>
</body>
</html>
Output:
Client OS WinNT
Web Browser IE
Browser version 5.0
Frame support? True
Table support? True
Sound support? True
Cookies support? True
VBScript support? True
JavaScript support? True
The "Browsercap.ini" file is used to declare properties and to set default values for browsers.
This section is not a tutorial on how to maintain "Browsercap.ini" files, it only shows you the basics; so
you get an idea what a "Browsercap.ini" file is all about.
[;comments]
[HTTPUserAgentHeader]
[parent=browserDefinition]
[property1=value1]
[propertyN=valueN]
[Default Browser Capability Settings]
[defaultProperty1=defaultValue1]
[defaultPropertyN=defaultValueN]
Parameter Description
comments Optional. Any line that starts with a semicolon are ignored by the BrowserType
object
HTTPUserAgentHeader Optional. Specifies the HTTP User Agent header to associate with the browser-
property value statements specified in propertyN. Wildcard characters are allowed
browserDefinition Optional. Specifies the HTTP User Agent header-string of a browser to use as the
;IE 5.0
[IE 5.0]
browser=IE
Version=5.0
majorver=#5
minorver=#0
frames=TRUE
tables=TRUE
cookies=TRUE
backgroundsounds=TRUE
vbscript=TRUE
javascript=TRUE
javaapplets=TRUE
ActiveXControls=TRUE
;DEFAULT BROWSER
[*]
browser=Default
frames=FALSE
tables=TRUE
cookies=FALSE
backgroundsounds=FALSE
vbscript=FALSE
javascript=FALSE
CDOSYS(CDO) is a built-in component in ASP. This component is used to send e-mails with ASP.
CDO (Collaboration Data Objects) is a Microsoft technology that is designed to simplify the creation of
messaging applications.CDOSYS is a built-in component in ASP.
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.TextBody="This is a message."
myMail.Send
set myMail=nothing
%>
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.Bcc="someoneelse@somedomain.com"
myMail.Cc="someoneelse2@somedomain.com"
myMail.TextBody="This is a message."
myMail.Send
set myMail=nothing
%>
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.HTMLBody = "<h1>This is a message.</h1>"
myMail.Send
set myMail=nothing
%>
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.CreateMHTMLBody "http://www.w3schools.com/asp/"
myMail.Send
set myMail=nothing
%>
Sending an HTML e-mail that sends a webpage from a file on your computer:
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.CreateMHTMLBody "file://c:/mydocuments/test.htm"
myMail.Send
set myMail=nothing
%>
<%
Set myMail=CreateObject("CDO.Message")
myMail.Subject="Sending email with CDO"
myMail.From="mymail@mydomain.com"
myMail.To="someone@somedomain.com"
myMail.TextBody="This is a message."
myMail.AddAttachment "c:\mydocuments\test.txt"
myMail.Send
set myMail=nothing
%>
Connection Object
The ADO Connection Object is used to create an open connection to a data source. Through this connection, you
can access and manipulate a database.
If you want to access a database multiple times, you should establish a connection using the Connection object.
You can also make a connection to a database by passing a connection string via a Command or Recordset
object. However, this type of connection is only good for one specific, single query.
set objConnection=Server.CreateObject("ADODB.connection")
Properties
Property Description
ConnectionString Sets or returns the details used to create a connection to a data source
ConnectionTimeout Sets or returns the number of seconds to wait for a connection to open
Provider Sets or returns the provider name
State Returns a value describing if the connection is open or closed
Version Returns the ADO version number
Methods
Method Description
BeginTrans Begins a new transaction
Cancel Cancels an execution
Close Closes a connection
CommitTrans Saves any changes and ends the current transaction
Execute Executes a query, statement, procedure or provider specific text
Open Opens a connection
RollbackTrans Cancels any transaction
The ADO Command object is used to execute a single query against a database. The query can perform actions
like creating, adding, retrieving, deleting or updating records.
If the query is used to retrieve data, the data will be returned as a RecordSet object. This means that the retrieved
data can be manipulated by properties, collections, methods, and events of the Recordset object.
The major feature of the Command object is the ability to use stored queries and procedures with parameters.
set objCommand=Server.CreateObject("ADODB.command")
Properties
Property Description
ActiveConnection Sets or returns a definition for a connection if the connection is closed, or
the current Connection object if the connection is open
CommandText Sets or returns a provider command
CommandType Sets or returns the type of a Command object
Name Sets or returns the name of a Command object
State Returns a value that describes if the Command object is open, closed,
connecting, executing or retrieving data
Methods
Method Description
Cancel Cancels an execution of a method
CreateParameter Creates a new Parameter object
Execute Executes the query, SQL statement or procedure in the CommandText
property
Collections
Collection Description
Parameters Contains all the Parameter objects of a Command Object
Recordset Object
The ADO Recordset object is used to hold a set of records from a database table. A Recordset object consist of
records and columns (fields).
In ADO, this object is the most important and the one used most often to manipulate data from a database.
set objRecordset=Server.CreateObject("ADODB.recordset")
When you first open a Recordset, the current record pointer will point to the first record and the BOF and EOF
properties are False. If there are no records, the BOF and EOF property are True.
Methods
Method Description
AddNew Creates a new record
Cancel Cancels an execution
CancelUpdate Cancels changes made to a record of a Recordset object
The common way to access a database from inside an ASP page is to:
1. Create an ADO connection to a database
2. Open the database connection
3. Create an ADO recordset
4. Open the recordset
5. Extract the data you need from the recordset
6. Close the recordset
7. Close the connection
<%
'declare the variable that will hold new connection object
Dim Connection
'create an ADO connection object
Set Connection=Server.CreateObject("ADODB.Connection")
'Open the recordset object executing the SQL statement and return records
Recordset.Open SQL, Connection
%>
We have returned a recordset based on our SQL statement so let's now print out them in the browser.
<%
'first of all determine whether there are any records
Finally, need to close the objects and free up resources on the server.
<%
Recordset.Close
Set Recordset=Nothing
Connection.Close
Set Connection=Nothing
%>
Let’s look at a sample script to get an idea how to connect to MS SQL Server database without DSN:
<%
'declare the variables
Dim Connection
Dim ConnString
Dim Recordset
Dim SQL
'Open the recordset object executing the SQL statement and return records
Recordset.Open SQL,Connection
Let’s look at a sample script to get an idea how to connect to MySQL database without DSN:
<%
'declare the variables
Dim Connection
Dim ConnectionString
Dim Recordset
Dim SQL
'Open the recordset object executing the SQL statement and return records
Recordset.Open SQL,Connection
Insert
Connection.Execute(sql)
Delete
Filter
The Filter property sets or returns a variant that contains a filter for the data in a Recordset object. The filter
allows you to select records that fit a specific criteria.
When the Filter property is set, the cursor moves to the first record in the filtered Recordset. And, when the Filter
property is cleared, the cursor moves to the first record in the unfiltered Recordset.
• rs.Filter="name='Smith'"
• rs.Filter="name='Smith' AND Birthdate >= #4/10/70#"
• rs.Filter="Lastname='Jonson' OR Lastname='Johnson'"
• rs.Filter= "Lastname LIKE Jon*"
• rs.Filter = adFilterNone 'removes the filter'
Stored Procedures
A Stored Procedure is a prepared sql code that is saved into the database so that it can be reused over and over
again. It is also possible to pass parameters to the stored procedure. A stored procedure can be a group of SQL
statements compiled into a single execution plan.
Examples:
Stored Procedure for the Query : “Select * from Students”
Create PROCEDURE GetStudents
As BEGIN
Select * from Students
End
GO
Stored procedure for insert sql statement
These 3 methods is used with the Connection object to save or cancel changes made to the data source.
BeginTrans
The BeginTrans method starts a new transaction.
CommitTrans
The CommitTrans method saves all changes made since the last BeginTrans method call, and ends the current
transaction.
Since transactions can be nested, all lower-level transactions must be resolved before you can resolve higher-
level transactions.
RollbackTrans
The RollbackTrans method cancels all changes made since the last BeginTrans method call, and ends the
transaction.
.NET is a software development and application execution environment that allows us to create, compile, test,
deploy, and execute software that may be coded in a variety of different programming languages that adhere to a
single set of Common Language Runtime files.
From a high-level view, the .NET Framework can be described as a little virtual operating system that runs on
top of the operating systems.
The .NET Framework is an integral Windows component that supports building and running the next generation
of applications. The .NET Framework is designed to fulfil the following objectives:
To provide a consistent object-oriented programming environment whether object code is stored and
executed locally, executed locally but Internet-distributed, or executed remotely.
To provide a code-execution environment that minimizes software deployment and versioning conflicts.
To provide a code-execution environment that promotes safe execution of code, including code created
by an unknown or semi-trusted third party.
To provide a code-execution environment that eliminates the performance problems of scripted or
interpreted environments.
To make the developer experience consistent across widely varying types of applications, such as
Windows-based applications and Web-based applications.
1. At the bottom of the Architecture is Common Language Runtime. Dot NET Framework common
language runtime resides on top of the operating system services. The common language runtime loads
and executes code that targets the runtime. The runtime gives you, for example, the ability for cross-
language integration.
2. .NET Framework provides a rich set of class libraries. These include base classes, like networking and
input/output classes, a data class library for data access, and classes for use by programming tools, such
as debugging services. All of them are brought together by the Services Framework, which sits on top of
the common language runtime.
3. ADO.NET is Microsoft ActiveX Data Object (ADO) model for the .NET Framework. ADO.NET is not
simply the migration of the popular ADO model to the managed environment but a completely new
paradigm for data access and manipulation.
1
ADO.NET is intended specifically for developing web applications. This is evident from its two major
design principles:
1. Disconnected Datasets In ADO.NET, almost all data manipulation is done outside the context of
an open database connection.
2. Effortless Data Exchange with XMLDatasets can converse in the universal data format of the
Web, namely XML.
4. The 4th layer of the framework consists of the Windows application model and, in parallel, the Web
application model.
The Web application model-in the slide presented as ASP.NET-includes Web Forms and Web
Services.ASP.NET comes with built-in Web Forms controls, which are responsible for generating the
user interface. They mirror typical HTML widgets like text boxes or buttons. If these controls do not fit
your needs, you are free to create your own user controls.
Web Services brings you a model to bind different applications over the Internet. This model is based on
existing infrastructure and applications and is therefore standard-based, simple, and adaptable.
Web Services are software solutions delivered via Internet to any device. Today, that means Web
browsers on computers, for the most part, but the device-agnostic design of .NET will eliminate this
limitation.
5. One of the obvious themes of .NET is unification and interoperability between various programming
languages. In order to achieve this; certain rules must be laid and all the languages must follow these
rules. In other words we cannot have languages running around creating their own extensions and their
own fancy new data types. CLS is the collection of the rules and constraints that every language (that
seeks to achieve .NET compatibility) must follow.
6. The CLR and the .NET Frameworks in general, however, are designed in such a way that code written in
one language can not only seamlessly be used by another language. Hence ASP.NET can be
programmed in any of the .NET compatible language whether it is VB.NET, C#, Managed C++ or
JScript.NET/
The main two components of .NET Framework are: the common language runtime and the class library.
Establishes a framework that helps enable cross-language integration, type safety, and high performance
code execution.
Provides an object-oriented model that supports the complete implementation of many programming
languages.
Defines rules that languages must follow, which helps ensure that objects written in different languages
can interact with each other.
When compilers emit code to run on the CLR, they do not emit machine language code. Rather, an intermediate
language code is used called Microsoft Intermediate Language (MSIL). MSIL is like an object-oriented version
of assembly language and is platform independent. It has a rich set of instructions that enable efficient
representation of the code. When a code starts to execute, a process knowing as Just in Time Compilation
(JIT) converts the MSIL code into the native processor instructions of the platform, which is then executed.
For example, the .NET Framework collection classes implement a set of interfaces that you can use to develop
your own collection classes. Your collection classes will blend seamlessly with the classes in the .NET
Framework.
The .NET Framework types enable you to accomplish a range of common programming tasks, including tasks
such as string management, data collection, database connectivity, and file access. In addition to these common
tasks, the class library includes types that support a variety of specialized development scenarios. For example,
the Windows Forms classes are a comprehensive set of reusable types that vastly simplify Windows GUI
development. If you write an ASP.NET Web Form application, you can use the Web Forms classes.
.Net Languages
.Net framework supports many programming languages. Some of them are Visual Basic(VB), C#, C++, F# and
others.
C# Language
C# is an elegant and type-safe object-oriented language that enables developers to build a wide range of secure
and robust applications that run on the .NET Framework. You can use C# to create traditional Windows client
applications, Web applications, client-server applications, database applications and much more. C# syntax is
highly expressive, yet with less than 90 keywords, it is also simple and easy to learn.
It is a Case-Sensitive object-oriented language which supports the concepts of encapsulation, inheritance and
polymorphism. All variables and methods, including the Main method, the application's entry point, are
3
encapsulated within class definitions. A class may inherit directly from one parent class, but it may implement
any number of interfaces.
C# language is developed by Microsoft. The name "C sharp" was inspired by musical notation where a sharp
indicates that the written note should be made a semitone higher in pitch.
Sample C# Program
//HelloWorld Program in c#
using System;
namespace HelloWorld
{
class Hello
{
static void Main()
{
Console.WriteLine("Hello World!");
using System;
namespace NamespaceReadString
{
public class ReadString {
public static void Main() {
string str;
Console.WriteLine("Enter some characters.");
str = Console.ReadLine();
Console.WriteLine("You entered: " + str);
Console.ReadKey();
}
}
}
Namespace in c#
Namespaces are C# program elements designed to help you organize your programs. A Namespace is simply a
logical collection of related classes in C#. We bundle our related classes in some named collection calling it a
namespace. As C# does not allow to classes with the same name to be used in a program, the sole purpose of
using namespaces is to prevent name conflicts. For example, if you created a class named Console, you would
need to put it in your own namespace, say MyNamespace, to ensure that there wasn't any confusion about when
the System.Console class should be used or when your class should be used. To avoid this, these classes are
made part of their respective namespace. So the fully qualified name of these classes will be
MyNamespace.Console and System.Console, hence resolving any ambiguity for the compiler. The namespace
may contain classes, events, exceptions, delegates and even other namespaces called ‗Internal namespace‘. For
Example.
namespace N1 // N1
{
class C1 // N1.C1
{
class C2 // N1.C1.C2
{
}
}
namespace N2 // N1.N2
{
class C2 // N1.N2.C2
{
}
}
}
Namespaces don't correspond to file or directory names. If naming directories and files to correspond to
namespaces helps you organize your code, then you may do so, but it is not required.
The using keyword allows us to use the classes in the following namespace. For example:
using System;
By doing this, we can now access all the classes defined in the System namespace like we are able to access the Console
class in our Main method. using allows us to access the classes in the referenced namespace only and not in its
internal/child namespace. Hence we might need to write
using System.Collections;
in order to access the classes defined in Collection namespace which is a sub/internal namespace of System namespace.
A C# application must contain a Main method, in which control starts and ends. The Main method is where you
create objects and execute other methods.The Main method is a static method that resides inside a class or a
struct. The main method is the entry point of our program. The main method is designated as static as it will be
called by the Common Language Runtime (CLR) without making any object.
In the previous "Hello World!" example, it resides in a class named Hello. You can declare the Main method in
one of the following ways:
Variables
During the execution of program, data is temporarily stored in memory. A variable is the name given to a
memory location holding particular type of data. Each variable is associated with a data type and value.
<data_type> <variable>;
Eg: int i;
string myName;
Constants
Constants once defined, the value cannot be changed by program. All the constants are replaced by their values at the
compile time.
Eg. const double PI 3.1416
Operators in C#
C# provides a large set of operators, which are symbols that specify which operations to perform in an expression.
Arithmetic operators: +,-,*,/,%,++,--
Assignment operators: =,+=,…
Relational operators: ==,!=,<,>,<=,>=
Logical operators: &, |, ^, !, ||
Example:
static void Main(string[] args)
{
int num1 = int.parse(args[0]);
int num2 = int.parse(args[1]);
int sum = num1+num2;
Console.WriteLine(―Sum of {0} and {1} is {2}.‖,num1,num2,sum);
Console.WriteLine(―Sum of ‖+ num1+ ―and‖ + num2 + ―is‖ + sum);
}
Blocks
The C#, Java, and C languages all rely heavily on curly braces—parentheses with a little more attitude: {}.Curly
braces group multiple code statements together. Typically, the reason you‘ll want to group code statements
together is because you want them to be repeated in a loop, executed conditionally, or grouped into a function.
{
// Code statements go here.
}
Loops
Looping statements repeat a specified block of code until a given condition is met.
For loop
for (int i = 0; i<=9; i++)
{
System.Console.WriteLine(i);
}
foreach Loops
static void Main()
{
string[] arr= new string[] {"Jan", "Feb", "Mar"};
Conditional Logic
If else
{
// Do something.
}
else
{
// Do something.
}
switch
C# also provides a switch statement that you can use to evaluate a single variable or expression for multiple
possible values. The only limitation is that the variable you‘re evaluating must be an integer-based data type, a
bool, a char, a string, or a value from an enumeration.
In the following code, each case examines the myNumber variable and tests whether it‘s equal to a specific
integer:
switch (myNumber)
{
case 1:
// Do something.
break;
case 2:
// Do something.
break;
default:
// Do something.
break;
}
Declaration
Single Dimension Array
<data_type>[ ] <identifier> = new <data_type> [<size>]
Multidimension Array
8
Declaring arrays does not actually create the arrays. In C#, arrays are objects and must be instantiated.
foreach
foreach statement provides a simple, clean way to iterate through the elements of an array.
foreach(<type_of_element> <identifier> in <array>)
{
<statement or set of statements>
}
foreach(int i in numbers)
{
Console.WriteLine(i);
}
In foreach, variable used to hold the individual elements of array in each iteration is read only. The elements in
array cannot be changed through it. This means that foreach will only allow to iterate through the array or
collection and not to change the contents of it. foreach can be used to iterate through arrays or collections. By
collection, we mean any class, struct or interface that implements the IEnumerable interface.
String is also the collection of characters. So you can iterate over a string using foreach.
String firstName = ―Michael‖;
Foreach(char ch in firstName)
{
Console.WriteLine(ch);
}
A class is a construct that enables us to create your own custom types by grouping together variables of other
types, methods and events. Together, these elements are called class members. A class is simply an abstract
model used to define a new data types. A class may contain any combination of encapsulated data (fields or
member variables), operations that can be performed on data (methods) and accessors to data(properties).
For example, there is a class String in the System namespace of .Net framework Class Library. This class contains an
array of characters (data) and provide different operations (methods) that can be applied to its data like ToLowerCase(),
Trim(), Substring() etc. It also has some propertied like Length.
An object is the concrete realization of instance built on the model specified by the class. An object is created in
the memory using the keyword ‗new‘ and is referenced by an identifier called a ―reference‖.
For example: MyClass myClassObject=new MyClass();
In this example, an object of MyClass is referenced by an identifier myClassObject .
Fields are the data contained in the class. Fields may be implicit data types, objects of some other class,
enumerations, structs or delegates.
Methods are the operations performed on the data. A method may take some input values through its parameters
and may return a value of particular data type.
A static class is a class which cannot be instantiated. Static classes and class members are used to create data and
functions that can be accessed without creating an instance of the class. Static class members can be used to
separate data and behavior that is independent of any object identity i.e. the data and functions do not change
regardless of what happens to the object.
Keyword static is used to define a static class and static class members.
Example
Access Modifiers
Access modifiers are keywords used to specify the declared accessibility of a member or a type. C# has
introduced the four access modifiers: public, protected, internal, and private.
The following five accessibility levels can be specified using the access modifiers:
public: Access is not restricted.
protected: Access is limited to the containing class or types derived from the containing class.
Internal: Access is limited to the current project(Assembly).
protected internal: Access is limited to the current project(Assembly) or types derived from the containing
class.
private: Access is limited to the containing type.
Example:
using System;
namespace StudentNamespace
{
public class student
{
//fields
private int age,markMaths,markSci,markEng,obt;
private string name;
private double percentage;
//methods
10
Properties
Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields.
Properties can be used as though they are public data members, but they are actually special methods called
accessors. This enables data to be accessed easily while still providing the safety and flexibility of methods.
Since all the fields of class are made private, to assign values to them through their reference ‗Properties‘ is
used. C# is the first language to provide the support of defining properties in the languages core. Properties hold
specific information relevant to that class of object. Properties can be thought as characteristics of the objects
that they represent. In traditional languages like java and C++, for accessing the private fields of class, public
methods called getters (to retrieve the value) and setters (to assign the value) were defined like if we have a
private field name:
private string name;
then the getters and setters would be like
//getter to name field
public string GetName()
{
return name;
}
//setter to name field
public void SetName(string theName)
{
name=theName;
}
11
These procedures gives a lot of control over how fields of classes should be accessed and dealt in a program.
But, the problem is that two methods have to be defined and have to prefix the name of fields with Get or Set.
C# provides the built in support for these getters and setters in the form of properties. Properties are context
sensitive constructs used to read, write or compute private fields of class land to achieve control over how the
fields can be accessed. The general syntax for properties is
<access_modifier> <data_type> <name_of_property>
{
get
{
//some optional statements
return <some_private_fields>;
}
set
{
//some optional statements
<some_private_fields>=value;
}
}
Example:
class TimePeriod
{
private double seconds;
class Program
{
static void Main()
{
TimePeriod t = new TimePeriod();
Auto-Implemented Properties
Auto-implemented properties make property-declaration more concise when no additional logic is required in
the property accessors. When you declare a property as shown in the following example, the compiler creates a
private, anonymous backing field that can only be accessed through the property's get and set accessors.
class Customer
{
12
class Program
{
static void Main()
{
// Intialize a new object.
Customer cust1 = new Customer ( 4987.63, "Northwind");
//Modify a property
cust1.TotalPurchases += 499.99;
}
}
Constructors
Constructors are class methods that are executed when an object of a class or struct is created. They have the
same name as the class or struct, and usually initialize the data members of the new object. A class or struct may
have multiple constructors that take different arguments. Constructors enable the programmer to set default
values, limit instantiation, and write code that is flexible and easy to read.
If you do not provide a constructor for your object, C# will create one by default that instantiates the object and
sets member variables to the default values.
In the following example, a class named Taxi is defined by using a simple constructor. This class is then
instantiated with the new operator. The Taxi constructor is invoked by the new operator immediately after
memory is allocated for the new object.
{
isInitialized = true;
}
}
class TestTaxi
{
static void Main()
{
Taxi t = new Taxi();
Console.WriteLine(t.isInitialized);
}
}
A constructor that takes no parameters is called a default constructor. Default constructors are invoked whenever
an object is instantiated by using the new operator and no arguments are provided to new.
It is possible to have more than one method with the same name and return type but with different number and types of
arguments (parameters). This is called method overloading. For example, in the following class MathUtil, we have
defined two methods with the name plus. Both of them have same return type but the first one has two parameters
whereas the second one has 3 parameters. When plus() is called, the compiler will decide, on the basis of the types and
number of parameters being passed, which one of these two to actually call, for example, plus(2,3) calls the first one and
plus(2,3,4) calls the second one.
Class MathUtil
{
public static int plus(int n1, int n2)
{
return(n1+n2);
}
public static int plus(int n1, int n2, int n3)
{
return (n1 + n2 +n3);
}
Static void Main()
{
plus(2,3);
plus(2,3,4);
}
}
Methods are overloaded depending on the parameter list and not on the return type. The WriteLine() method of Console
class in the System namespace has 19 different overloaded forms.
Passing Parameters
In C# variables are of two types: reference types and value types.
A reference type is a type which has as its value a reference to the appropriate data rather than the data itself.
Array is a reference type. Similarly Class types, interface types, delegate types are all reference types.
A value type is a type which contains the actual data. Variables of a value type directly contain the data. Simple
types such as float, int, char are all value types.
In C#, parameters can be passed either by value or by reference. Passing parameters by reference allows function
members (methods, properties, constructors) to change the value of the parameters and have that change persist.
To pass a parameter by reference, use the ref or out keyword.
using System;
class PassingValByRef
{
static void SquareIt(ref int x)
// The parameter x is passed by reference.
// Changes to x will affect the original value of myInt.
{
x *= x;
Console.WriteLine("The value inside the method: {0}", x);
//output: The value inside the method: 25
}
public static void Main()
{
int myInt = 5;
Console.WriteLine("The value before calling the method: {0}",
myInt);
//output: The value before calling the method: 5
SquareIt(ref myInt); // Passing myInt by reference.
Console.WriteLine("The value after calling the method: {0}",
myInt);
//Output: The value after calling the method: 25
}
}
In this example, it is not the value of myInt that is passed; rather, a reference to myInt is passed. The parameter x
is not an int; it is a reference to an int (in this case, a reference to myInt). Therefore, when x is squared inside the
method, what actually gets squared is what x refers to: myInt.
16
class OutExample
{
static void Method(out int i)
{
i = 44;
}
static void Main()
{
int value;
Method(out value);
// value is now 44
}
}
A common example of changing the values of the passed parameters is the Swap method, where you pass two
variables, x and y, and have the method swap their contents. You must pass the parameters to the Swap method
by reference; otherwise, you will be dealing with a local copy of the parameters inside the method. The
following is an example of the Swap method that uses reference parameters:
When you call this method, use the ref keyword in the call, like this:
A variable of a reference type does not contain its data directly; it contains a reference to its data. When you pass
a reference-type parameter by value, it is possible to change the data pointed to by the reference, such as the
value of a class member. However, you cannot change the value of the reference itself; that is, you cannot use
the same reference to allocate memory for a new class and have it persist outside the block. To do that, pass the
parameter using the ref (or out) keyword.
This example is the same as previous, except for using the ref keyword in the method call. Any changes that
take place in the method will affect the original variables in the calling program.
using System;
class PassingRefByRef
{
static void Change(ref int[] arr)
{
// Both of the following changes will affect the original variables:
arr[0]=888;
arr = new int[5] {-3, -1, -2, -3, -4};
Console.WriteLine("Inside the method, the first element is: {0}", arr[0]);
//output : Inside the method, the first element is: -3
}
All of the changes that take place inside the method affect the original array in Main. In fact, the original array is
reallocated using the new operator. Thus, after calling the Change method, any reference to myArray points to
the five-element array, which is created in the Change method.
Inheritance
Inheritance enables you to create new classes that reuse, extend and modify the behavior that is defined in other
class. The class whose members are inherited is called base or parent or super class and the class that inherits
those members is called the derived or child or sub class.
When you define a class to derive from another class, the derived class implicitly gains all the members of the
base class, except for its constructors. The derived class can thereby reuse the code in the base class without
having to re-implementing it. You can add more members in the derived class.
Base Class
19
{
}
public class Reptile : Animal
{
}
In the example above, class Mammal is effectively both Mammal and Animal. When you access a Mammal
object, you can use the cast operation to convert it to an Animal object. The Mammal object is not changed by
the cast, but your view of the Mammal object becomes restricted to Animal's data and behaviors. After casting
a Mammal to an Animal, that Animal can be cast back to a Mammal. Not all instances of Animal can be cast
to Mammal —just those that are actually instances of Mammal. If you access class Mammal as a Mammal
type, you get both the class Animal and class Mammal data and behaviors. The ability for an object to represent
more than one type is called polymorphism.
Consider a class Student with the fields registrationNumber, name and dateOfBirth, along with the corresponding
properties. The class has a method GetAge() which returns the age of student in years.
public class Student
{
//fields
private string name;
private int registrationNumber;
private DateTime dateOfBirth;
private int age;
//methods
public int RegistrationNumber
{
get { return registrationNumber; }
set { registrationNumber = value; }
}
public string Name
{
get{return name;}
set{name=value}
}
public DateTime DOB
{
get { return dateOfBirth; }
set { dateOfBirth = value; }
}
//constructors
public Student()
{
System.Console.WriteLine("New student created without parameters");
}
public Student(int rNo, string nm, DateTime dob)
{
this.RegistrationNumber = rNo;
this.Name = name;
this.DOB = dob;
}
public int getAge()
{
int age = (DateTime.Now.Year - dateOfBirth.Year);
return age;
}
20
Now, Let us declare another class named SchoolStudent that inherits the Student class but with additional members like
marks of different subjects and methods for calculating total marks and percentage.
//Constructors
public SchoolStudent()
{
System.Console.WriteLine("New School Student create without parameters");
}
public SchoolStudent(int rNo, string name, DateTime dob, int totalMarks, int obtMarks, int CRN): base(rNo, name, dob)
{
this.totalMarks=totalMarks;
this.obtMarks=obtMarks;
this.classRollNumber=CRN;
}
public int ObtainedMarks
{
get{return obtMarks;}
set{obtMarks=value;}
}
public int TotalMarks
{
get{return totalMarks;}
set{totalMarks=value;}
}
public double GetPercentage()
{
percentage=(double)obtMarks/totalMarks*100;
return percentage;
}
}
The SchoolStudent class inherits the Student class by using the colon operator. The SchoolStudent class inherits all the
members of the Student class. In additions, it also declares its own members: two private fields with their corresponding
properties, two constructors and one instance method.
21
In code above, the parameterized constructor of the sub-class (SubClass) is explicitly calling the parameterless
constructor of the base class. We can also calls the parameterized of the base-class through the base keyboard like:
public class SubClass :BaseClass
{
SubClass(int id) :base (id) //explicit constructor call
{
//statements
}
}
Now, the constructor of SubClass(int) will explicitly call the constructor of the base-class (BaseClass) that takes an int
argument. In our SchoolStudent Class,
public SchoolStudent(int regNum, string name, DateTime dob, int totalMarks, int obtMarks): base (roll,name,dob)
{
this.totalMarks = totalMarks;
this.obtMarks = obtMarks;
}
The constructor above calls the parameterized constructor of its base-class(Student) , delegating the initialization of the
inherited fields to the base-class‘s parameterized constructor.
public Student(int registrationNumber, string name, DateTime dateOfBirth
{
this. registrationNumber = registrationNumber;
this.Name=name
this.dob = dob;
}
Sealed Class
Sealed classes are used to prevent a class from being used as a base class. It is primarily useful to
prevent unintended derivations.
Sealed Method
A class member, method, field, property, or event, on a derived class that is overriding a virtual member of the
base class can declare that member as sealed. This negates the virtual aspect of the member for any further
derived class. This is accomplished by putting the sealed keyword before the override keyword in the class
member declaration. For example:
Abstract Class
When we want to define a base class but do not want to instantiate it, then we define abstract class
using the keyword abstract. Other classes can be derived from abstract classes. An abstract class can
contain one or more method signatures that themselves are declared as abstract. These signatures
specify the parameters and return value but have no implementation (method body). An abstract
method does not have to contain abstract members, but if a class contains an abstract member, the class
itself must be declared as abstract. Derived classes of the abstract class must implement all abstract
methods. Abstract classes are useful when creating components because they allow you specify an invariant
level of functionality in some methods, but leave the implementation of other methods until a specific
implementation of that class is needed. They also version well, because if additional functionality is needed in
derived classes, it can be added to the base class without breaking code.
When an abstract class inherits a virtual method from a base class, the abstract class can override the
virtual method with an abstract method.
In the following example, the class MyDerivedC is derived from an abstract class MyBaseC. The abstract class
contains an abstract method, MyMethod(), and two abstract properties, GetX() and GetY().
// abstract_keyword.cs
// Abstract Classes
using System;
abstract class MyBaseC // Abstract class
{
protected int x = 100;
protected int y = 150;
23
Polymorphism
Polymorphism is the ability to create a variable, a function, or an object that has more than one form. The word
derives from the Greek word which has meaning "having multiple forms". It is the third pillar of object
oriented programming after encapsulation after inheritance. Polymorphism is the ability for classes to
provide different implementations of methods that are called by the same name. The primary usage of
24
polymorphism in object-oriented programming is the ability of objects belonging to different types to respond
to method, field, or property calls of the same name, each one according to an appropriate type-specific
behavior. The programmer (and the program) does not have to know the exact type of the object in advance, and
so the exact behavior is determined at run-time (this is called late binding or dynamic binding).
Through inheritance, a class can be used as more than one type; it can be used as its own type, any base types, or
any interface type if it implements interfaces. This is called polymorphism. In C#, every type is polymorphic.
Types can be used as their own type or as a Object instance, because any type automatically treats Object as a
base type.
1>At run time, objects of a derived class may be treated as objects of a base class in places such as method
parameters and collections or arrays. When this occurs, the object's declared type is no longer identical to its run-
time type.
2>Base classes may define and implement virtual methods, and derived classes can override them, which means
they provide their own definition and implementation. At run-time, when client code calls the method, the CLR
looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source
code you can call a method on a base class, and cause a derived class's version of the method to be executed.
When a derived class inherits from a base class, it gains all the methods, fields, properties and events of the base
class. To change the data and behavior of a base class, you have two choices: you can replace the base member
with a new derived member, or you can override a virtual base member.
Replacing a member of a base class with a new derived member requires the new keyword. If a base class
defines a method, field, or property, the new keyword is used to create a new definition of that method, field, or
property on a derived class. The new keyword is placed before the return type of a class member that is being
replaced. To override the virtual base member, the override keyword is used.
{
public void myMethod()
{
System.Console.WriteLine("Parent class method");
}
}
public class ClassB : ClassA
{
public void myMethod()
{
System.Console.WriteLine("Child Class Method");
}
}
public class MyClass
{
static void Main()
{
ClassB b = new ClassB();
b.myMethod(); //output: child class method
}
}
As we have overridden the method of classA in classB and since the method is marked virtual in
classA, the compiler will no longer see the apparent (or reference) type to call the static early or
compile time object binding rather it will apply dynamic, late or runtime object binding and will see the
object type at the runtime to decide which method it should call. This procedure is called
polymorphism, where we have different implementations of a method with the same name and
signature in the base-class and sub-classes.
When such a method is called using a base-type-reference, the compiler uses the actual object type
reference by the base type reference to decide which of the method to call.
By marking virtual, we allow a method to be overridden and be used polymorphically. In the same
way, we make the method in the sub-class as override when it is overriding the virtual method in the
base class.
First we declare three classes: a base class called Car, and two classes that derive from it.
ConvertibleCar and Minivan. The base class contains a single method,DescribeCar, which sends a description of
the car to the console. The derived class methods also include a method called DescribeCar, which displays their
unique properties. These methods also call the base class DescribeCar method to demonstrate how they have
inherited the properties of the Car class.
In order to highlight the difference, the ConvertibleCar class is defined with the new keyword, while
the Minivan class is defined with override.
class Car
{
public virtual void DescribeCar()
{
System.Console.WriteLine("Four wheels and an engine.");
}
}
----------
----------
28
----------
However, in this next section of code, we declare an array of objects derived from the Car base class. This array
can store Car, ConvertibleCar, and Minivanobjects. The array is declared like this:
{
Car[] cars = new Car[3];
cars[0] = new Car();
cars[1] = new ConvertibleCar();
cars[2] = new Minivan();
}
We can then use a foreach loop to visit each Car object contained in the array, and call the DescribeCar method,
like this:
foreach (Car vehicle in cars)
{
System.Console.WriteLine("Car object: " + vehicle.GetType());
vehicle.DescribeCar();
System.Console.WriteLine("----------");
}
The output from this loop is as follows:
Car object: YourApplication.Car
----------
----------
----------
Notice how the ConvertibleCar description is not what you might expect. As the new keyword was used to
define this method, the derived class method is not called—the base class method is called instead.
The Minivan object correctly calls the overridden method, producing the results we expected.
If you want to enforce a rule that all classes derived from Car must implement the DescribeCar method, you
should create a new base class that defines the method DescribeCar as abstract. An abstract method does not
contain any code, only the method signature. Any classes derived from this base class must provide an
implementation of DescribeCar.
29
override extends the base class method, whereas new keyword hides the base class method.
Interfaces
Interfaces are a special kind of type in c# used to define the specifications that should be followed by
its sub-types. An interface can be defined using the interface keyword.
An interface has the following properties:
1. An interface is like an abstract class which can not be instantiated.
2. Any class implementing the interface must implement all of its members.
3. Interface can contain signatures for methods, properties, events.
4. Interface contain no implementation of methods
5. Classes can implement more than one interface
6. An interface itself can inherit from multiple interfaces.
7. Interface can not contain constants, fields, instance constructors, destructors or types
8. All members are public and abstract by default
Interfaces provide a way to achieve runtime polymorphism.
interface ISampleInterface
{
void SampleMethod();
}
class TestClass : ISampleInterface
{
public void SampleMethod()
{
System.Console.WriteLine("Interface method implementation");
}
static void Main()
{
ISampleInterface obj = new TestClass();
obj.SampleMethod();
}
}
The following example demonstrates interface implementation. In this example, the interface IPoint contains the
property declaration, which is responsible for setting and getting the values of the fields. The class Point contains
the property implementation.
using System;
interface IPoint
{
//property signatures
int x
{ get; set; }
int y
{ get; set; }
}
class Point : IPoint
{
//fields
private int _x;
private int _y;
//constructor
public Point(int x, int y)
{
_x = x;
_y = y;
30
}
//property implementation
public int x
{
get { return _x; }
set { _x = value; }
}
public int y
{
get { return _y; }
set { _y = value; }
}
}
class MainClass
{
static void PrintPoint(IPoint P)
{
Console.WriteLine("X= {0}, y={1}", P.x, P.y);
}
static void Main()
{
Point P = new Point(2, 3);
PrintPoint(P);
}
}
Partial Class
It is possible to split the definition of a class or an interface over two or more source files. Each source
file contains a section of the class definition, and all parts are combined when the application is
compiled.
Benefits
1. More than one developer can simultaneously work on the same class
2. When working with automatically generated source code, code can be added to the class without
having to re-create the source file. Visual studio uses this approach when it creates windows forms
etc. You can create code that uses these classes without having to modify the file created by visual
studio.
To split a class definition, use the partial keyword modifier
public partial class Employee
{
public void DoWork()
{
}
}
public partial class Employee
{
public void MyWork()
{
}
}
31
The partial keyword indicates that other parts of the class; interface can be defined in the namespace.
All the parts must use the partial keyword. All the parts must be available at compile time to form the
fixed type. All the parts must have same accessibility i.e. private
if any part is declared abstract, then the whole type is considered abstract
if any part is declared sealed, then the whole type is considered sealed
if any part declares a base type, then the whole type inherits that class
any class, struct or interface member declared in a partial definition are available to all other parts.
The final type is the combination of all the parts at compile time.
Example:
public partial class Coordinates
{
private int x;
private int y;
public Coordinates(int x, int y)
{
this.x = x;
this.y = y;
}
}
public partial class Coordinates
{
public void PrintCoordinates()
{
System.Console.WriteLine("Coordinates: {0},{1}", x, y);
}
}
class TestCoordinates
{
static void Main()
{
Coordinates mycords = new Coordinates(10, 15);
mycords.PrintCoordinates();
}
}
Interface example:
partial interface ITest
{
void Interface_Test();
}
partial interface ITest
{
void Interface_Test2();
}
Partial Method
file1.cs.
partial void onNameChanged();
file2.cs
partial void onNameChanged();
32
A partial class may contain a partial method. One part of the class contains the signature of the method.
An optional implementation may be defined in the same part or another part. If the implementation is
not supplied, then the method and all calls are removed at compile time.
A partial method declaration consists of two parts: the definition, and the implementation. They may be
in separate parts of the partial class, or in the same part.
Collections
Collections are the enumerable data structures that can be accessed using indexes or keys. Closely
related data can be handled more efficiently when grouped together into a collection. Instead of writing
separate code to handle each individual object. We can use the same code to process all the elements of
a collection.
To manage a collection, the array class and the System.Collections classes are used to add, remove and
modify either individual elements of the collection or a range of elements.
The collection classes provide support for stacks, queues, lists and hash tables. Most collection classes
implement the same interfaces, and these interfaces may be inherited to create new collection classes
that fit more specialized data storage needs.
Example:
ArrayList list=new ArrayList()
list.Add(10);
list.Add("John");
list.Add('R');
Any reference or value type that is added to an ArrayList is implicitly upcast to Object. If the items are value
types, they must be boxed when added to the list, and unboxed when they are retrieved. Both the casting and the
boxing and unboxing operations degrade performance; the effect of boxing and unboxing can be quite significant
in scenarios where you must iterate over large collections.
Properties:
collections are defined as part of the System.Collections or System.Collections.Generic namespace
most collection derive from the interfaces ICollection, IComparer, IEnumerable, IList, IDictionary
and IDictionaryEnumerator and their generic equivalents.
System.Collection classes
Queue FIFO
Stack LIFO
Linked list Sequential access
33
Stack
Stack myStack = new Stack();
myStack.Push("Hello");
myStack.Push("World");
myStack.Push("!");
System.Console.WriteLine(mystack.count);
Sorted List
Maintain the elements sorted based on the key.
PrintKeysAndValues(mySL);
34
Generics
Generic classes and methods combine re-usability, type safety and efficiency to their counterpart
collections. Generics are most commonly used with collections and the method that operate on them.
.NET Framework 2.0 class library provide a new namespace System.Collections.Generic which
contains several new generic based collection classes. Generics are checked at compile time.
List is a generic form of a ArrayList.
Generics
Queue
Queue<string> numbers = new Queue<string>();
numbers.Enqueue("One");
numbers.Enqueue("two");
numbers.Enqueue("three");
foreach(String number in numbers)
{
Console.WriteLine(number);
}
numbers.Dequeue();
queueCopy.Contains("Four"); //true
queueCopy.Clear();
Console.WriteLine(queueCopy.count); //0
OpenWith.Add("rtf", "wordpad.exe");
OpenWith.Add("txt", "notepad.exe"); //error
Console.Writeline("For Key = \"rtf\",value={0}",OpenWith["rtf"];
OpenWith["rtf"] = "winword.exe";
OpenWith["doc"] = "winword.exe"; //adds new element
get{return t.element[position];}
}
static void Main()
{
Token f = new Tokens("This is a sample sentence ", new char[]{'_',',','_'});
foreach(string item in f)
{
System.Console.WriteLine(item);
}
}
Jagged Array
A jagged array is an array whose elements are arrays. The elements of a jagged array can be of
different dimensions and sizes. A jagged array is also called an array of arrays. Multidimensional array
are of fixed length whereas Jagged array are of variable length. So, performance is good.
int [][] jaggedArray = new int[3][];
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
jaggedArray4[0][1,0];
Example:
37
System.Console.WriteLine();
}
Delegates
A delegate is a type that references a method. Delegates are similar to object reference, but are used to
reference methods instead of objects. The type of a delegate is the type or signature of the method.
Points to
An Object Reference An object of particular type
Points to
A Delegate A method of particular type
Delegates are similar to the function pointers in C++ but are type safe. Delegates allow methods to pass
as parameters.
using System;
delegate void SampleDelegate(string message);
class MainClass
{
static void SampleDelegateMethod(string message)
{
Console.WriteLine(message);
}
static void Main()
{
//instantiation with named method:
SampleDelegate d1 = SampleDelegateMethod;
A delegate can be instantiated by associating it either with a named or anonymous method. For use
with named method, the delegate must be instantiated with a method that has acceptable signature. For
use with anonymous method, the delegate and the code to be associated with it are declared together.
using System;
delegate int intDelegate(int x, int y);
static void Main()
{
myDelegate delMethod = null;
Console.WriteLine("Enter Choice (+,-,/)");
char choice = (char)Console.Read();
switch(choice)
{
case '+';
38
Multicast Delegate
It is a delegate which holds the reference of more than one method. Multicast delegates must contain
only methods that return void.
39
{
static void Method1(int a, int b)
{
System.Console.WriteLine("method1");
}
static void Method2(int a, int b)
{
System.Console.WriteLine("method2");
}
public static void Main()
{
Delegate_Multicast func = new Delegate_Multicast(Method1);
func + = new Delegate_Multicast(Method2);
func(1,2); //method11 and method2 are called
func - = new Delegate_Multicast(Method1);
func(2,3); //only method2 is called
}
}
Publisher
Declare a Delegate
Notify subscribed
Subscriber events Subscriber
Event Handling
Events are implemented as multicast delegates. Events are defined using the event keyword.
Steps for event implementation and handling are:-
1. Declare an event:
To declare an event inside a class, first a delegate type of the event must be declared, if none is already
declared.
public delegate void ChangedEventHandler(object sender, Eventargs e);
The delegate type defines the set of arguments that are passed to the method that handles the event.
Next, declare the event itself.
public event ChangedEventHandler Changed;
40
An event is declared like a field of delegate type, except that the keyword precedes the event
declaration, following the modifiers. Events usually are declared public, but any accessibility modifiers
are allowed.
2. Invoking an event:
Once a class has declared an event, it can treat that event just like a field of the indicated delegate type.
The field will either be null, if no client has hooked up a delegate to the event, or else it refers to a
delegate that should be called when the event is invoked. This invoking an event is generally done by
first checking for null and then calling the event.
If(Changed != null)
Changed(this,e);
Invoking an event can only be done from within the class that declares the event.
3. Hooking up to an event:
From outside the class that declared it an event looks like a field, but access to that field is very
restricted. The only things that can be done are:
compose a new delegate onto that field
remove a delegate from a (possible composite)field
This is done with the += and - = operators. To begin receive event notifications; client code first creates
a delegate of the event type that refers to the method that should be invoked from the event. Then it
composes that onto any other delegates that the event might be connected to using +=.
List.Changed += new ChangedEventHandler(ListChanged);
When the client code is done receiving event notifications, it removes its delegate from the event by
using operator - =
Example:
using System;
namespace MyCollections
{
using System.Collections;
public delegate void ChangedEventHandler(object sender, EventArgs e);
public class ListWithChangedEvent ArrayList
{
public event ChangedEventHandler Changed;
void OnChanged(EventArgs e)
{
if(Changed != null)
Changed(this,e);
}
public override int Add(object Value)
{
int i = base.Add(Value);
OnChanged(EventArgs.Empty);
return i;
}
public override void Clear()
{
41
base.clear()
OnChanged(EventArgs.Empty);
}
}
}
namespace TestEvents
{
using MyCollections;
class EventListner
{
private ListWithChangedEvent List;
public EventListner(ListWithChangedEvent list)
List=list;
//Add "ListChanged" to the changed event on "List"
list.Changed += new ChangedEventHandler(listChanged);
private void listChanged(object sender, EventArgs e)
{
Console.WriteLine("This is called when the event fires.");
}
public void Detach()
{
List.Changed -= new ChangedEventHandler(listChanged);
list = null;
}
}
class Test
{
public static void Main()
{
ListWithChangedEvent list = new ListWithChangedEvent();
EventListner listener = new EventListner(list);
list.Add("item i");
list.Clear();
listener.Detach();
}
}
}
Indexers
Indexers are a syntactic convenience that enable you to create a class, struct, or interface that client applications
can access just as an array. Indexers are most frequently implemented in types whose primary purpose is to
encapsulate an internal collection or array. For example, suppose you have a class named TempRecord that
represents the temperature in Farenheit as recorded at 10 different times during a 24 hour period. The class
contains an array named "temps" of type float to represent the temperatures, and a DateTime that represents the
date the temperatures were recorded. By implementing an indexer in this class, clients can access the
temperatures in a TempRecord instance as float temp = tr[4] instead of as float temp = tr.temps[4]. The indexer
notation not only simplifies the syntax for client applications; it also makes the class and its purpose more
intuitive for other developers to understand.
To declare an indexer on a class or struct, use the this keyword, as in this example:
The following example shows how to declare a private array field, temps, and an indexer. The indexer enables
direct access to the instance tempRecord[i]. The alternative to using the indexer is to declare the array as
a public member and access its members, tempRecord.temps[i], directly.
Notice that when an indexer's access is evaluated, for example, in a Console.Write statement, the get accessor is
invoked. Therefore, if no get accessor exists, a compile-time error occurs.
class TempRecord
{
// Array of temperature values
private float[] temps = new float[10] { 56.2F, 56.7F, 56.5F, 56.9F, 58.8F,
61.3F, 65.9F, 62.1F, 59.2F, 57.5F };
set
{
temps[index] = value;
}
}
}
class MainClass
{
static void Main()
{
TempRecord tempRecord = new TempRecord();
// Use the indexer's set accessor
tempRecord[3] = 58.3F;
tempRecord[5] = 60.1F;
43
}
/* Output:
Element #0 = 56.2
Element #1 = 56.7
Element #2 = 56.5
Element #3 = 58.3
Element #4 = 58.8
Element #5 = 60.1
Element #6 = 65.9
Element #7 = 62.1
Element #8 = 59.2
Element #9 = 57.5
*/
44