Complete Notes
Complete Notes
Compiled by
Prof. Panchajanyeswari M Achar
SIMS, Mangalore
--------------
2015-16
CONTENTS
Chapter 1 Introduction to HTML
1.1 Concepts of Hypertext
1.2 Versions of HTML
1.3 Elements of HTML
1.4 Building HTML documents
Assignment questions
Chapter 2 Cascading Style Sheets
2.1 Introduction
2.2 Advantages of Style Sheets
2.3 Comments in CSS
2.4 Types of CSS
Assignment questions
Chapter 3 HTML 5
3.1 Introduction
3.2 Features of HTML5
3.3 Syntax of HTML 5
3.4 WAI-ARIA and HTML 5
3.5 <canvas> element
3.6 Video on the Web
3.7 Geo-location in HTML 5
3.8 Building forms in HTML 5
Assignment questions
Chapter 4 CSS3
4.1 Properties of CSS3
4.2 Enriching forms with CSS3
4.3 CSS Transforms
Assignment questions
Chapter 5 Introduction to [Link]
5.1 Introduction
5.2 Differences between ASP and [Link]
5.3 Similarities between ASP and [Link]
5.4 Characteristics of [Link]
5.5 Architecture of [Link]
5.6 [Link] Web Form Pages
5.7 Server Controls
5.8 HTML Server Controls
5.9 Web form Controls
5.10 Types of Web Form controls
Assignment questions
Chapter 6 Standard Controls
6.1 Introduction
6.2 TextBox Control
6.3 Button Control
6.4 Label Control
6.5 Image Control
6.6 Image Button Control
6.7 Drop Down List
6.8 Check Box Control
6.9 CheckBox List Control
6.10 Radio Button Control
6.11 RadioButtonList Control
6.12 Panel Control
6.13 AdRotator Control
6.14 Calendar Control
Assignment questions
Chapter 7 Validation Controls
7.1 Introduction
7.2 Base Validator Class
7.3 RequiredField Validator
7.4 Range Validator
7.5 Regular Expression Validator
7.6 Compare Validator
7.7 Custom Validator
7.8 Validation Summary
Assignment questions
Chapter 8 Database Controls
8.1 Introduction
8.2 [Link] Objects
8.3 SQLDataSource Control
8.4 ObjectDataSource Control
8.5 XMLDataSource Control
8.6 LinqDataSource Control
8.7 AccessDataSource Control
8.8 Data Bound controls
Assignment
Chapter 9 XML
9.1 Introduction
9.2 Differences between XML and HTML
9.3 Structuring Data in XML
9.4 Creating new Languages using XML
9.5 Tree Structure of XML
9.6 XML with DTD
9.7 Building blocks of XML
Assignment questions
Chapter 10 Web Services
10.1 Introduction
10.2 Managing states in [Link]
10.3 Enabling Technologies in Web Services
Assignment questions
UNIT I
CHAPTER 1
INTRODUCTION TO HTML
This is the first version of HTML that supported inline images and text controls. HTML 1.0
was very limited in terms of styling and presentation of content. In HTML 1.0, for example, you
could not:
• use tables or frames
• specify fonts
• change page background, or
• use forms
Because of these limitations, every web page created with HTML 1.0 looked the same with
similar background and the type of font used. HTML 1.0 was only supported by Lynx (a non-
graphical browser running on UNIX) and Mosaic.
This specification supported more browsers. HTML 2.0 was considerably improved to
support: It also supported:
• forms with limited set of form elements such as text boxes, and option buttons
• change of page background
• use of tables
Browser makers started to (and still do) create their own features , thus requiring additional
tags to use the features but the tags themselves were not part of the actual HTML specification.
Between HTML 1.0 and HTML 2.0 W3C was formed.
Compiled By
Panchajanyeswari M Achar Page 1
Srinivas Institute of Management Studies V Semester BCA
This version included support for creating tables and expanded options for form
elements. This version also allowed web pages to include complex mathematical equations.
W3C delayed agreeing on the next version (after HTML 2.0) of HTML, HTML 3.2 was created
instead of HTML 3.0. Although HTML 3.20 specification included support for CSS (cascaded
style sheets), browser manufactures did not support it very well in their browsers. Browser
manufactures included support for frames even though HTML 3.2 specification did not support
this feature.
This version added support for style sheets and scripting ability for multimedia elements.
HTML 4.01 focused on separating presentation styling information from the actual content by
the use of style sheets as HTML 3.20 resulted in difficult maintenance because presentation
styling information was included directly in the webpage. In HTML 4.0 with the use of style
sheets, it is now possible to change the appearance/look of the website by changing just the style
sheet (s) itself. In comparison, in the earlier versions of HTML making the same changes for the
entire website meant changing the styling information in the individual pages.
1.3 Elements of HTML
The basic structure of an HTML document includes tags, which surround content and
apply meaning to it.
<html>
<head>
<title>
TITLE OF WEB PAGE
</title>
</head>
<body>
CONTENTS OF WEB PAGE
</body>
</html>
Compiled By
Panchajanyeswari M Achar Page 2
Srinivas Institute of Management Studies V Semester BCA
• HTML document begins and ends with HTML tag i.e. <HTML> </HTML>
Here <HTML> indicates the browser that it is a HTML document and </HTML> tells the
browser that HTML document is completed.
• Header Tag i.e. <HEAD></HEAD> Header Tag does not contain any text, it only
contains the Title Tag in it.
• Title tag i.e. <TITLE></TITLE> Anything written between this tag is not displayed on
the screen but it is used to identify the Webpage.
• Body tag i.e.<BODY></BODY> This is the main part of HTML document. The content
which is to be displayed on screen as webpage should be written here. Body Tag contains
the text as well as various tags but only the text will be displayed on Webpage.
Example:
<html>
<head>
<title>
Jahnavi
</title>
</head>
<body>
Hi all!
This is my first web page
</body>
</html>
Output:
Comments in HTML:
Comments are piece of code which is ignored by any web browser. It is good practice to
comment your code, especially in complex documents, to indicate sections of a document, and
any other notes to anyone looking at the code. Comments help you and others understand your
[Link] Comment lines are indicated by the special beginning tag <!-- and ending tag -->
placed at the beginning and end of EVERY line to be treated as a comment.
Example:
<!--This is a comment line-->
1.3.3 HTML Attributes
Attributes are another important part of HTML markup. An attribute is used to define the
characteristics of an element and is placed inside the element's opening tag. All attributes are
made up of two parts: a name and a value
• The name is the property you want to set.
• The value is what you want the value of the property to be.
The value of the attribute should be put in double quotation marks, and is separated from the
name by the equals sign.
Compiled By
Panchajanyeswari M Achar Page 4
Srinivas Institute of Management Studies V Semester BCA
Inserting Texts
If you want people to read what you have written, then structuring your text well is even
more important on the Web than when writing for print. People have trouble reading wide, long,
paragraphs of text on Web sites unless they are broken up well. This section will deal with basic
text formatting elements like heading elements and paragraph elements.
Any document starts with a heading. You use different sizes for your headings. HTML
also have six levels of headings, which use the elements <h1>, <h2>, <h3>, <h4>, <h5>, and
<h6>. While displaying any heading, browser adds one line before and after that heading.
Example:
<html>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>
</body>
</html>
Output:
The <p> element offers a way to structure your text. Each paragraph of text should go in
between an opening <p> and closing </p> tag
Compiled By
Panchajanyeswari M Achar Page 5
Srinivas Institute of Management Studies V Semester BCA
Example:
<html>
<body>
<p>Hi I am Jahnavi.</p>
<p>I am working at SIMS.</p>
<p>My hobby is reading books.</p>
</body>
</html>
Output:
Compiled By
Panchajanyeswari M Achar Page 6
Srinivas Institute of Management Studies V Semester BCA
Whenever you use the <br> element, anything following it starts on the next line. This tag is an
example of an empty element, where you do not need opening and closing tags, as there is
nothing to go in between them.
Example:
<html>
<body>
Hello<br>Welcome to V Semester BCA <br>
Thanks<br>Jahnavi
</body>
</html>
Output:
Sometimes you want your text to follow the exact format of how it is written in the
HTML document. In those cases, you can use the preformatted tag (<pre>). Any text between
Compiled By
Panchajanyeswari M Achar Page 7
Srinivas Institute of Management Studies V Semester BCA
the opening <pre> tag and the closing </pre> tag will preserve the formatting of the source
document.
Example:
<html>
<body>
<pre>
void main(){
cout<<"Hello Jahnavi";
}
</pre>
</body>
</html>
Output:
Horizontal rules are used to visually break up sections of a document. The <hr> tag
creates a line from the current position in the document to the right margin and breaks the line
accordingly.
Example:
<html>
<body>
<p> We are BCA students</p>
<hr>
<p> We belong to SIMS</p>
</body>
</html>
Compiled By
Panchajanyeswari M Achar Page 8
Srinivas Institute of Management Studies V Semester BCA
Output:
Presentational Tags:
If you use a word processor, you are familiar with the ability to make text bold, italicized,
or underlined; these are just three of the ten options available to indicate how text can appear in
HTML.
The content of a <sup> element is written in superscript; the font size used is the same
size as the characters surrounding it but is displayed half a character’s height above the other
characters.
Compiled By
Panchajanyeswari M Achar Page 9
Srinivas Institute of Management Studies V Semester BCA
The content of a <sub> element is written in subscript; the font size used is the same as
the characters surrounding it, but is displayed half a character’s height beneath the other
characters.
Example:
<html>
<body>
<p> <b> I am Bold </b></p>
<p> <i> I am Italics </i></p>
<p> <u> I am Underlined </u></p>
<p> <strike> I am Strikethrough </strike></p>
<p> 2 raised to 4 is 2 <sup> 4</sup> </p>
<p> Chemical Formula of Water is H<sub> 2</sub> O</p>
</body>
</html>
Output:
Marquee Element:
Compiled By
Panchajanyeswari M Achar Page 10
Srinivas Institute of Management Studies V Semester BCA
Syntax:
Attributes:
A HTML marquee can have following attributes:
• width: how wide the marquee is. This will have a value like 10 or 20%etc.
• height: how tall the marquee is. This will have a value like 10 or 20% etc.
• direction: which direction the marquee should scroll. This will have value
either up, down, left or right.
• behavior: what type of scrolling. This will have value scroll, slid and alternate.
• scrolldelay: how long to delay between each jump. This will have a value like 10
etc.
• scrollamount: how far to jump. This will have a value like 10 etc.
• loop: how many times to loop. The default value is INFINITE, which means that
the marquee loops endlessly.
• bgcolor: background color. This will have any color name or color hex value.
• hspace: horizontal space around the marquee. This will have a value like 10 or
20%etc.
• vspace: vertical space around the marquee. This will have a value like 10 or
20%etc.
Example:
<html>
<body>
<marquee direction="right">
Hi Jahnavi!! I will scroll from left to right
</marquee>
</body>
</html>
Output:
Compiled By
Panchajanyeswari M Achar Page 11
Srinivas Institute of Management Studies V Semester BCA
1.4.2 Images
Images are very important to beautify as well as to depict many concepts on your web
page. It is true that one single image is worth than thousands of words. So as a Web Developer
you should have clear understanding on how to use images in web pages. This is done in HTML
using the <img> element
Syntax:
<img src="image URL" attr_name="attr_value"...more attributes >
Compiled By
Panchajanyeswari M Achar Page 12
Srinivas Institute of Management Studies V Semester BCA
• title: specifies a text title. The browser, perhaps flashing the title when the mouse passes
over the link.
Example:
<html>
<body>
<img src="C:\Users\Public\Pictures\Sample Pictures\[Link]"
width="100" height="100" alt="Flower" border="5" align="center" >
</body>
</html>
Output:
1.4.3 Hyperlinks
Web pages can contain links that take you directly to other pages and even specific parts
of a given page. These links are known as hyperlinks. Hyperlinks allow visitors to navigate
between Web sites by clicking on words, phrases, and images. Thus you can create hyperlinks
using text or images available on your any web page. In HTML, we can create text links between
the different pages of your site, links within pages of your sites, and link to other sites.
A link is specified using the <a> element. This element is called anchor tag as well.
Anything between the opening <a> tag and the closing </a> tag becomes part of the link and a
user can click that part to reach to the linked document. The HTML <a> tag defines a hyperlink.
A hyperlink (or link) is a word, group of words, or image that you can click on to jump to
another document.
When you move the cursor over a link in a Web page, the arrow will turn into a little
hand. The most important attribute of the <a> element is the href attribute, which indicates the
link's destination.
By default, links will appear as follows in all browsers:
Compiled By
Panchajanyeswari M Achar Page 13
Srinivas Institute of Management Studies V Semester BCA
Syntax:
<a href="Document URL" attr_name="attr_value"...more attributes />
Attributes:
The most frequently used attributes for <a> tag are
• href: specifies the URL of the target of a hyperlink. Its value is any valid document URL,
absolute or relative, including a fragment identifier or a JavaScript code fragment.
• target: specify where to display the contents of a selected hyperlink. If set to "_blank"
then a new window will be opened to display the loaded page, if set to "_top" or
"_parent" then same window will be used to display the loaded document, if set to "_self"
then loads the new page in current window. By default its "_self".
• name & id: attributes places a label within a document. When that label is used in a link
to that document, it is the equivalent of telling the browser to goto that label.
• event: attributes like onClick, onMouseOver etc. are used to trigger any Javascript or
VBscript code.
• title: attribute lets you specify a title for the document to which you are linking. The
value of the attribute is any string, enclosed in quotation marks. The browser might use it
when displaying the link, perhaps flashing the title when the mouse passes over the link.
• accesskey: attribute attribute provides a keyboard shortcut that can be used to activate a
link. For example, you could make the T key an access key so that when the user presses
either the Alt or Ctrl key on his keyboard along with the T key, the link gets activated.
Example:
<html>
<body>
This is V sem BCA class. I teach Web technology
<a href="[Link] Click Here </a>
</body>
</html>
Output:
Compiled By
Panchajanyeswari M Achar Page 14
in the color.
value with 00 as the first two digits has no red
Example:
<html>
<body link="RED" alink="yellow" vlink="green">
<a href="[Link] YAHOO</a>
<a href="[Link] GOOGLE</a>
<a href="[Link] FACEBOOK</a>
</body>
</html>
Output:
Compiled By
Panchajanyeswari M Achar Page 15
Srinivas Institute of Management Studies V Semester BCA
Example:
<html>
<body background="C:\Users\Public\Pictures\Sample Pictures\[Link]"
text="navy">
Welcome You All to Srinivas College
</body>
</html>
Output:
The font tag is having three attributes called size, color, and face to customize your fonts.
To change any of the font attributes at any time within your page, simply use the <font> tag. The
text that follows will remain changed until you close with the </font> tag. You can change any
or all of the font attributes at the one time, by including all the required changes within the one
<font> tag. You can set any font you like using face attribute but be aware that if the user
viewing the page doesn't have the font installed, they will not be able to see it. Instead they will
default to Times New Roman of your font with size attribute. You can set any font color you like
using color attribute. You can specify the color that you want by either the color name or
hexadecimal code for that color.
Example:
Compiled By
Panchajanyeswari M Achar Page 16
Srinivas Institute of Management Studies V Semester BCA
<html>
<body>
<font face="Times New Roman" size="5" color="red">Times New Roman</font>
<font face="Verdana" size="8" color="magenta">Verdana</font>
<font face="Comic sans MS" size="15" color="blue">Comic Sans MS</font>
</body>
</html>
Output:
<html>
<body>
<p> The list of hot beverages are<p>
<ul type="circle">
<li> Tea</li>
<li>Coffee</li>
<li>Badam Milk</li>
Compiled By
Panchajanyeswari M Achar Page 17
Srinivas Institute of Management Studies V Semester BCA
</ul>
</body>
</html>
Output:
<html>
<body>
<p> The list of cold beverages are<p>
<ul type="1">
<li>Sprite</li>
<li>Coca Cola</li>
<li>Fanta</li>
</ul>
</body>
</html>
Output:
<html>
<body>
<dl>
<dt> Keyboard
<dd> It is an input device
<dt> Printer
<dd> It is an output device
<dl>
</body>
</html>
Output:
Tables are very useful to arrange in HTML and they are used very frequently by almost
all web developers. Tables are just like spreadsheets and they are made up of rows and columns.
Tables are defined with the <table> tag in HTML.A table is divided into rows with the <tr> tag
where tr stands for table row. A row is divided into data cells with the <td> tag, where td stands
for table data. A row can also be divided into headings with the <th> tag where th stands for
table heading. The <td> elements are the data containers in the table. The <td> elements can
contain all sorts of HTML elements like text, images, lists, other tables, etc.
Inside <table> element the table is written out row by row. A row is contained inside a
<tr> tag which stands for table row. And each cell is then written inside the row element using a
<td> tag which stands for table data.
Syntax:
<table border="1">
<tr>
<td>Row 1, Column 1</td>
Compiled By
Panchajanyeswari M Achar Page 19
Srinivas Institute of Management Studies V Semester BCA
Table heading can be defined using <th> element. This tag will be put to replace <td> tag
which is used to represent actual data.
<HTML>
<BODY>
<table border="1">
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
<td>Janani</td>
<td>5000</td>
</tr>
<tr>
<td>Jahnavi</td>
<td>7000</td>
</tr>
</table>
</BODY>
</HTML>
Output:
Compiled By
Panchajanyeswari M Achar Page 20
Srinivas Institute of Management Studies V Semester BCA
There are two attribiutes called cellpadding and cellspacing which you will use to adjust
the white space in your table cell. Cellspacing defines the width of the border, while cellpadding
represents the distance between cell borders and the content within
Example:
<html>
<body>
<table border="1" cellpadding="5" cellspacing="5">
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
<td>Jahnavi</td>
<td>5000</td>
</tr>
<tr>
<td>Murali</td>
<td>7000</td>
</tr>
</table>
</body>
</html>
Compiled By
Panchajanyeswari M Achar Page 21
Srinivas Institute of Management Studies V Semester BCA
Output:
You will use colspan attribute if you want to merge two or more columns into a single
column. Similar way you will use rowspan if you want to merge two or more rows.
Example:
<html>
<body>
<table border="1">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr><td rowspan="2">Row 1 Cell 1</td>
<td>Row 1 Cell 2</td><td>Row 1 Cell 3</td></tr>
<tr><td>Row 2 Cell 2</td><td>Row 2 Cell 3</td></tr>
<tr><td colspan="3">Row 3 Cell 1</td></tr>
</table>
</body
</html>
Compiled By
Panchajanyeswari M Achar Page 22
Srinivas Institute of Management Studies V Semester BCA
Output:
Tables Backgrounds
You can set table background using of the following two ways:
• Using bgcolor attribute - You can set background color for whole table or just for one
cell.
• Using background attribute - You can set background image for whole table or just for
one cell.
You can set a table width and height using width and height attrubutes. You can specify
table width or height in terms of integer value or in terms of percentage of available screen area.
The caption tags will serve as a title or explanation and show up at the top of the table.
Example:
<html>
<body>
<TABLE BORDER=1 width=50%>
<CAPTION> <h3>Chocolates <h3> </Caption>
<TR><TH>Name</TH><TH>Company</TH><TH>Price</TH></TR>
<TR><TDbgcolor=cyan>Gems-Ball</TD>
<TD bgcolor=magenta>Cadbury</TD><TD>40.00</TD></TR>
<TR> <TDbgcolor=blue>KitKat</TD><TD bgcolor=orange>Nestle
</TD><TD>20.00</TD></TR>
<TR><TD bgcolor=green>Dairy Milk</TD>
Compiled By
Panchajanyeswari M Achar Page 23
Srinivas Institute of Management Studies V Semester BCA
<TD bgcolor=red>Cadbury</TD><TD>50.00</TD></TR>
</TABLE>
</body>
</html>
Output:
Frames divide a browser window into several pieces or panes, each pane containing a
separate HTML document. One of the key advantages that frames offer is that you can then load
and reload single panes without having to reload the entire contents of the browser window. A
collection of frames in the browser window is known as a frameset. The window is divided up
into frames in a similar pattern to the way tables are organized into rows and columns. The
simplest of framesets might just divide the screen into two rows, while a complex frameset
could use several rows and columns.
To create a frameset document, first you need the <frameset> element, which is used
instead of the <body> element. The frameset defines the rows and columns your page is divided
into, which in turn specify where each individual frame will go. Each frame is then represented
by a <frame> element.
Compiled By
Panchajanyeswari M Achar Page 24
Srinivas Institute of Management Studies V Semester BCA
• Each frame is indicated by <frame> tag and it defines what HTML document to put into
the frame.
Following are important attributes of <frameset> and should be known to you to use frameset.
• cols: specifies how many columns are contained in the frameset and the size of each
column. You can specify the width of each column in one of four ways:
o Absolute values in pixels. For example to create three vertical frames,
usecols="100, 500,100".
o A percentage of the browser window. For example to create three vertical frames,
use cols="10%, 80%,10%".
o Using a wildcard symbol. For example to create three vertical frames,
usecols="10%, *,10%". In this case wildcard takes remainder of the window.
o As relative widths of the browser window. For example to create three vertical
frames, use cols="3*,2*,1*". This is an alternative to percentages. You can use
relative widths of the browser window. Here the window is divided into sixths:
the first column takes up half of the window, the second takes one third, and the
third takes one sixth.
• rows: attribute works just like the cols attribute and can take the same values, but it is
used to specify the rows in the frameset. For example to create two horizontal frames,
use rows="10%, 90%". You can specify the height of each row in the same way as
explained above for columns.
• border: attribute specifies the width of the border of each frame in pixels. For example
border="5". A value of zero specifies that no border should be there.
• frameborder: specifies whether a three-dimensional border should be displayed between
frames. This attrubute takes value either 1 (yes) or 0 (no). For example frameborder="0"
specifies no border.
• framespacing: specifies the amount of space between frames in a frameset. This can take
any integer value. For example framespacing="10" means there should be 10 pixels
spacing between each frames.
The <frame> element indicates what goes in each frame of the frameset. The <frame>
element is always an empty element, and therefore should not have any content, although each
<frame> element should always carry one attribute, src, to indicate the page that should represent
that frame.
Compiled By
Panchajanyeswari M Achar Page 25
Srinivas Institute of Management Studies V Semester BCA
Following are important attributes of and should be known to you to use frames.
• src: indicates the file that should be used in the frame. Its value can be any URL. For
example, src="/html/top_frame.htm" will load an HTML file avaible in html directory.
• name: attribute allows you to give a name to a frame. It is used to indicate which frame a
document should be loaded into. This is especially important when you want to create
links in one frame that load pages into a second frame, in which case the second frame
needs a name to identify itself as the target of the link.
• frameborder: attribute specifies whether or not the borders of that frame are shown; it
overrides the value given in the frameborder attribute on the <frameset> element if one is
given, and the possible values are the same. This can take values either 1 (yes) or 0 (no).
• marginwidth: allows you to specify the width of the space between the left and right of
the frame's borders and the frame's content. The value is given in pixels. For example
marginwidth="10".
• marginheight: allows you to specify the height of the space between the top and bottom
of the frame's borders and its contents. The value is given in pixels. For example
marginheight="10".
• noresize: By default you can resize any frame by clicking and dragging on the borders of
a frame. The noresize attribute prevents a user from being able to resize the frame. For
example noresize="noresize".
• scrolling: controls the appearance of the scrollbars that appear on the frame. This takes
values either "yes", "no" or "auto". For example scrolling="no" means it should not have
scroll bars.
If a user is using any old browser or any browser which does not support frames then
<noframes> element should be displayed to the [Link] can place a <body> element inside the
<noframes> element because the <frameset> element is supposed to replace the <body> element,
but if a browser does not understand the <frameset> element it should understand what is inside
the <body> element contained in the <noframes> element. You can put some meaningful
message for your user having old browsers. For example Sorry!! your browser does not support
frames.
Compiled By
Panchajanyeswari M Achar Page 26
Srinivas Institute of Management Studies V Semester BCA
One of the most popular uses of frames is to place navigation bars in one frame and then
load the pages with the content into a separate frame. As you have already seen, each <frame>
element can carry the name attribute to give each frame a name. This name is used in the links to
indicate which frame the new page should load into.
Example:
<!--[Link]-->
<html>
<head>
<frameset cols="25%,*">
<frame src="F:\web\[Link]" name="left_pane">
<frame name="right_pane">
</frameset>
</head>
</html>
<!--[Link]-->
<html>
<body link="purple" alink="red" vlink="green">
<a href="[Link]" target="right_pane"> Link1</a> <br>
<a href="[Link]" target="right_pane"> Link2</a> <br>
<a href="[Link]" target="right_pane"> link3</a>
</body>
</html>
Output:
HTML Forms are required when you want to collect some data from the site visitor. For
example registration information: name, email address, credit card, etc. A form will take input
Compiled By
Panchajanyeswari M Achar Page 27
Srinivas Institute of Management Studies V Semester BCA
from the site visitor and then will post your back-end application such as CGI, ASP Script or
PHP script etc. Then your back-end application will do required processing on that data in
whatever way you like. Form elements are like text fields, textarea fields, drop-down menus,
radio buttons, checkboxes, etc. which are used to take information from the user.
• target: It specifies the target page where the result of the script will be displayed. It takes
values like _blank, _self, _parent etc.
There are different types of form controls that you can use to collect data from a visitor to
your site.
• Text input controls
• Buttons
• Checkboxes and radio buttons
• Select boxes
• File select boxes
• Hidden controls
• Submit and reset button
Compiled By
Panchajanyeswari M Achar Page 28
Srinivas Institute of Management Studies V Semester BCA
• Single-line text input controls: Used for items that require only one line of user input,
such as search boxes or names. They are created using the <input> element.
• Password input controls: Single-line text input that mask the characters a user enters.
• Multi-line text input controls: Used when the user is required to give details that may
be longer than a single sentence. Multi-line input controls are created with the <textarea>
element.
Single-line text input controls are created using an <input> element whose type attribute
has a value of text.
Example:
<html>
<body>
<form action="/cgi-bin/hello_get.cgi" method="get">
First name:
<input type="text" name="first_name" />
<br>
Last name:
<input type="text" name="last_name" />
<input type="submit" value="submit" />
</form>
</body>
</html>
Output:
Compiled By
Panchajanyeswari M Achar Page 29
Srinivas Institute of Management Studies V Semester BCA
• name: Used to give the name part of the name/value pair that is sent to the server,
representing each form control and the value the user entered.
• value: Provides an initial value for the text input control that the user will see when the
form loads.
• size: Allows you to specify the width of the text-input control in terms of characters.
• maxlength: Allows you to specify the maximum number of characters a user can enter
into the text box.
This is also a form of single-line text input controls are created using an <input> element
whose type attribute has a value of password. The input characters are masked here.
Example:
<html>
<head>
<title>Practice HTML Jahnavi</title>
</head>
<body>
<form action="" method="get">
Login :
<input type="text" name="login" />
<br>
Password:
<input type="password" name="password" /> <br>
<input type="reset" value="reset" />
</form>
</body>
</html>
Compiled By
Panchajanyeswari M Achar Page 30
Srinivas Institute of Management Studies V Semester BCA
Output:
If you want to allow a visitor to your site to enter more than one line of text, you should
create a multiple-line text input control using the <textarea> element. The attributes of textarea
element are
• name: The name of the control. This is used in the name/value pair that is sent to the
server.
• rows: Indicates the number of rows of text area box.
• cols: Indicates the number of columns of text area box.
Example:
<html>
<body>
<form action="/cgi-bin/hello_get.cgi" method="get">
Description : <br />
<textarea rows="5" cols="50" name="description">
Enter description here...
</textarea>
<input type="submit" value="submit" />
</form>
</body>
</html>
Output:
Compiled By
Panchajanyeswari M Achar Page 31
Srinivas Institute of Management Studies V Semester BCA
There are various ways in HTML to create clickable buttons. You can create clickable
button using <input> tag.
When you use the <input> element to create a button, the type of button you create is specified
using the type attribute. The type attribute can take the following values:
• submit: This creates a button that automatically submits a form.
• reset: This creates a button that automatically resets form controls to their initial values.
• button: This creates a button that is used to trigger a client-side script when the user
clicks that button.
Example:
<html>
<body>
<form action="[Link] method="get">
<input type="submit" name="Submit" value="Submit" />
<br /><br />
<input type="reset" value="Reset" />
<input type="button" value="Button" />
</form>
</body>
</html>
Output:
Compiled By
Panchajanyeswari M Achar Page 32
Srinivas Institute of Management Studies V Semester BCA
Checkboxes are used when more than one option is required to be selected. They are
created using <input> tag as shown below.
Following is the list of important checkbox attributes:
• type: Indicates that you want to create a checkbox.
• name: Name of the control.
• value: The value that will be used if the checkbox is selected. More than one checkbox
should share the same name only if you want to allow users to select several items from
the same list.
• checked: Indicates that when the page loads, the checkbox should be selected.
Example:
<html>
<body>
<form action="/cgi-bin/[Link]" method="get">
Select your hobbies from the list <br>
<input type="checkbox" name="Cricket" value="on"> Cricket<br>
<input type="checkbox" name="Football" value="on"> Football<br>
<input type="checkbox" name="Reading" value="on"> Reading <br>
Compiled By
Panchajanyeswari M Achar Page 33
Srinivas Institute of Management Studies V Semester BCA
Output:
Radio Buttons are used when only one option is required to be selected. They are created
using <input> tag as illustrated below.
Following is the list of important radiobox attributes:
• type: Indicates that you want to create a radiobox.
• name: Name of the control.
• value: Used to indicate the value that will be sent to the server if this option is selected.
• checked: Indicates that this option should be selected by default when the page loads.
Example:
<html>
<body>
<form action="/cgi-bin/[Link]" method="post">
<input type="radio" name="gender" value="Male" /> Male <br>
<input type="radio" name="gender" value="Female" /> Female<br>
<input type="submit" value="Select Gender" />
</form>
</body>
</html>
Compiled By
Panchajanyeswari M Achar Page 34
Srinivas Institute of Management Studies V Semester BCA
Output:
Drop Down Box is used when we have many options available to be selected but only
one or two will be selected.
Following is the list of important attributes of <select>:
• name: This is the name for the control.
• size: This can be used to present a scrolling list box.
• multiple: If set to "multiple" then allows a user to select multiple items from the menu.
Example:
<html>
<body>
<form action="/cgi-bin/[Link]" method="post">
<select name="dropdown">
<option value="Maths" selected>Maths</option>
<option value="Physics">Physics</option>
<option value="Chemistry">Chemistry</option>
</select>
<input type="submit" value="Submit" />
Compiled By
Panchajanyeswari M Achar Page 35
Srinivas Institute of Management Studies V Semester BCA
</form>
</body>
</html>
Output:
If you want to allow a user to upload a file to your web site from his computer, you will
need to use a file upload box, also known as a file select box. This is also created using the
<input> element.
Example:
<html>
<body>
<form action="/cgi-bin/hello_get.cgi" method="post"
name="fileupload" enctype="multipart/form-data">
<input type="file" name="fileupload" accept="image/*" />
</form>
</body>
</html>
Output:
Compiled By
Panchajanyeswari M Achar Page 36
Srinivas Institute of Management Studies V Semester BCA
Assignment
2 mark Questions
1. What is the purpose of <br> tag in HTML?
2. What is the purpose of <hr> tag in HTML?
3. Give the syntax of <a> tag in HTML.
4. Give the syntax of making an image as a marquee in HTML
5. What is the purpose of <head> element in HTML
Compiled By
Panchajanyeswari M Achar Page 37
Srinivas Institute of Management Studies V Semester BCA
CHAPTER 2
CASCADING STYLE SHEETS
2.1 Introduction:
CSS stands for Cascading Style Sheets. These styles define how to customize and
display HTML elements. CSS was introduced together with HTML 4, to provide a better way to
style HTML elements.
• CSS saves time - You can write CSS once and then reuse same sheet in multiple HTML
pages. You can define a style for each HTML element and apply it to as many Web pages
as you want.
• Pages load faster - If you are using CSS, you do not need to write HTML tag attributes
every time. Just write one CSS rule of a tag and apply to all the occurrences of that tag.
So less code means faster download times.
Compiled By
Panchajanyeswari M Achar Page 38
Srinivas Institute of Management Studies V Semester BCA
• Easy maintenance - To make a global change, simply change the style, and all elements
in all the web pages will be updated automatically.
• Superior styles to HTML - CSS has a much wider array of attributes than HTML so you
can give far better look to your HTML page in comparison of HTML attributes.
• Multiple Device Compatibility - Style sheets allow content to be optimized for more
than one type of device. By using the same HTML document, different versions of a
website can be presented for handheld devices such as PDAs and cell phones or for
printing.
• Global web standards - Now HTML attributes are being deprecated and it is being
recommended to use CSS. So its a good idea to start using CSS in all the HTML pages to
make them compatible to future browsers.
Comments are lines that are ignored by browsers. A CSS comment starts with /* and ends
with */. Comments can also span multiple lines
E.g. /* This is
a multi-line
comment*/
Syntax:
Selector
{
Declaration; /*property:value*/
Declaration; /*property:value*/
}
• The selector points to the HTML element you want to style.
Compiled By
Panchajanyeswari M Achar Page 39
Srinivas Institute of Management Studies V Semester BCA
• An inline style can be used if a unique style is to be applied to one single occurrence of
an element
• To use inline styles, use the style attribute in the relevant tag. The style attribute can
contain any CSS property
Example:
<html>
<body style="background-color:yellow;">
<h2 style="background-color:red;">This is a heading</h2>
<p style="background-color:green;">This is a paragraph.</p>
</body>
</html>
Output:
Syntax:
<head>
<style>
Compiled By
Panchajanyeswari M Achar Page 40
Srinivas Institute of Management Studies V Semester BCA
Selector
{
Declaration; /*property:value*/
Declaration; /*property:value*/
}
</style>
</head>
Example:
<html>
<head>
<style>
body {background-color:pink;}
p {color:blue;}
</style>
</head>
<body>
I am Jahnavi. This is Internal Style sheet
<p> Cascading Style Sheets </p>
</body>
</html>
Output:
• An external style sheet is ideal when the style is applied to many pages.
• With an external style sheet, you can change the look of an entire Web site by changing
one file.
Compiled By
Panchajanyeswari M Achar Page 41
Srinivas Institute of Management Studies V Semester BCA
• Each page must link to the style sheet using the <link> tag. The <link> tag goes inside
the <head> section
• An external style sheet can be written in any text editor. The file should not contain any
html tags. The style sheet file must be saved with a .css extension
Syntax:
<head>
<link rel="stylesheet" type="text/css" href="[Link]">
</head>
Example:
/* This is an external style sheet file. Save this file as [Link]*/
hr
{
color: yellow;
}
h2
{
color: red;
text-align: left;
font-size: 8pt;
}
Compiled By
Panchajanyeswari M Achar Page 42
Srinivas Institute of Management Studies V Semester BCA
<html>
<head>
<link rel="stylesheet" type="text/css" href="[Link]">
</head>
<body>
<hr>
Welcome to V sem BCA
<h2>I teach web technology</h2>
<hr>
<h3> Welcome to SIMS </h3>
</body>
</html>
Output [Link]
Output [Link]
Compiled By
Panchajanyeswari M Achar Page 43
Srinivas Institute of Management Studies V Semester BCA
Assignment:
1. What is CSS?
2. Give the syntax of CSS element.
3. Give the purpose of <style> tag in HTML
4. Differentiate between internal and external CSS
5. What are the advantages of CSS?
6. Explain the various ways in which style sheets can be created with examples.
CHAPTER 3
HTML 5
3.1 Introduction
HTML5 is the next major revision of the HTML standard superseding HTML 4.01,
XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content on
the World Wide Web.
Compiled By
Panchajanyeswari M Achar Page 44
Srinivas Institute of Management Studies V Semester BCA
HTML5 is cooperation between the World Wide Web Consortium (W3C) and the Web
Hypertext Application Technology Working Group (WHATWG). The new standard incorporates
features like video playback and drag-and-drop that have been previously dependent on third-
party browser plug-ins such as Adobe Flash
HTML5 introduces a number of new elements and attributes that helps in building a modern
websites. Following are great features introduced in HTML5.
• New Semantic Elements: These are like <header>, <footer>, and <section>.
• Forms 2.0: Improvements to HTML web forms where new attributes have been
introduced for <input> tag.
• Persistent Local Storage: To achieve without resorting to third-party plug-ins.
• WebSocket: A next-generation bidirectional communication technology for web
applications.
• Server-Sent Events: HTML5 introduces events which flow from web server to the web
browsers and they are called Server-Sent Events (SSE).
• Canvas: This supports a two-dimensional drawing surface that you can program with
JavaScript.
• Audio & Video: You can embed audio or video on your web pages without resorting to
third-party plug-ins.
• Geolocation: Now visitors can choose to share their physical location with your web
application.
• Microdata: This lets you create your own vocabularies beyond HTML5 and extend your
web pages with custom semantics.
• Drag and drop: Drag and drop the items from one location to another location on the
same webpage.
DocType Declaration
<!DOCTYPE html>
Compiled By
Panchajanyeswari M Achar Page 45
Srinivas Institute of Management Studies V Semester BCA
Character Encoding
The syntax followed in HTML 5 for character encoding is
<meta charset="UTF-8">
The following tags have been introduced in HTML 5 for better structure:
• section: This tag represents a generic document or application section. It can be used
together with h1-h6 to indicate the document structure.
• article: This tag represents an independent piece of content of a document, such as a blog
entry or newspaper article.
• aside: This tag represents a piece of content that is only slightly related to the rest of the
page.
• header: This tag represents the header of a web page.
• footer: This tag represents a footer of a web page and can contain information about the
author, copyright information, etc.
• nav: This tag represents a section of the document intended for navigation.
• dialog: This tag can be used to mark up a conversation.
• figure: This tag can be used to associate a caption together with some embedded content,
such as a graphic or video.
Syntax:
<!DOCTYPE html>
<html>
<head>
Compiled By
Panchajanyeswari M Achar Page 46
Srinivas Institute of Management Studies V Semester BCA
<meta charset="utf-8">
<title>...</title>
</head>
<body>
<header>...</header>
<nav>...</nav>
<article>
<section>
...
</section>
</article>
<aside>...</aside>
<footer>...</footer>
</body>
</html>
Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jahnavi's First HTML5</title>
</head>
<body>
<header role="banner">
<h1>HTML5 Document Structure Example</h1>
<p>This page should be tried in safari, chrome or Mozila.</p>
</header>
<nav>
<ul>
<li> BCA
<li> MCA
<li> SIMS
</ul>
</nav>
<article>
<section>
Compiled By
Panchajanyeswari M Achar Page 47
Srinivas Institute of Management Studies V Semester BCA
Output:
Syntactic rules describe exactly how the language elements can be put together. Semantic
rules describe how the meaning emerges from the meaning emerges from the sentences
constructed using syntactical rules.
Compiled By
Panchajanyeswari M Achar Page 48
Srinivas Institute of Management Studies V Semester BCA
HTML 5 has two outlining models – implicit model and explicit model. The explicit
model is based on the use of section and article element.
In HTML 5 codespec each section element as well as article element starts a section of
document outline. The first heading in a section or article is associated with that specific section
in the web page outline. All subsequent heading elements used within a section will start implicit
sections of the web page provided they are not contained within the nested section elements
themselves.
Sectioning in HTML 5
HTML introduces an explicit sectioning model. There are a number of new structural
elements which can be used to section the web page content.
This element contains a self contained block of web page content in a HTML 5
document. This element is intended to be independently distributable or reusable. This element
can be used to enclose
• A forum post
• A magazine or newspaper feature story
• A blog entry
• A user submitted comment
• An interactive widget
• Any other independent block of content
This element, represents a section of a page that links to other web pages or to parts of
web page within the same page. It is a section of web page content with navigation links.
Compiled By
Panchajanyeswari M Achar Page 49
Srinivas Institute of Management Studies V Semester BCA
This element is used to represent a section of a web page content which is tangentially
related to the main content of the web page. The web page content that is enclosed within the
aside element can be considered separate from the main page.
This element is used for grouping related content within the body of the web page. This
element can be nested.
Compiled By
Panchajanyeswari M Achar Page 50
Srinivas Institute of Management Studies V Semester BCA
• Search – This attribute is used to identify a text box or a form used to submit search
request to a web site or a search engine.
It is used to display graphics in web pages. It is used to define an area within a web page.
Javascript is used to draw graphics image within the area defined by the canvas element.
<canvas> element is a paired tag. Attributes of the tag are: height, width. The browsers that
support this element are – chrome, safari, opera, Firefox. A canvas is a rectangular area on an
HTML page, and it is specified with the <canvas> element.
Syntax:
<canvas id="myCanvas" width="200" height="100">
</canvas>
We have to always specify an id attribute that will be referred to in a script, and a width and
height attribute to define the size of the canvas. We can have multiple <canvas> elements on one
HTML page. We can add a border, by using the style attribute as follows:
<canvasid="myCanvas"width="200"height="100"style="border:2pxsolidblue;">
</canvas>
Example:
<!doctype html>
<html>
<head>
<script type="text/javascript">
function draw()
{
var c = [Link]("sample");
var ct = [Link](2D);
}
</script>
<style type="text/css">
canvas {border:2px solid blue;}
</style>
</head>
<body bgcolor=“pink” onLoad="draw();">
<canvas id="sample" width="150" height="150">
Compiled By
Panchajanyeswari M Achar Page 51
Srinivas Institute of Management Studies V Semester BCA
</canvas>
</body>
</html>
Output:
Explanation:
The onLoad event of the body fires when the web page is loaded into the browser. This
event invokes the JavaScript function named draw().
var ct = [Link](2D); The variable ct uses the getContext method of canvas object to
get access to the area defined by canvas object’s height and width attributes.
Once access to the canvas area is obtained, another JavaScript method can be invoked to draw
some 2D image within this canvas area.
We can draw hollow rectangles with the strokeRect function. The syntax is:
strokeRect(float x, float y, float w, float h);
We can draw filled-in rectangles with the fillRect function. The syntax is:
fillRect(float x, float y, float w, float h);
Compiled By
Panchajanyeswari M Achar Page 52
Srinivas Institute of Management Studies V Semester BCA
Here (x,y) are the upper left hand coordinates of the rectangle and w and h are the width
and height of the rectangle respectively. In a canvas element, the upper left corner of the canvas
corresponds to (0,0), positive x is to the left and positive y is downward. All measurements are
made in pixels.
The color of the rectangle can be set with fillStyle attribute. We can use the rgba function
to assign a color for the fillStyle attribute. The syntax of rgba function is as follows:
rgba(int r, int g, int b, int a).
The first three parameters correspond to the RGB values and range from 0-255. The last
parameter is the visibility factor that takes either a 0 or 1 value. The value 0 indicates that the
shape will be invisible and value 1 indicates the shape will be invisible.
Example 1:
<!DOCTYPE html>
<html>
<body bgcolor=pink>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid black;">
</canvas>
<script>
var c = [Link]("myCanvas");
var ctx = [Link]("2d");
[Link](10,10,75,50);
</script>
</body>
</html>
Output:
Compiled By
Panchajanyeswari M Achar Page 53
Srinivas Institute of Management Studies V Semester BCA
Example 2:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid black;">
</canvas>
<script>
var c = [Link]("myCanvas");
var ctx = [Link]("2d");
[Link](10,10,75,50);
[Link]=rgba(200,100,100,1)
</script>
</body>
</html>
Output:
Compiled By
Panchajanyeswari M Achar Page 54
Srinivas Institute of Management Studies V Semester BCA
We can draw lines on the canvas element. Start with beginPath() to let the canvas know
that the figure is being created. Then use the combination of moveTo() and lineTo() to position
the starting and ending points of the line. When the desired figure is drawn completely, use
closePath() to complete the path drawn. The stroke() method is used to draw the result on the
canvas area.
Example:
<!DOCTYPE html>
<html>
<body> <canvas id="myCanvas" width="200" height="100" style="border:1px solid red;">
</canvas>
<script>
var c = [Link]("myCanvas"); var ctx = [Link]("2d");
[Link](0,0);
[Link](200,50);
[Link]();
</script>
</body>
</html>
Compiled By
Panchajanyeswari M Achar Page 55
Srinivas Institute of Management Studies V Semester BCA
Output:
Example:
<!DOCTYPE html>
<html>
<body bgcolor=“pink”>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid blue;">
</canvas>
<script>
var c = [Link]("myCanvas");
var ctx = [Link]("2d");
[Link]();
[Link](95,50,40,0,2*[Link]);
[Link]();
</script>
</body>
</html>
Compiled By
Panchajanyeswari M Achar Page 56
Srinivas Institute of Management Studies V Semester BCA
Output:
Text also can be drawn on the canvas. The important properties and methods are:
• font - defines the font properties for text
• fillText(text,x,y) - Draws "filled" text on the canvas
• strokeText(text,x,y) - Draws text on the canvas with no fill
Example 1:
<!DOCTYPE html>
<html>
<body bgcolor="cyan">
<canvas id="myCanvas" width="200" height="100" style="border:1px solid orange;">
</canvas>
<script>
var c = [Link]("myCanvas");
var ctx = [Link]("2d");
[Link] = "30px Arial";
[Link]("SIMS",10,50);
</script>
</body>
</html>
Compiled By
Panchajanyeswari M Achar Page 57
Srinivas Institute of Management Studies V Semester BCA
Output:
Example 2:
<!DOCTYPE html>
<html>
<body bgcolor=pink>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid black;">
<script>
var c = [Link]("myCanvas");
var ctx = [Link]("2d");
[Link] = "30px Arial";
[Link]("Hello World",10,50);
</script>
</body>
</html>
Output:
Compiled By
Panchajanyeswari M Achar Page 58
Srinivas Institute of Management Studies V Semester BCA
Video can be embedded into a web page using the <video> element. A single HTML5
element can link multiple video files. The various attributes of <video> element are:
• Src – URL of the video to be downloaded
• Height – height of the video window
• Width – width of the video window
• Preload – informs the browser that it should start downloading the video as soon as the
page loads
• autoplay – start playing the video as soon as the page loads
Geo-location is the art of figuring out where the site visitor is located in the world. You
can optionally share that information with any trusted network. There are many methods to know
where the site visitor is located
- IP address
- Wireless network connection
- Cell tower of mobile
- Dedicated GPS hardware that receives longitude and latitude information from satellites
This API lets the site visitor to share the location information with trusted web sites. The
latitude and longitude of the site visitor are available to the Javascript embedded in the web page.
This API is supported by in several web browsers and mobile devices. To detect whether a
browser supports geo location API, modernizr can be used.
A Modernizr is a small and simple JavaScript library that helps programmers to take
advantage of emerging web technologies while still maintaining control over older browsers
Compiled By
Panchajanyeswari M Achar Page 59
Srinivas Institute of Management Studies V Semester BCA
The position object tells the current site visitors physical location on the globe. This object
has two properties
- Coords
- Timestamp
HTML5 permits the placement of placeholder text within an input field. Placeholder text
is a text displayed inside the input field as long as that field is empty and the form cursor is not in
that field. The placeholder attribute can contain only text and not HTML markup.
Example:
<form>
<input name= “sample” placeholder= “Search”>
</form>
The email type is used for input fields that should contain an e-mail address. This field
will be automatically validated when submitted
Example:
<form>
<input type= “email”>
</form>
Web addresses are also known as URLs. The structure of the web address is controlled by
internet syntax. The url type is used for input fields that should contain a URL address. The
value of the url filueld is automatically validated when the form is submitted.
Compiled By
Panchajanyeswari M Achar Page 60
Srinivas Institute of Management Studies V Semester BCA
Example:
<form>
<input type= “url”>
</form>
3.8.4 Numbers:
Numeric values can be captured in a web page in HTML 5 in two different ways – spin
boxes and sliders. These are controls that are used to input whole numbers.
Spin Boxes:
Here, the input type is number. The various other attributes are
- Min – specifies minimum acceptable value for this field
- Max – specifies maximum acceptable value for this field
- Step – specifies legal number increments
- Value – default value that is displayed when the page is loaded
Example:
<form>
<input type="number" min="0" max="10" step="2" value="6">
</form>
Sliders:
Here, the input type is range. The various other attributes are
- Min – specifies minimum acceptable value for this field
- Max – specifies maximum acceptable value for this field
- Step – specifies legal number increments
- Value – default value that is displayed when the page is loaded
Example:
<form>
<input type="range" min="0" max="10" step="2" value="6"> <br>
</form>
There are very few browsers that support this control. This is a very important tool
required to design any web page. The various forms of date and time can be given as input. The
The various values type attribute can take are
- Date : This displays only date
- Date time : This is used to display both date and time
- Week : This is used to pick a particular week of the year
- Time : This displays only time
Compiled By
Panchajanyeswari M Achar Page 61
Srinivas Institute of Management Studies V Semester BCA
Search Boxes:
A search input box can be created in HTML5 as follows:
<input type=“search”>
HTML5 has a color picker tool. It is defined by the type attribute taking “color” as a
value. This attribute will spawn a color picker which lets the user pick a color and returns the
color’s hexadecimal value
Syntax:
<input type= “color”>
Example:
<!doctype html>
<html>
<body bgcolor="pink">
<form>
PlaceHolder: <input name= “sample” placeholder=“Jahnavi”> <br>
email id: <input type= “email”><br>
Spinbox: <input type="number" min="0" max="10" step="2" value="6"> <br>
Slider :<input type="range" min="0" max="10" step="2" value="6"> <br>
Date Picker:<input type="date"> <br>
Time : <input type="time"> <br>
Week :<input type="week"> <br>
Search :<input type="search"> <br>
Color Picker: <input type="color"><br>
<br>
<input type="submit" value="go">
</form>
</body>
</html>
Output:
Compiled By
Panchajanyeswari M Achar Page 62
Srinivas Institute of Management Studies V Semester BCA
Assignment :
2 marks Questions
1. Who developed HTML5?
2. Give the DTD of HTML5
3. How is the character encoding done in HTML5?
4. List the modes of operations for web browsers.
5. What do you mean by WAI-ARIA?
6. How do you draw a 2D image in HTML5
7. List the methods used to draw rectangles in HTML5
8. List the methods used to draw text in HTML5
9. List the methods used to draw arcs in HTML5
10. List the methods used to draw lines in HTML5
11. List the attributes of <video> element in HTML
12. Define geo-location API
13. Define modernizr.
14. How can you give numeric input to a form in HTML5?
Compiled By
Panchajanyeswari M Achar Page 63
Srinivas Institute of Management Studies V Semester BCA
CHAPTER 4
CSS3
Example 1:
Compiled By
Panchajanyeswari M Achar Page 64
Srinivas Institute of Management Studies V Semester BCA
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 2px solid #a1a1a1;
padding: 10px 40px;
background: #dddddd;
width: 100px;
border-radius: 25px;
}
</style>
</head>
<body bgcolor="cyan">
</body>
</html>
Output:
Compiled By
Panchajanyeswari M Achar Page 65
Srinivas Institute of Management Studies V Semester BCA
Example 2:
<!DOCTYPE html>
<html>
<head>
<style>
div
{
width: 300px;
height: 100px;
background-color: red;
box-shadow: 10px 10px 5px #888888;
}
</style>
</head>
<body>
</body>
</html>
Output:
Example 3:
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
text-shadow: 5px 5px 5px #FF0000;
}
Compiled By
Panchajanyeswari M Achar Page 66
Srinivas Institute of Management Studies V Semester BCA
</style>
</head>
<body bgcolor="pink">
<p><b>Note:</b> Internet Explorer 9 and earlier versions, does not support the text-
shadow property.</p>
</body>
</html>
Output:
We can change the appearance of the form input elements using CSS3. We can make
them look visually appealing.
CSS3 gradients let you display smooth transitions between two or more specified colors.
Earlier, we had to use images for these effects. However, by using CSS3 gradients you can
reduce download time and bandwidth usage. In addition, elements with gradients look better
when zoomed, because the gradient is generated by the browser.
CSS3 defines two types of gradients:
• Linear Gradients (goes down/up/left/right/diagonally)
• Radial Gradients (defined by their center)
Linear Gradients
Compiled By
Panchajanyeswari M Achar Page 67
Srinivas Institute of Management Studies V Semester BCA
To create a linear gradient you must define at least two color stops. Color stops are the
colors you want to render smooth transitions among. You can also set a starting point and a
direction (or an angle) along with the gradient effect.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
#grad1
{
height: 100px;
background: -webkit-linear-gradient(red,blue); /* For Safari 5.1 to 6.0 */
}
</style>
</head>
<body>
<div id="grad1"></div>
</body>
</html>
Output:
Radial Gradients:
Compiled By
Panchajanyeswari M Achar Page 68
Srinivas Institute of Management Studies V Semester BCA
A radial gradient is defined by its center. To create a radial gradient you must also define
at least two color stops. You can also specify the gradient's center, shape (circle or ellipse) as
well as its size. By default, center is center, shape is ellipse, and size is farthest-corner.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
#grad1
{
height: 150px;
width: 200px;
background: -webkit-radial-gradient(red , yellow, green); /* Safari 5.1 to 6.0 */
}
</style>
</head>
<body>
</body>
</html>
Output:
We can apply any of the above said features to any element of a form. The example given
below illustrates the use of gradient and box-shadow feature that is applied to a button in a form.
Example:
Compiled By
Panchajanyeswari M Achar Page 69
Srinivas Institute of Management Studies V Semester BCA
<!DOCTYPE html>
<html>
<head>
<style>
#sample input[type="submit"]
{
padding: 8px 15px;
border-radius: 25px;
background: -webkit-linear-gradient(red,blue);
}
#sample input[type="button"]
{
background-color: green;
box-shadow: 10px 10px 5px #888888;
}
</style>
</head>
<body bgcolor="pink">
<form id="sample">
<input type="submit" value="Login"><br>
<input type="button" value="Clear">
</form>
</body>
</html>
Output:
Compiled By
Panchajanyeswari M Achar Page 70
Srinivas Institute of Management Studies V Semester BCA
With CSS3, we can create animations which can replace Flash animations, animated
images, and JavaScript in existing web pages. The @keyframes rule is where the animation is
created. We have to specify a CSS style inside the @keyframes rule and the animation will
gradually change from the current style to the new style. When an animation is created in the
@keyframe rule, you must bind it to a selector, otherwise the animation will have no effect. Bind
the animation to a selector (element) by specifying at least these two properties:
• the name of the animation
• the duration of the animation
An animation lets an element gradually change from one style to another. You can
change as many properties you want, as many times you want. You can specify when the change
will happen in percent, or you can use the keywords "from" and "to" (which represents 0% and
100%). 0% represents the start of the animation, 100% is when the animation is complete.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background: red;
-webkit-animation: myfirst 5s; /* Chrome, Safari, Opera */
animation: myfirst 5s;
}
/* Standard syntax */
@keyframes myfirst {
from {background: red;}
to {background: yellow;}
}
</style>
</head>
<body>
Compiled By
Panchajanyeswari M Achar Page 71
Srinivas Institute of Management Studies V Semester BCA
<div></div>
</body>
</html>
Output:
4.3.1 Scale
With the scale() method, the element increases or decreases the size, depending on the
parameters given for the width (X-axis) and the height (Y-axis). For example, The value
scale(2,4) transforms the width to be twice its original size, and the height 4 times its original
size.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 75px;
background-color: red;
border: 1px solid black;
}
div#div2 {
Compiled By
Panchajanyeswari M Achar Page 72
Srinivas Institute of Management Studies V Semester BCA
margin: 100px;
-ms-transform: scale(2,3); /* IE 9 */
-webkit-transform: scale(2,3); /* Chrome, Safari, Opera */
transform: scale(2,3); /* Standard syntax */
}
</style>
</head>
<body>
</body>
</html>
Output:
4.3.2 Rotate
With the rotate() method, the element rotates clockwise at a given degree. When negative
values are given the element is rotated counter-clockwise.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
div
{
width: 200px;
Compiled By
Panchajanyeswari M Achar Page 73
Srinivas Institute of Management Studies V Semester BCA
height: 100px;
background-color: cyan;
/* Rotate div */
}
</style>
</head>
<body>
</body>
</html>
Output:
4.3.3 Skew
With the skew() method, the element turns in a given angle, depending on the parameters
given for the horizontal (X-axis) and the vertical (Y-axis) lines
Example:
<!DOCTYPE html>
<html>
<head>
<style>
Compiled By
Panchajanyeswari M Achar Page 74
Srinivas Institute of Management Studies V Semester BCA
div {
width: 100px;
height: 75px;
background-color: red;
border: 1px solid black;
}
div#div2 {
-ms-transform: skew(30deg,20deg); /* IE 9 */
-webkit-transform: skew(30deg,20deg); /* Chrome, Safari, Opera */
transform: skew(30deg,20deg); /* Standard syntax */
}
</style>
</head>
<body>
<div>Hello!!! SIMS</div>
</body>
</html>
Output:
4.3.4 Translate
With the translate() method, the element moves from its current position, depending on
the parameters given for the left (X-axis) and the top (Y-axis) position
Example:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
Compiled By
Panchajanyeswari M Achar Page 75
Srinivas Institute of Management Studies V Semester BCA
height: 75px;
background-color: red;
border: 1px solid black;
}
div#div2 {
}
</style>
</head>
<body>
<div>Jahnavi</div>
<div id="div2">Panchajanyeswari</div>
</body>
</html>
Output:
Assignment
1. Explain the most common used properties in CSS3.
2. Write a note on CSS3 gradients
3. Write a note on CSS3 transforms
4. Write a note on CSS3 animations
Compiled By
Panchajanyeswari M Achar Page 76
Srinivas Institute of Management Studies V Semester BCA
QUESTION BANK
UNIT – I
Compiled By
Panchajanyeswari M Achar Page 77
Srinivas Institute of Management Studies V Semester BCA
UNIT II
CHAPTER 5
INTRODUCTION TO [Link]
5.1 Introduction:
[Link] is the latest version of ASP(Active Server Pages). ASP is a server side web
technology for building dynamic, interactive and database driven web sites. It is a product of
Microsoft and one of the most popular technologies for developing web applications and web
sites. [Link] is an unified web platform that provides all the services necessary for you to
build enterprise class applications. Here, the .NET framework acts as an interface between
[Link] application and the operating system.
Compiled By
Panchajanyeswari M Achar Page 79
Srinivas Institute of Management Studies V Semester BCA
ASP [Link]
ASP code is mixed with HTML code. Supports separation of code and content
Unstructured and difficult to understand
Platform dependence Platform independence
No backward compatibility Maintains backward compatibility with earlier
versions
File extension is .asp File extension is .aspx
Supports only scripting languages like [Link] applications can be developed using
javascript or vbscript any of the .NET compatible programming
languages
• The [Link] page framework is a programming framework that runs on a web server to
produce and manage [Link] web form pages dynamically
• These pages are extensions of standard HTML forms. They render dynamic, interactive
and database driven content
• The [Link] page framework creates an abstraction of the traditional client-server web
interaction so that the user can program an application using traditional methods and
tools that support rapid application development and object-oriented programming
• Web form pages can expose HTML elements as server-side objects with properties,
methods and events
• The [Link] page framework and web forms pages also support [Link] server
controls that encapsulate the common UI(User Interface) functionality, easy to use and
reusable controls
Web clients
Compiled By
Panchajanyeswari M Achar
[Link] Page 80
applications IIS
.NET
Framework
Srinivas Institute of Management Studies V Semester BCA
The [Link] web form pages are built on the .NET framework using [Link]
technology. They enable user to create programmable web pages with interactive, dynamic or
database driven content that serve as user interface for the web form application.
A web form page implements application logic using server-side code. It can render the
output in any HTTP-capable language such as HTML, XML, WML, JavaScript or VBscript. It
can run on any browser or client-device. It automatically renders correct browser-compliant
output for features such as styles and layout. We can also design a web form to target specific
browsers.
Web form pages comprise of two components: Dynamic user interface and application
logic. They are contained in two separate files. The user interface is contained in the file with the
extension .aspx. The application form is contained in a file known as code behind the file which
has extension .[Link] using [Link] or [Link] using C#.
Compiled By
Panchajanyeswari M Achar Page 81
Srinivas Institute of Management Studies V Semester BCA
• They retain page and control properties between round trips to the server. This is known
as saving the view state of the control.
• They have state management facilities to save variable and application-specific or
session-specific information
• They are compliant with any .NET compliant programming language
• They are reusable
• They are flexible because we can add user-created and third party controls in them
Server controls are tags that are understood by the server. The types of server controls are
- HTML server controls (HTML tags)
- Web server controls ([Link] tags)
- Validation server controls (input validation tags)
These are HTML tags understood by the server. By default, [Link] treats them as text
To make these tags programmable, add runat=“server” to the HTML tags. It indicates that the
element should be treated as a server control. All HTML server controls must be within the form
tag with runat=“server” attribute.
• This attribute indicates that the form should be processed at the server
• The enclosed controls can be accessed by server scripts
These are special [Link] tags that are understood by the server. These are also created
by the server and require runat=“server” attribute.
Compiled By
Panchajanyeswari M Achar Page 82
Srinivas Institute of Management Studies V Semester BCA
These controls are also created on the server and they require runat=”server” attribute to
work. The syntax for creating a web server control is
These are used for form validation. They do not correspond to any HTML tag. They
include
• RequiresFieldValidator
• CompareValidator
• RangeValidator
• RegularExpressionValidator
• CustomValidator
• ValidationSummary
These controls are used to display data from a data source such as a table. They include
• DataGrid
• DataList
• DataRepeater
Compiled By
Panchajanyeswari M Achar Page 83
Srinivas Institute of Management Studies V Semester BCA
Assignment Questions
2 marks Questions:
1. Give the syntax to create a web form control in [Link]
2. What is the purpose of runat attribute in HTML server controls.
3. List the data controls
4. List the rich form controls
5. List any four validation controls
5 marks Questions
1. Explain the architecture of [Link]
2. Differentiate between ASP and [Link]
3. Explain the characteristics of [Link]
4. Explain the characteristics of web form controls
CHAPTER 6
STANDARD CONTROLS
6.1 Introduction
The [Link] class is the base class for all web server controls. This class
is directly derived from the Object class that resides in the System namespace. The hierarchy of
the Control class is
[Link]
[Link]
All the web server controls exist within the [Link]’s namespace
and can be used on any web form. The hierarchy of WebControl class is
[Link]
[Link]
Compiled By
Panchajanyeswari M Achar Page 84
Srinivas Institute of Management Studies V Semester BCA
[Link]
The TextBox web server control is used to accept input. It allows the user to entre text in
the control. It exists within [Link] namespace. When we add a TextBox
control in a web form, the following HTML code is added to the web form
<asp:TextBox ID="TextBox1" runat="server“></asp:TextBox>
Property Descriptionption
AutoCompleteType Specifies the AutoComplete behavior of a TextBox
AutoPostBack A Boolean value that specifies whether the control is
automatically posted back to the server when the contents
change or not. Default is false
CausesValidation Specifies if a page is validated when a Postback occurs
Columns The width of the textbox
MaxLength The maximum number of characters allowed in the textbox
ReadOnly Specifies whether or not the text in the text box can be
changed
Rows The height of the textbox (only used if
TextMode="Multiline")
Runat Specifies that the control is a server control. Must be set to
"server"
Text The contents of the textbox
TextMode Specifies the behavior mode of a TextBox control
(SingleLine, MultiLine or Password)
ValidationGroup The group of controls that is validated when a Postback
occurs
Wrap A Boolean value that indicates whether the contents of the
textbox should wrap or not
OnTextChanged The name of the function to be executed when the text in the
textbox has changed
Compiled By
Panchajanyeswari M Achar Page 85
Srinivas Institute of Management Studies V Semester BCA
The Button control is used to display a push button. The push button may be a submit
button or a command button. By default, this control is a submit button.
A submit button does not have a command name and it posts the Web page back to the
server when it is clicked. It is possible to write an event handler to control the actions performed
when the submit button is clicked.
A command button has a command name and allows you to create multiple Button
controls on a page. It is possible to write an event handler to control the actions performed when
the command button is clicked.
Property Description
CausesValidation Specifies if a page is validated when a button is clicked
CommandArgument Specifies additional information about the command to
perform
CommandName Specifies the command associated with the Command
event
OnClientClick Specifies the name of the function to be executed when
a button is clicked
PostBackUrl Specifies the URL of the page to post to from the
current page when a button is clicked
Runat Specifies that the control is a server control. Must be
set to "server"
Text Specifies the text on a button
UseSubmitBehavior Specifies whether or not a button uses the browser's
submit mechanism or the [Link] postback
mechanism
ValidationGroup Specifies the group of controls a button causes
validation, when it posts back to the server
The Label control is used to display text on a page that a user cannot edit. The text is
programmable i.e. lets you apply styles to its content
Property Description
AssociatedControlID Obtains or sets the identifier for a server control with which a
Label control is associated.
Compiled By
Panchajanyeswari M Achar Page 86
Srinivas Institute of Management Studies V Semester BCA
Property Description
The ImageButton control is used to display a clickable image. This control allows the
user to display images that can handle click events.
Property Description
Compiled By
Panchajanyeswari M Achar Page 87
Srinivas Institute of Management Studies V Semester BCA
image is clicked
PostBackUrl The URL of the page to post to from the current page
when the ImageButton control is clicked
ValidationGroup The group of controls for which the ImageButton
control causes validation when it posts back to the
server
6.7 DropDownList
The DropDownList control is used to create a drop-down list. The dropdown list
displays data as a drop-down list from which you can make single selection. The user cannot
select multiple items from the list because the list closes automatically once the selection is
made. Each selectable item in a DropDownList control is defined by a ListItem element. This
control supports data binding
Property Description
SelectedIndex The index of a selected item
OnSelectedIndexChanged The name of the function to be executed when
the index of the selected item has changed
The CheckBox control is used to create a check box that the user can select by clicking.
They display a check mark that allow a user to toggle between true and false.
Property Description
AutoPostBack Specifies whether the form should be posted immediately after the
Checked property has changed or not. Default is false
CausesValidation Specifies if a page is validated when a Button control is clicked
Checked Specifies whether the check box is checked or not
InputAttributes Attribute names and values used for the Input element for the
CheckBox control
Compiled By
Panchajanyeswari M Achar Page 88
Srinivas Institute of Management Studies V Semester BCA
LabelAttributes Attribute names and values used for the Label element for the
CheckBox control
Runat Specifies that the control is a server control. Must be set to "server"
Text The text next to the check box
TextAlign On which side of the check box the text should appear (right or left)
ValidationGroup Group of controls for which the Checkbox control causes validation
when it posts back to the server
OnCheckedChanged The name of the function to be executed when the Checked property
has changed
Property Description
CellPadding The amount of pixels between the border and the contents of the
table cell
CellSpacing The amount of pixels between table cells
RepeatColumns The number of columns to use when displaying the check box
group
RepeatDirection Specifies whether the check box group should be repeated
horizontally or vertically
RepeatLayout The layout of the check box group
Runat Specifies that the control is a server control. Must be set to
"server"
TextAlign On which side of the check box the text should appear
This control is used to create a radio button. These buttons form exclusive groups where
only one button can be selected at a time.
Property Description
GroupName The name of the group to which this radio button belongs
Compiled By
Panchajanyeswari M Achar Page 89
Srinivas Institute of Management Studies V Semester BCA
The RadioButtonList control is used to create a group of radio buttons. Each selectable
item in a RadioButtonList control is defined by a ListItem element. This control supports data
binding
Property Description
CellPadding The amount of pixels between the border and the contents of the table
cell
CellSpacing The amount of pixels between table cells
RepeatColumns The number of columns to use when displaying the radio button group
RepeatDirection Specifies whether the radio button group should be repeated
horizontally or vertically
RepeatLayout The layout of the radio button group
TextAlign On which side of the radio button the text should appear
This control creates a borderless division on a web form which serves as a container for
other controls. This control is often used to generate controls by code and to display and hide
groups of controls.
Property Description
BackImageUrl Specifies a URL to an image file to display as a background for this
control
DefaultButton Specifies the ID of the default button in the Panel
Direction Specifies the content display direction of the Panel
GroupingText Specifies the caption for the group of controls in the Panel
HorizontalAlign Specifies the horizontal alignment of the content
ScrollBars Specifies the position and visibility of scroll bars in the Panel
Wrap Specifies whether the content should wrap or not
[Link] supports banner advertisements. These advertisements are image files that a
user clicks to make the browser navigate to the advertisement site. The AdRotator control is used
to display advertisement banners in a web page. This control displays a sequence of images that
can be pre-defined or random.
Property Description
AdvertisementFile Specifies the path to the XML file that contains ad information
Compiled By
Panchajanyeswari M Achar Page 90
Srinivas Institute of Management Studies V Semester BCA
AlternateTextField Specifies a data field to be used instead of the Alt text for an ad
ImageUrlField Specifies a data field to be used instead of the ImageURL attribute
for an ad
KeywordFilter Specifies a filter to limit ads after categories
NavigateUrlField Specifies a data field to be used instead of the NavigateUrl
attribute for an ad
Runat Specifies that the control is a server control. Must be set to
"server"
Target Specifies where to open the URL
The Calendar control is used to display a calendar in the browser. This control displays a
one-month calendar that allows the user to select dates and move to the next and previous
months.
Property Description
Caption The caption of the calendar
CaptionAlign The alignment of the caption text
CellPadding The space, in pixels, between the cell walls and contents
CellSpacing The space, in pixels, between cells
DayHeaderStyle The style for displaying the names of the days
DayNameFormat The format for displaying the names of the days
DayStyle The style for displaying days
FirstDayOfWeek What should be the first day of week
NextMonthText The text displayed for the next month link
NextPrevFormat The format of the next and previous month links
NextPrevStyle The style for displaying next and previous month links
OtherMonthDayStyle The style for displaying days that are not in the current
month
PrevMonthText The text displayed for the previous month link
SelectedDate The selected date
SelectedDates The selected dates
SelectedDayStyle The style for selected days
SelectionMode How a user is allowed to select dates
SelectMonthText The text displayed for the month selection link
SelectorStyle The style for the month and weeks selection links
SelectWeekText The text displayed for the week selection link
ShowDayHeader A Boolean value that specifies whether the days of the week
header should be shown
ShowGridLines A Boolean value that specifies whether the grid lines
between days should be shown
ShowNextPrevMonth A Boolean value that specifies whether the next and
previous month links should be shown
Compiled By
Panchajanyeswari M Achar Page 91
Srinivas Institute of Management Studies V Semester BCA
Assignment Questions:
1. Explain the textbox control in [Link] with all its properties
2. Explain the label control in [Link] with all its properties
3. Explain the image control in [Link] with all its properties
4. Explain the button control in [Link] with all its properties
5. Explain the imagebutton control in [Link] with all its properties
6. Explain the calendar control in [Link] with all its properties
7. Explain the adRotator control in [Link] with all its properties
8. Explain the dropdown list control in [Link] with all its properties
9. Explain the radiobutton list control in [Link] with all its properties
10. Explain the checkbox list control in [Link] with all its properties
11. Explain the hyperlink control in [Link] with all its properties
12. Explain the panel control in [Link] with all its properties
CHAPTER 7
VALIDATION CONTROLS
7.1 Introduction
Validation controls are controls used to validate the data entered in an input control such
as textbox on a web page. When the user enters invalid data into an associated control, the
validation control displays an error message on the screen. The data entered by the user is
Compiled By
Panchajanyeswari M Achar Page 92
Srinivas Institute of Management Studies V Semester BCA
validated each time it is entered, and the error message disappears only when the data is found
valid. Validation controls save time and enhance the efficiency of the applications by validating
the data before they are sent to the server for processing.
Here, we deal with the following validation controls.
• RequiredFieldValidator
• RangeValidator
• RegularExpressionValidator
• CompareValidator
• CustomValidator
• ValidationSummary
[Link]
[Link]
[Link]
[Link]
[Link]
Property Description
ControlToValidate The id of the control to validate
Display The display behavior for the validation control. Legal values are:
• None (the control is not displayed. Used to show the error
message only in the ValidationSummary control)
• Static (the control displays an error message if validation
fails. Space is reserved on the page for the message even if
the input passes validation.
• Dynamic (the control displays an error message if
validation fails. Space is not reserved on the page for the
message if the input passes validation
EnableClientScript A Boolean value that specifies whether client-side validation is
enabled or not
Enabled A Boolean value that specifies whether the validation control is
enabled or not
ErrorMessage The text to display in the ValidationSummary control when
validation fails. This text will also be displayed in the validation
control if the Text property is not set
Compiled By
Panchajanyeswari M Achar Page 93
Srinivas Institute of Management Studies V Semester BCA
The RequiredFieldValidator control ensures that the user has entered the required data in
the input control, such as text box control to which it is bound. With this control, the validation
fails if the input value does not change from its initial value. By default, the initial value is an
empty string ("").The InitialValue property does not set the default value for the input control. It
indicates the value that you do not want the user to enter in the input control.
Property Description
InitialValue Specifies the starting value of the input control. Default value is ""
Output:
The RangeValidator Control checks whether or not the value of an input control lies
within a specified range of values. This control is used to check that the user enters an input
value that falls between two values. It is possible to check ranges within numbers, dates, and
characters. The validation will not fail if the input control is empty. Use the
RequiredFieldValidator control to make the field required. The following are the properties of
RangeValidator control:
Property Description
Compiled By
Panchajanyeswari M Achar Page 94
Srinivas Institute of Management Studies V Semester BCA
Output:
Output:
Compiled By
Panchajanyeswari M Achar Page 95
Srinivas Institute of Management Studies V Semester BCA
The CompareValidator control is used to compare the value entered by a user into one
input control with the value entered into another or with an already existing value. This control
exists within the [Link] namespace
Property Description
ControlToCompare Obtains or sets the input control to compare with the input control
being validated
Operator Sets the comparison operator like equal, notequal,greaterthan,
lessthan
ValueToCompare Sets a constant value to compare with the value entered by the user
in the input control being validated
Output:
The CustomValidator control allows you to write a method to handle the validation of the
value entered. It checks the input given matches with a given condition or not. It basically
validates the input provided by the user against user-defined validations. This control exists
within the [Link] namespace
Property Description
ClientValidationFunction Specifies the name of the client-side validation script function to
be executed.
Compiled By
Panchajanyeswari M Achar Page 96
Srinivas Institute of Management Studies V Semester BCA
Output:
Property Description
DisplayMode How to display the summary. Legal values are:
• BulletList
• List
• SingleParagraph
EnableClientScript A Boolean value that specifies whether client-side validation is
enabled or not
ForeColor The fore color of the control
HeaderText A header in the ValidationSummary control
ShowMessageBox A Boolean value that specifies whether the summary should be
displayed in a message box or not
ShowSummary A Boolean value that specifies whether the ValidationSummary
control should be displayed or hidden
Output:
Compiled By
Panchajanyeswari M Achar Page 97
Srinivas Institute of Management Studies V Semester BCA
Assignment Questions
2 marks
1. What is the purpose of validation controls in [Link]?
2. List the various validation Controls available in [Link]
3. Give the inheritance hierarchy of the baseclass validator
5 marks
1. Explain RequiredFieldValidator control with its properties
2. Explain RangeValidator control with its properties
3. Explain RegularExpressionValidator control with its properties
4. Explain CompareValidator control with its properties
5. Explain CustomValidator control with its properties
6. Explain ValidationSummary control with its properties
CHAPTER 8
DATABASE CONTROLS
8.1 Introduction:
Compiled By
Panchajanyeswari M Achar Page 98
Srinivas Institute of Management Studies V Semester BCA
The [Link] technology uses the following objects to manipulate the data in the
database
• Connection objects – Connects to the database. A data adapter is needs a connection to a
data source to read and write data. For this purpose, it uses OledbConnection,
OdbeConnection, OracleConnection, or SQLConnection to communicate with the data
source.
• DataAdapter object – Enables the user to communicate with the data source and the data
set. We can configure a data adapter with SQL to execute against the data source. The
Compiled By
Panchajanyeswari M Achar Page 99
Srinivas Institute of Management Studies V Semester BCA
Compiled By
Panchajanyeswari M Achar Page 100
Srinivas Institute of Management Studies V Semester BCA
Properties Description
ConnectionString Specifies the connection string parameters in
the connection class constructor. The string
contains database name, server name, user ID
and password
SelectCommand Specifies the query string for retrieving the
records from SQL database
InsertCommand Specifies the string that contains Insert query
for inserting data into the database
Methods Description
Databind Binds the SQL data source to the datasource
control
Select Retrieves the records or data from the database
Insert Inserts the records or data from the database
This control is used to configure an Object Data provider layer to retrieve data from
business objects. Business objects are logical independent components such as classes, modules
or .NET components that process the data and return customized or encapsulated data objects.
The ObjectDataSource control resides within [Link] namespace
Compiled By
Panchajanyeswari M Achar Page 101
Srinivas Institute of Management Studies V Semester BCA
is pointing to
Insert Allows the user to insert the records into the
object to which the ObjectDataSource control
is pointing to
This control is used to configure XML files as data sources. XML files are structured
documents in which XML schemas define the data layout and structure of the document. This
control utilizes the functions contained in the classes belonging to [Link] and
[Link] namespaces
This control provides a wizard to configure XML files into the application. The wizard
provides an option to specify the XML data file as a data source for the XMLDataSource control.
This control is a data source control that allows a web server control to access data
located in the database or in the memory data collection, such as array and context objects. This
control enables developers to use Language-Integrated Query(LINQ), which simplifies the
interaction between object-oriented programming and relational data by applying principles of
object-oriented programming to relational data. It provides the capability to connect to data
either a database or an in-memory collection. It enables users to handle insert and delete
operations without using SQL commands.
Compiled By
Panchajanyeswari M Achar Page 102
Srinivas Institute of Management Studies V Semester BCA
Property Method
Select Gets or sets the properties and calculated
values that are included in the retrieved data.
SelectParameters Gets the collection of parameters that are used
during a data-retrieval operation.
StoreOriginalValuesinViewState Gets or sets a value that indicates whether the
data from the data source should be stored in
view state to make sure that the data has not
been changed by another process before it is
updated or deleted.
TableName Gets or sets the name of the property or field in
the data context class that represents a data
collection.
UpdateParameter Obtains a collection of parameters that are used
in Update operation.
Where Gets or sets a value that specifies what
conditions must be true for a record to be
included in the retrieved data.
WhereParameters Gets the collection of parameters that is used to
create the Where clause.
Method Description
Delete Deletes data from database
Insert Inserts data into database
Update Updates data into database
This control is a data source control that allows a web server control to access a
Microsoft Access database. This control does not support connection strings, but the DataFile
property of the control allows you to specify the access file(.mdb extension) that you want to
use. It does not allow you to provide user name and password to access the data.
Compiled By
Panchajanyeswari M Achar Page 103
Srinivas Institute of Management Studies V Semester BCA
Property Description
ConnectionString Specifies the connection string that is used to
connect to Microsoft Access database
DataFile Specifies the location of .mdb file
ProviderName Obtains the name of the .NET provider that the
control uses to connect to Microsoft Access
database
Data bound controls are controls that are used to bind the data source controls to display
and modify data in web applications easily. These controls enable the user to customize the
layout of the control by using various templates provided in the control.
This control displays the data from a data source in the form of a list. It supports various
templates to display grouped-up in various layouts. These templates display data with visual
clarity and ease of distinction.
The DataSource control is use to feed data to a DataList control. In order to use this
control we need to include DataSource control in the web form. This control resides in the
[Link] namespace.
This control displays only a single record in a table at a time retrieved from the data
source. Templates are used to edit and the bound values in the control. When multiple records
are retrieved from the data source, paging is used to view all the records. This control supports
basic functions like editing, inserting and deleting data records. This control resides in the
[Link] namespace.
Property Description
DataKey Retrieves a data key object on which the
control performs page-wise grouping
AllowPaging Accepts a Boolean value to enable or disable
paging
BackColor Sets the background for display
Compiled By
Panchajanyeswari M Achar Page 104
Srinivas Institute of Management Studies V Semester BCA
Method Description
RenderControl Renders output to the server control
ToString Provides a string representation od current
object into the FormView Control
This control is used to display a single record from the associated data source in a table
format, where each row of the table represents a field of the record. This control uses the
DataSourceID property to support two-way binding. This control supports basic functions like
inserting, updating and deleting data records. This control resides in the
[Link] namespace.
The ListView control is a data bound control used to display data from the associated
data source. It enables developers to display data in any format using templates and styles. It also
provides capability to control the rendered HTML output, and provides support for adding new
row and sorting.
The DataPager control is used to provide paging functionality to the data-bound controls
such as ListView control
Assignment
2 marks
1. What is the purpose of listview and datapager controls in [Link]
2. List the types of data access
CHAPTER 9
Compiled By
Panchajanyeswari M Achar Page 105
Srinivas Institute of Management Studies V Semester BCA
XML
9.1 Introduction
XML stands for eXtensible Markup Language. It is called extensible because it does not
follow a fixed format like HTML. It was developed by W3C. It is designed to improve the
functionality of the web by providing more flexible and more adaptable information
identification. It is a language for structured documentation and is easy to learn. XML is used for
describing data whereas; HTML is used for displaying data. It is actually a meta language i.e. it
is used to describe other languages
We can create our own tags in XML. This allows the programmer incredible flexibility in
describing data. Tags are used to show begin and end of elements. XML is case sensitive. XML
program begins with <? XML version = “1.0”?>. This tells the parser that a specific version of
XML is being used.
A lot of new internet languages are created with XML. Some of them are
• WAP and WML as markup for hand-held devices
• RDF and OWL for describing resources and ontology in semantic web technology
• WSDL for describing available web services
• XHTML the newer version of HTML
Compiled By
Panchajanyeswari M Achar Page 106
Srinivas Institute of Management Studies V Semester BCA
All XML documents should contain a root element. This element is the parent of other
elements. The elements in a XML document forma document tree, The tree starts at the root and
branches to the lowest level of the tree. All elements that have sub elements are called parents.
The sub elements are called children. All children at the same level are called siblings.
Syntax:
<root>
<child> <subchild>.....</subchild>
</child>
</root>
Example:
<employee>
<details>
<fname> Jahnavi </fname>
<lname> Achar </lname>
</details>
<employee>
DTD stands for Document Type Declaration. It is a set of rules that are allowed within an
XML document. They specify the allowed content and attributes of each element type. The DTD
is an XML and SGML description of the content model of a class of documents. It is a statement
in XML file that identifies the DTD that belongs to that document. A DTD defines the document
structure with a list of legal elements and attributes. A DTD can be declared inside an XML file
or as an external file. The two types of DTD are
• Internal DTD – If the DTD is declared inside an XML file then it is called an internal
DTD
• External DTD – If the DTD is declared in an external file then it is called an external
DTD
Compiled By
Panchajanyeswari M Achar Page 107
Srinivas Institute of Management Studies V Semester BCA
9.7.1 Elements
Elements are the basic building blocks of XML. Elements can contain text, other
elements or be empty
Example:
<body>some text</body>
<message>some text</message>
9.7.2 Attributes
Example:
<body bgcolor= “pink”>
9.7.3 Entities
Some characters have a special meaning in XML, like the less than sign (<) that defines
the start of an XML tag.
Most of you know the HTML entity: " ". This "no-breaking-space" entity is used in
HTML to insert an extra space in a document. Entities are expanded when a document is parsed
by an XML parser.
Compiled By
Panchajanyeswari M Achar Page 108
Srinivas Institute of Management Studies V Semester BCA
" "
' '
9.7.4 PCDATA
PCDATA means parsed character data. Think of character data as the text found between
the start tag and the end tag of an XML element. PCDATA is text that WILL be parsed by a
parser. The text will be examined by the parser for entities and markup. Tags inside the text will
be treated as markup and entities will be expanded. However, parsed character data should not
contain any &, <, or > characters; these need to be represented by the & < and >
entities, respectively.
9.7.5 CDATA
CDATA means character data. CDATA is text that will NOT be parsed by a parser. Tags
inside the text will NOT be treated as markup and entities will not be expanded.
Assignment
2 marks
1. Give the acronym of XML, SGML, HMTL, DTD
2. What is internal DTD?
3. What is external DTD?
4. What is a DTD in XML
Compiled By
Panchajanyeswari M Achar Page 109
Srinivas Institute of Management Studies V Semester BCA
Question Bank
UNIT – II
Short answer questions (2 marks)
1. What is [Link] ?
2. Write any two difference between ASP and [Link].
3. What are Server controls ? Name the different types of it.
4. Name the different types of web controls (four types).
5. Write the syntax of creating Web Server Control.
6. List any four Web Server Control ,also specify their purpose.
7. List any four HTML Server Control ,also specify their function.
8. Name any four validation web controls.
9. What are the different options are used to specify the RepeatLayout property of the
CheckBoxList.
10. What are Panel Controls? Why it is used?
11. Name the control used for banner advertisement in [Link]? Explain any one attribute of it.
12. Write the usage of CompareValidator
13. What is the purpose of the following objects used in [Link]:
a). Command Object b). DataSet Object c)DetailsViewd) ListView
14) What is XML ? Why it is called so?
15) Write any two difference between XML and HTML.
16) What is PCDATA ?
Compiled By
Panchajanyeswari M Achar Page 110
Srinivas Institute of Management Studies V Semester BCA
Compiled By
Panchajanyeswari M Achar Page 111
Srinivas Institute of Management Studies V Semester BCA
UNIT III
CHAPTER 10
WEB SERVICES
10.1 Introduction:
The evolution of the internet and its exponential growth in recent years has resulted in a
gradual shift from desktop to distributed applications. This shift has led to the development of
complex enterprise applications that are managed across different platforms and geographical
boundaries. These applications may consist of components that may have been developed using
different programming languages and hosted in application involves ensuring that such
components are interoperable.
A Web service exposes a number of methods to provide functions that can be used by one
or more applications, regardless of the programming languages, operating systems, and hardware
platforms used to develop them. The methods that provide such function are called Web
methods. The functions used by a Web service can be accessed by applications using Internet
standards, such as Simple Object Access Protocol (SOAP). SOAP is a protocol that uses
eXtensible Markup Language (XML) to describe data and HyperText Transfer Protocol (HTTP)
to transmit application data. An application that uses a Web service is called a Web service
client.
Web services provide the following benefits:
Easy accessibility: Any computer that has access to the Internet can easily access a Web
service. This enables a number of applications residing on different software and
hardware platforms to exchange data between each other. For example, a news network
such as CNN can create a Web service, which used a method that accepts the news
category as a parameter and returns the news items belonging to the specified category. If
you want to use this Web service in an application or a Web site, you can design a form
to accept the news category from a user. This form can invoke the method exposed by the
Web service and display the news items returned by the method.
Flexibility in structure: Depending on the requirements of a business, different types of
Web services can be created and used in an application. For example, you can create
simple Web services that provide a fundamental functionality that can be used in multiple
applications. You can also create Web service to integrate the existing applications that
might have been created using different software and hardware platforms. Web services
also prove useful in business-to-business transactions. Business partners may have
Compiled By
Panchajanyeswari M Achar Page 112
Srinivas Institute of Management Studies V Semester BCA
Compiled By
Panchajanyeswari M Achar Page 113
Srinivas Institute of Management Studies V Semester BCA
HiddenField control: The HiddenField control is not visible when the application is
viewed in the browser; the content of the control is sent in the HTTP Form collection
control along with the values of other controls to the server on page reload; this control
acts as a storage area for storing any page specific information.
Cookies: These are the text files that store data, such as user ID and preferences at the
client end; when a browser again requests the same web page, the cookie is sent along
with the request; the Web server then retrieves the information from the cookie.
Query Strings: These are the information strings added at the end of a URL to mention
the state of a Web application; however, the use of query string is not secure because the
query string values are exposed to the internet through the URL.
In all the above methods, the states information is stored at the client end. However, we can also
save the states of an [Link] Web application on the Web server. Saving the state of an
application on the Web server is secure in comparison to a client machine for obvious reasons.
Now let us highlight a few of the methods used to save state information on the Web server.
Application State Object: It stores the application data that is not frequently modified
by users; the object of HttpApplicationState class is used to store the state of an
[Link] Web application.
Session State Object: It store information specific to a user session; user session refers to
the duration for which a user uses a website; the object of HttpSessionState class is used
to store the session-state for each [Link] Web application that is being executed.
Database: It stores the application-state when the information to be stored is too large;
the database can be used along with cookies to store the application-state.
Compiled By
Panchajanyeswari M Achar Page 114
Srinivas Institute of Management Studies V Semester BCA
The application-state is used to store the data corresponding to the global variables of an
[Link] Web application. The data in the application-state is stored once and read many times.
The application-state uses the HttpApplicationstate class to store and share the data throughout
the application. You can access the information stored in the application-state by using the
HttpApplication class property. The data stored in the application-state is accessible to all the
pages of an [Link] Web application and the data is same for all the user accessing the Web
application. The HttpApplicastionstate class provides a lock method that you can use to ensure
that the only a single user access and modify data of an [Link] Web application at any instant
of time.
Each client accessing a Web application maintains distinct session with a Web server and
there is also specific information associated with each of these sessions. Session-state is used to
store this information. The session-state is defined in the <sessionState> section of the
[Link] file and stores the data specific to a user session in session variables. Different
session variables are created for each user session. Also, the session variables can be accessed
from any page of a Web application. When a user accesses a web page a session ID for the user
is created. The session ID is transferred between the server and the client over the HTTP
protocol using cookies.
The view-state stores the page-specific information when a page is posted back to the
server. When a page is processed, the current state of the web page and control is hashed into a
string and saved as a hidden field. Such a state of web page is called view-state and is defined as
a hidden field on a web page.
The ViewState property is used to save the view-state for each control, such as HTML
controls and Web controls used in a web page. If the ViewState property is not used, then the
values written in various controls, such as Textbox and Checkbox on the web page are not
retained when the page is reloaded.
The hidden field of a view-state is placed at the top of each page. The source code to
maintain a view-state contains an input tag with three attribute, type, name and value. The type
attribute is said to hidden. The name attribute contains the name of the controls, such as Web and
HTML, for which the ViewState property is being used. The value attributes specifies a string
value, which is not in human readable format. The string value is a combination of control values
that are used in a web page. Therefore when the web page is reloaded, the server reads the values
in the value attribute and restores the values of the controls when the page is sent back to the
client.
Compiled By
Panchajanyeswari M Achar Page 115
Srinivas Institute of Management Studies V Semester BCA
A Web service can be created using any programming language in the .NET suite, such
as Visual Basic .NET, Visual C#.NET and C++.NET. However, requirements need to be fulfilled
to enable applications to access the functionality provided by Web services. These requirements
are listed below:
• A common data representation format in order to ensure the interoperability of the data
exchanged by the client application and the Web service.
• A standard method for sending messages from the client application to the Web service
and vice versa.
• A standard format for describing the Web service.
• A mechanism to allow client applications to discover the Web services and their location
10.3.1 XML
10.3.2 SOAP
To be able to communicate with each other, a Web service and a client application must
agree upon a common protocol. SOAP is a standard communication protocol for interchanging
information in a structured format in a distributed environment. The information exchanged
between the client application and the Web service is called a message. Messages include the
calls made by a client application to a Web method and the data returned by the Web method to
the client. When a client application makes a request for a Web method, a SOAP packet is
created. This packet contains the name of the Web method to be invoked and the parameters to
be passed to the Web method in an XML format. This information is used to invoke the Web
Compiled By
Panchajanyeswari M Achar Page 116
Srinivas Institute of Management Studies V Semester BCA
method with the appropriate parameters. When the SOAP packet arrives at the Web server on
which the Web service resides, the Web method name and its parameters are extracted from the
SOAP packet and the appropriate Web method is invoked.
10.3.3 WSDL
To be able to use a Web service, the developers of a client application need to know the
methods exposed by the Web service and the parameters to be passed to these methods.
Therefore, you need a standard method to describe the methods that are exposed by a Web
service. This information should be readily accessible to the Web service clients during the
design phase. This is achieved by using an XML vocabulary called Web Services Description
Language(WSDL). WSDL is a markup language that describes a Web service.
A WSDL document contains the following information about a Web service:
o The Web service available for a given Web site
o The purpose for which these service can be used
o The types of parameters that need to be passed to a Web service
o The types of value that is returned by a Web service
o The format used to access these Web services
o The URL at which a We service can be accessed
10.3.4 UDDI
UDDI provides a standard mechanism to register and discover a Web service. When a
Web service provider wants to make a Web service available to client applications, the provider
describes the Web service by using a WSDL document. Then, the provider registers the Web
service in the UDDI Directory. The UDDI Directory contains pointers to the web service and the
WSDL document for the Web service. Client application can then discover the Web service by
using the UDDI Directory.
The following diagram depicts the relation between the various enabling Web service
technologies:
Compiled By
Panchajanyeswari M Achar Page 117
Srinivas Institute of Management Studies V Semester BCA
WSDL
UDDI Document
Registry
Direction
Client Web
Application Services
11.1 Introduction:
After the designing, implementing and testing phases are over; the application is ready
for production. Deployment can be viewed as the process of installing the application from the
development computer to the production computer. In case of [Link] ,the production
computer refers to the server on which the [Link] application will be hosted.
Technically, deployment of an application consists of two important processes:
Assembling Components: Involves the identification of all the components of an
application. Then, each component is analyzed to identify its dependencies on further
components. Finally, all the components and their dependencies are assembled into one
package.
Creating an Application Structure: Involves the identification of the structure in which the
application components must be arranged on the client computer for the application to run
successfully. This process also involves the identification of any special settings, such as the
Internet Information Server (IIS) settings and the security policy settings required for the
application to run.
The following four different deployment techniques are available for deploying an
application from a development server to the production server:
XCopy Deployment: In this technique, different application components are copied from the
development computer to the production computer. You can use either the XCopy command in
DOS or use Windows Explorer to copy application components.
No-Touch: Used to deploy an application from the Internet. In this method, the application
components are from a web page to a special folder called the Internet download cache on the
Compiled By
Panchajanyeswari M Achar Page 119
Srinivas Institute of Management Studies V Semester BCA
computer where the application is to be deployed. This technique is commonly used to deploy
windows application.
Microsoft Windows Installer (.MSI): In this technique, the application components are
packed into a windows Installer or an .MSI file. Next, the MSI file is run on the production
computer and the deployment happens automatically.
Cabinet-file (.CAB): In this technique, the application components are packed into a cabinet
file. This technique is commonly used to deploy Activex components.
The different types of deployment projects available in visual [Link] are as follows:
Setup project: Help to create a MSI file that can be used for deploying an application. The
MSI file created contains the application, installation instructions, information about the registry
entries to be made, and dependencies. When this MSI file gets executed, all the components are
copied to the Program Files directory on the destination computer. Setup projects are used to
deploy the windows from application.
Web Setup project: Help to create a MSI file. It is very similar to the Setup project, except
that when the MSI file gets executed, all the components are copied to the virtual root directory
in IIS and the web application is registered on the Web server.
Merge module project: Helps to unite all files, registry entries, resources, and the setup
logic required to deploy the package as one unit. Merge module allows multiple applications to
share the setup code. It identifies all the dependencies for a component and makes sure that the
correct versions of te components are installed. A merge module project enables you to solve the
problem related to versioning. When a new version of any component needs to be deployed, a
new merge module project can be created. A new merge module project contains the
dependencies for the new version of the component.
CAB project: Helps to generate CAB files to bundle the ActiveX controls. These CAB
files can then be used to download components form the Web server to a Web browser. If it is
required that the components should run on the client side, a CAB project should be created. A
CAB project does not have any editors. The Solution Explorer can be used to add application
components to a CAB file. After an application component is added, you can set properties, such
as the level of compression and the location of dependent file on the Web, for each component
by using the Properties window. This type of deployment project creates a file with the
Compiled By
Panchajanyeswari M Achar Page 120
Srinivas Institute of Management Studies V Semester BCA
extension, .msm. the .msm file cannot be used independently. For this reason, it must be merged
with the project that creates the MSI file.
The type of Deployment Project you should choose depends upon the components to be
deployed and the mode of deployment. For example, you may deploy an application in the form
of a collection of CAB files for downloading the application.
A Setup project and a web Setup project can be used in situation when standard Windows-based
or Web-based applications need to be deployed. A merge module project can be used to deploy a
component used by multiple applications. A CAB project can be used to deploy components like
ActiveX controls.
11.3 Caching:
Caching is a technique to store frequently accessed Web pages (or data), temporarily in
memory that are faster to access than accessing it from the original source. For example, when
you access a Web page for the first time, it takes a while to load. Subsequent visits to that Web
page will be a lot faster because the Web page has been cached on your computer. You may
cache a whole Web page, parts of a Web page, or application data according to your
requirements. However, you may not want certain items to be cached independently. For
example, you are running a news website and you want the content on your website to be
refreshed at regular intervals. You may want the content on your website to refresh every half an
hour, ten minutes, or even every minute.
[Link] class is used to implement cache for a Web application in
[Link]. This class can not be inherited. Some important public properties and public methods
of the [Link] class and given in the following table
Compiled By
Panchajanyeswari M Achar Page 121
Srinivas Institute of Management Studies V Semester BCA
You can easily implement Output caching by just adding the @ OutputCache directive
in the Web page as follows:
<%@ OutputCache Duration =“10” VaryByParam=”none” %>
You can also define as to where you want to cache the data either on the client-side, or
the server-side, or the proxy server by including a location attribute:
Compiled By
Panchajanyeswari M Achar Page 122
Srinivas Institute of Management Studies V Semester BCA
The @ OutputCache directive has few more attributes. All the attributes supported by
@ OutputCache directive are given in Table As-10.3.
Identify the contents of the Web page, which are more resource hungry and
require more processing than other parts of the page, while rendering.
Create a single or more User controls for those parts of the page and decide the
caching policies of those User controls.
To cache the contents of User control, either use @ OutputCache directive or make it possible
programmatically by using the PartialCachingAttribute class. The following code will direct
the caching engine to caching the control in the Output cache for 500 seconds:
If you prefer to use code-behind technique, you can use the following lines of code in the
metadata of your class declaration:
<PartialCaching(500)>
Compiled By
Panchajanyeswari M Achar Page 124
Srinivas Institute of Management Studies V Semester BCA
Now, when someone requests for the Web page where this User control is used, the
caching engine will store the User control for 500 seconds in its Output cache and will serve it
from the cache for the subsequent requests. The rest of the contents of the page will be retrieved
from the server on every request.
Now comes the tricky part; suppose our User control is cached for 200 seconds and we
nested it in a Web page which also has Output cache enabled for only 100 seconds. What will
happen then? In such a situation, our User control will be cached for 200 seconds as used, even
through the cache for the page will be regenerated after 100 seconds. The control will be
retrieved from the same cache only after a complete 200 seconds.
Let us reverse this case. Let us assume that our page will expire in 200 seconds and our
control will expire in 100 seconds. In such a situation, the complete page will be present in cache
for 200 seconds including the User control.
The Data Caching is one of the most powerful features in the whole caching scenario in
.NET. So far, we have seen declarative ways of enabling caching in our [Link] application,
where Data caching is all about doing it programmatically. Data caching is very useful when you
need to cache your own custom data into cache. For example, we need to cache a dataset which
can be used later somewhere in your application. For this, we need Data caching.
In [Link], caching is implemented using two mechanisms-application caching and
page out caching. Application caching allows you to cache data that you generate, such as a
DataSet or a custom report. This page out caching saves the output of page processing and reuses
the output. It supports the following basic types of dependency models:
File Based Dependency
Key Based Dependency
SQL Based Dependency
Aggregate based Dependency
Custom Dependency
11.4 Threads
A thread is defined as the execution path of a program. Each thread defines a unique flow
of control. If your application involves complicated and time consuming operations like
database access or some intense I/O operations, then it is often helpful to set different execution
paths or threads, with each thread performing a particular job. Threads are lightweight processes.
One common example of use of thread is implementation of concurrent programming by modern
Compiled By
Panchajanyeswari M Achar Page 125
Srinivas Institute of Management Studies V Semester BCA
operating systems. Use of threads saves wastage of CPU cycle and increase efficiency of an
application. So far we have written programs where a single thread runs as a single process
which is the running instance of the application. However, this way the application can perform
one job at a time. To make it execute more than one task at a time, it could be divided into
smaller threads. In .NET, the threading is handled through the [Link]
namespace. Creating a variable of [Link] type allows you to create a
new thread to start working with. It allows you to create and access individual threads in a
program.
• Unstarted
• Running
• Background
• StopRequested
• Suspended
• SuspendRequested
• WaitSleepJoin
• Aborted
• AbortRequested
Compiled By
Panchajanyeswari M Achar Page 126
Srinivas Institute of Management Studies V Semester BCA
• Stopped
You can use the Thread class belonging to the [Link] namespace to create,
use, and manage threads in [Link] applications. To create and start a new thread, you need to
create an instance of the Thread class and then call its start method. Here’s an example:
Notice the parameter DoWork in the call to the ThreadStart constructor in the code above. The
method DoWork is a thread method. A thread method is one that contains the actual code that
the thread should execute. It should have no parameters and should have a return type of void.
When you start a thread using the Start() method on the thread object, the thread is
scheduled to the ready state (i.e., it’s placed in the ready queue). Here it awaits its turn to be
allocated the processor. The thread would be allocated the processor as and when its turn comes.
The OS takes care of scheduling threads from the ready state to the running state; you have no
control over this.
You can suspend a thread that is already running by making a call to the Suspend()
method on the thread object. Note that the runtime doesn’t suspend a thread immediately after
you make a call to the Suspend() method. The thread is placed in the suspended state only after a
safe point is achieved. A safe point is a point at which suspension is possible and this point is
decided by the runtime only. Here’s how you can use the Suspend() method to request a thread
to be suspended:
if ([Link] <h1><a
name="ThreadState_Running_br_br_thread_Suspend_br_br_pre_p_You_can_rev
oke_the_suspension_of_the_thread_later_by_making_a_call_to_the_Resume_
method_on_the_thread_object_Here_rsquo_s_an_example_p_p_nbsp_p_pre_if_
thread_ThreadState_">[Link] ) <br>\\{ <br>
Compiled By
Panchajanyeswari M Achar Page 127
Srinivas Institute of Management Studies V Semester BCA
[Link](); <br>\\}<br></a></h1>
You can revoke the suspension of the thread later by making a call to the Resume()
method on the thread object. Here’s an example:
You can also put a thread in the sleep state by making a call to the Sleep() method on the
thread object. The following code makes the thread sleep for 10 seconds:
[Link](10000);
You can also put a thread to sleep infinitely using the following code:
[Link]([Link]);
You can use the Join() method on a thread to allow it to wait until another thread has
completed its activity. Here’s an example that illustrates how you can make a worker thread wait
until the other thread has completed its work:
if([Link]()!= [Link]())<br>
\\{<br> [Link](); <br> \\}<br>
To terminate a thread you can use the Abort() method, which stops a running thread
prematurely. This method raises a ThreadAbortException. Here’s an example:
The Priority property of the Thread class specifies the priority of one thread with
respect to other. The .Net runtime selects the ready thread with the highest priority. The
priorities could be categorised as:
• Above normal
• Below normal
• Highest
Compiled By
Panchajanyeswari M Achar Page 128
Srinivas Institute of Management Studies V Semester BCA
• Lowest
• Normal
Once a thread is created its priority is set using the Priority property of the thread class.
[Link] = [Link];
Property Description
CurrentUICulture Gets or sets the current culture used by the Resource Manager to look up
culture-specific resources on time.
ExecutionContext Gets an ExecutionContext object that contains information about the
various contexts of the current thread.
IsAlive Gets a value indicating the execution status of the current thread
Compiled By
Panchajanyeswari M Achar Page 129
Srinivas Institute of Management Studies V Semester BCA
Methods Description
Compiled By
Panchajanyeswari M Achar Page 130
Srinivas Institute of Management Studies V Semester BCA
EndThreadAffinity Notifies a host that managed code has finished executing instructions
that depend on the identity of the current physical operating system
thread.
FreeNamedDataSlot Eliminates the association between a name and a slot, for all threads in
the process. For better performance, use fields that are marked with
the ThreadStaticAttribute instead.
GetData Retrieves the value from the specified slot on the current thread,
within the current thread’s current domain. For better performance,
use fields that are marked with the ThreadStaticAttribute instead.
GetDomain Returns the current domain in which the current thread is running.
GetNamedDataSlot Looks up a named data slot. For better performance, use fields that are
marked with the ThreadStaticAttribute attribute instead.
Interrupt Interrupts a thread that is in the WaitSleepJoin thread.
Join Blocks the calling thread until a thread terminates, while continuing to
perform standard COM and SendMessage pumping. This method has
different overload forms.
MemoryBarrier Synchronizes memory access as follows: The processor executing the
current thread cannot reorder instructions in such a way that memory
accesses that follow the call to MemoryBarrier
ResetAbort Cancels an Abort requested for the current thread
SetData Sets the data in the specified slot on the currently running thread, for
that thread’s current domain. For better performance, use fields
marked with ThreadStaticAttribute attribute instead.
Start Starts a thread
SpinWait Causes a thread to wait the number of times defined by the iterations
parameter.
VolatileRead() Reads the value of a field. The value is the latest written by any
processor in a computer, regardless regardless of the number of
Compiled By
Panchajanyeswari M Achar Page 131
Srinivas Institute of Management Studies V Semester BCA
The following summarise the .NET tools available for coordinating or synchronizing the
action of threads:
• Lock – Ensures just one thread can access a resource, or section of code.
• Mutex – Ensures just one thread can access a resource, or section of code. It can be used
to prevent multiple instances of an application from starting.
• Semaphore – Ensures not more than a specified number of thread can access a resource,
or section of code.
• Events wait Handle-Allows a thread to wait until it receives a signal from another thread.
• Wait and pulse-Allows a thread to wait until a custom blocking condition is met.
Compiled By
Panchajanyeswari M Achar Page 132
Srinivas Institute of Management Studies V Semester BCA
Web applications are prone to security breaches because multiple users access them from
remote locations. Therefore, you need to secure these applications using different security
mechanisms. The security mechanisms in [Link] are:
• Authentication: Authentication is the process of validating the identity of the user before
granting access to a restricted resource. User credentials like username/password pair is
used to verify the identity of a user. Several authentication methods are provided by
[Link] in conjunction with IIS.
• Authorization: Authorization is the process of verifying if the authenticated user has
permission for accessing the requested resource. For example, consider a user requesting
a file on the server. First, the user is authenticated to determine if the user has access to
the server. Once user identity is verified, the authorization process determines the
permission of the user for the requested file. In this example, permission can be read,
write or full access.
• Impersonation: Impersonation is the process of assuming the identity of the user while
requesting for a resource. For example, consider the user requesting an access to a file on
the file server. The user is authenticated on the web server and checked if the user is
authorized for accessing the file server. Now, is the user is again authenticated on the file
server before granting access to the file. If impersonation is enabled, the web server
accesses the file server using the credentials passed on by the user during the
authentication process. Therefore, impersonation is the process by which the server
performs an action
on behalf of the user.
In addition to various security mechanisms defined in the preceding section, you need
to implement different reliable verification mechanism to ensure the integrity of data. Consider
the example of an online shopping site. Shopping cart facility is only available to users who have
logged in. You need to implement a flawless mechanism to verify if the status of the user before
catering this facility.
Microsoft .NET Framework has a built-in security system called Code Access Security
(CAS) that enables administrators to control, actions performed by a code. For example,
administrator can restrict codes exchanging directly from the Integer zone to access system files
Compiled By
Panchajanyeswari M Achar Page 133
Srinivas Institute of Management Studies V Semester BCA
on the local machine. Zone refers to the location from where the code is executing, such as My
Computer zone, Intranet zone, Internet zone and so on. Administrators can define a set of
permission for each zone. The set of permissions is called security policy.
In .NET Framework, you can define different policies for different security levels. The
four different security levels are as follow:
• Enterprise-level
• Machine -level
• User-level
• Application -level
Security policy is a set of rules that map a security requirement to a set of permissions.
Some actions defined by the security policy are as follows:
• Identifying the code that is granted or denied the permission to run.
• Identifying the tasks that a code is allowed to perform.
• Identifying the tasks that the users are permitted to perform.
• Identifying the resources that the code can access.
In the .NET Framework, security is achieved through the Code Access Security (CAS)
model. In this model, CLR checks permissions on a code to access a restricted resource, before
granting access.
The permission classes controls the rights of an application to requested or accept data.
For example, you may use a permission class to grant an application the right to answer an
incoming connection from another party or the right to initiate a connection to another party.
When applications try to access protected resources, the .NET Framework uses its
security policy to grant or deny permission through code access .Any application that is executed
is automatically evaluated and given a set of permissions by the run time security system. The
application runs property if all the required permissions are granted. On the other hand, it
generates a security exception if the requested permissions are not granted.
The [Link] file provides various sections for implementing security. Some of the
Compiled By
Panchajanyeswari M Achar Page 134
Srinivas Institute of Management Studies V Semester BCA
Compiled By
Panchajanyeswari M Achar Page 135
Srinivas Institute of Management Studies V Semester BCA
In forms authentication, users are validated against their credentials in a data source. Form
authentication provides a very flexible mechanism of defining different types of users and
permission sets. The main disadvantage of form authentication is that the security of the form
authentication heavily depends on how it is implemented. If an unauthenticated user tries to
access a restricted resource, the user is redirected to logon form that is specified in the
[Link] file. After the logon form successfully authenticates a user, the user is redirected to
the original resource that was requested by the user. To implement forms authentication, you
need to perform the following steps:
Set the authentication mode in the [Link] form authentication. The following code
snippet illustrates how to set the authentication mode to form authentication:
<authentication mode=”Forms”>
Create a login form which would authenticate the user against a data source, such as a
database.
Disable anonymous access. The following code snippet illustrates how to deny anonymous
access:
<deny users=”+” />
The <authentication> tag provides the <forms> sub tag to configure a Web application for
form authentication. The loginURL attribute of the <forms> tag specifies the name of the
logon form. In addition, it specifies the default extension of the cookie that is issued to an
authenticated user by using the name attribute of the <forms> element. The definition of the
<forms> element for implementing forms authentication is:
<authentication>
<forms loginURL=”[Link]” name=”.ASPXFORMSAUTH” />
</authentication>
The following example illustrates the [Link] file entries for configuring a web application
for form authentication:
Compiled By
Panchajanyeswari M Achar Page 136
Srinivas Institute of Management Studies V Semester BCA
<configuration>
<[Link]>
<authentication mode=”Forms”>
<forms
name=”.AuthenticationCookie”
loginUrl=”/login/[Link]”
protection=”All”
timeout=”60”
path=”/”/>
</authentication>
<deny users=”*” />
</[Link]>
</configuration>
In the preceding example, name of HTTP cookie is AuthenticationCookie and URL to which the
user will be directed for login is “/login/[Link]”.
The user credential can be stored in either [Link], database or even in an array
within the application. The user credentials can be stored in the [Link] file using the
<credentials> and <user> tags. The<credentials>are defined within the <forms> tag and the
<user> tag is nested within the<credentials>tag.
The following code snippet illustrates how user credentials are stored in a [Link]
file:
<configuration>
<[Link]>
<authentication mode=”Forms”>
<forms
name=”.AuthenticationCookie”
loginUrl=”/login/[Link]”
protection=”All”
timeout=”60”
path=”/”>
<credentials passwordFormat=”Clear”>
<user name=”John” password=”p@ssword”/>
<user name=”Tom” password=”123_p@ss”/>
</credentials>
</forms>
</authentication>
</[Link]>
Compiled By
Panchajanyeswari M Achar Page 137
Srinivas Institute of Management Studies V Semester BCA
</configuration>
In the preceding example,two set of username/password pair John/p@ssword and
Tom/123_p@ss are stored in the [Link] file. The passwordFormat attribute of the
<credentials> tag is used to specify the format in which the password is stored in the [Link]
[Link] is set to Clear which means the password is stored as plain text. Other
options available with passwordFormat attribute are MD5 and SHA both of which are encryption
algorithms.
Authorization is the process of verifying whether the authenticated user has privilege to
access the requested resource. [Link] provides the following two mechanisms to authorize a
user:
• File Authorization: when a user sends a request to access a file,the Access control List
(ACL) associated with the requested file checks for the user credentials given by the
user. ACL is a data structure that is associated with a resource. It contains information
about the various users allowed to access it and the level of access for each user. For
example,if John has a read-only permission for a file XYZ,the ACL of XYZ file have this
information. Authorization can be used only when an application is using windows
authentication.
• URL Authorization: when user requests access to a resource, the user is authorized
Compiled By
Panchajanyeswari M Achar Page 138
Srinivas Institute of Management Studies V Semester BCA
using the configuration data. URL authorization can be used with form authentication.
You can specify the list of users who are allowed to access a Web site in the
<authorization> element. The <authorization> element is specified in the [Link] file. The
<authorization> element includes two child elements,<allow> and <deny>. You can specify the
list of users who are allowed to access the Web site in the <allow> element and the list of users
who should not access the Web site in the <deny> element.
When a user tries to access a web application, the first step is to check whether
impersonation is enabled for the application. Impersonation is used to decide whether the user
requests should be executed under a user account or a local system process account used by
[Link] for anonymous requests. When impersonation is enabled, IIS uses the client token to
impersonate the client to access resources.
Impersonation involves the following steps:
1. When a request from a remote client is received, IIS carries out authentication. If the
client is authenticated, it passes the request to the [Link] application.
2. The application impersonates the client and uses the authentication given by IIS to access
the restricted resources.
Compiled By
Panchajanyeswari M Achar Page 139
Srinivas Institute of Management Studies V Semester BCA
Assignment
2 marks Questions
7. List the processes in deployment
8. List the deployment techniques
9. Define caching
10. List the caching techniques
11. Define a thread.
12. List the various states of a thread
13. What is thread synchronization?
14. List the tags to configure security in [Link]
5 marks Questions
1. Explain the various deployment techniques
2. Explain the various caching techniques
3. Explain the concept of working with threads
4. Explain the security mechanism in [Link]
Compiled By
Panchajanyeswari M Achar Page 140
Srinivas Institute of Management Studies V Semester BCA
CHAPTER 12
OVERVIEW OF C#
12.1 Introduction
class SampleOne
{
public static void Main()
Compiled By
Panchajanyeswari M Achar Page 141
Srinivas Institute of Management Studies V Semester BCA
{
[Link](“Hello from Jahnavi”);
}
}
The first line class SampleOne declares a class, which is an object oriented construct.
Here, class is a keyword and declares a new class definition. SampleOne is a C# identifier that
specifies the name of the class to be defined. A class is a template for what an object looks like
and how it behaves.
C# is a block structured language i.e. code blocks are always enclosed within { and }.
Every class definition is enclosed in braces.
12.3 Namespaces:
A class in a namespace can be accessed using the dot operator. Namespaces are the way
C# segregates the .NET library classes into reasonable groups. Using directive is sued to import
the namespace into the program. Once the namespace is imported, we can use elements of that
namespace without using namespace as prefix.
Example:
using System;
class SampleOne
{
public static void Main()
{
[Link](“Hello from Jahnavi”);
}
}
12.4 Comments in C#
Comments are used to enhance the readability and understanding of code. C# supports
two types of comments
• Single line comments – single line comments begin with //
• Multi-line comments – multi-line comments are enclosed within /* and */
The using keyword can only be applied to namespaces and cannot be applied to classes.
Hence, the statement
using [Link] ;
is illegal. We can overcome this by using aliases for namespace class. This takes the following
syntax
using alias-name = class-name;
Example:
Using A = [Link];
Compiled By
Panchajanyeswari M Achar Page 143
Srinivas Institute of Management Studies V Semester BCA
Class Sample1
{
public static void Main()
{
[Link](“Hi I am Jahnavi”);
}
}
We can store string values in string objects and use these objects to the WriteLine
method. We can create a string data type to create a string variable and assign a string constant to
it as below:
string s = “abc”;
[Link](s);
Example:
using System;
Class Sample2
{
public static void Main()
{
string name = “Hello Jahnavi”;
[Link](name);
}
}
Documentation Section
Using Directive Section
Interfaces Section
Classes Section
Main Method (compulsory)
Example:
Compiled By
Panchajanyeswari M Achar Page 144
Srinivas Institute of Management Studies V Semester BCA
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
/* my first program in C# */
[Link]("Hello Jahnavi");
}
}
}
Output:
Hello Jahnavi
Explanation:
• The first line of the program using System; - the using keyword is used to include
the System namespace in the program. A program generally has
multiple using statements.
• The next line has the namespace declaration. A namespace is a collection of classes. The
HelloWorldApplication namespace contains the class HelloWorld.
• The next line has a class declaration, the class HelloWorld contains the data and method
definitions that your program uses. Classes generally would contain more than one
method. Methods define the behavior of the class. However, the HelloWorld class has
only one method Main.
• The next line defines the Main method, which is the entry point for all C# programs.
The Main method states what the class will do when executed
• The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in the program.
• The Main method specifies its behavior with the statement [Link]("Hello
Jahnavi"); WriteLine is a method of the Console class defined in the System namespace.
This statement causes the message "Hello, World!" to be displayed on the screen.
Assignment
2 marks
1. Define namespaces
2. How do you write comments in C#?
Compiled By
Panchajanyeswari M Achar Page 145
Srinivas Institute of Management Studies V Semester BCA
CHAPTER 13
LITERALS, VARIABLES, DATA TYPES
13.1 Introduction:
13.1.1 Keywords:
Compiled By
Panchajanyeswari M Achar Page 146
Srinivas Institute of Management Studies V Semester BCA
Keywords are reserved words predefined to the C# compiler. These keywords cannot be
used as identifiers; however, if you want to use these keywords as identifiers, you may prefix the
keyword with the @ character. In C#, some identifiers have special meaning in context of code,
such as get and set, these are called contextual keywords.
The following table lists the reserved keywords and contextual keywords in C#:
Reserved Keywords
Abstract as Base Bool Break byte case
Catch char Checked Class Const continue decimal
Default delegate Do Double Else enum event
Explicit extern False Finally Fixed float for
Foreach goto If Implicit In in (generic int
modifier)
Interface internal Is Lock Long namespace new
Null object Operator Out out override params
(generic
modifier)
Private protected Public Readonly Ref return sbyte
Sealed short Sizeof Stackalloc Static string struct
Switch this Throw True Try typeof uint
Ulong unchecked Unsafe Ushort Using virtual void
Volatile while
Contextual Keywords
Add alias ascending Descending Dynamic from get
Global group Into Join Let orderby partial
(type)
partial remove Select Set
(method)
13.1.2 Identifiers:
An identifier is a name used to identify a class, variable, function, or any other user-
defined item. The basic rules for naming classes in C# are as follows:
• A name must begin with a letter that could be followed by a sequence of letters, digits (0
- 9) or underscore. The first character in an identifier cannot be a digit.
• It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ; :
" ' / and \. However, an underscore ( _ ) can be used.
• It should not be a C# keyword.
13.1.3 Operators
Compiled By
Panchajanyeswari M Achar Page 147
Srinivas Institute of Management Studies V Semester BCA
Operators are symbols used in expressions to describe operations involving one or more
operands.
13.1.4 Punctuators:
Punctuators are symbols used to group and separate codes in C#. Punctuators are also
known as separators. The punctuators in C# include
• Parentheses()
• Braces { }
• Brackets []
• Semi-colon ;
• Colon :
• Comma ,
• Period .
13.2 Literals:
C# Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the
base or radix: 0x or 0X for hexadecimal, 0 for octal, and no prefix is required for decimal.
Examples:
212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
Compiled By
Panchajanyeswari M Achar Page 148
Srinivas Institute of Management Studies V Semester BCA
3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
While representing using decimal form, you must include the decimal point, the
exponent, or both and while representing using exponential form you must include the integer
part, the fractional part, or both. The signed exponent is introduced by e or E.
There are two Boolean literals in C#. They are true and false. They are used as values for
relational expressions.
A single character constant contains a single character enclosed within single quotes.
Examples are ‘x’, ‘5’, ‘ ’
String literals or constants are enclosed in double quotes "". A string contains characters
that are similar to character literals: plain characters, escape sequences, and universal characters.
Examples : “hello”, “hi”, “Jahnavi”, “5+4”
There are certain characters in C# when they are preceded by a backslash they will have
special meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a list
of some of such escape sequence codes:
Compiled By
Panchajanyeswari M Achar Page 149
Srinivas Institute of Management Studies V Semester BCA
Escape Meaning
sequence
\\ \ character
\' ' character
\" " character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\ooo Octal number of one to three
digits
\xhh . . . Hexadecimal number of one or
more digits
13.3 Variables:
A variable is an identifier that denotes a storage location used to store a data value. A
variable may take different values at different times during the execution of a program. Every
variable has a type that determines what values can be stored in a variable.
The rules to name a variable are
• They must nit begin with a digit
• Uppercase and lower case letters are distinct
• It should not be a keyword
• Whitespaces are not allowed
• Variable names can be of any length
Data types specify the size and type of value to that can be stored. C# is a language rich
in data types. The variety allows the programmer to select the type appropriate to the need of the
application. The types in C# are
Value types
Compiled By
Panchajanyeswari M Achar Page 150
Srinivas Institute of Management Studies V Semester BCA
Reference types
Value types and reference types differ in
4. Where they are stored
5. How they behave in the context of assignment statements
Value types are of fixed length and they are stored on a stack, and when the value of the
variable is assigned to another variable, the value is actually copied. This means that two
identical copies of the values are available in the memory. Reference types are of variable length
and are stored in a heap. When an assignment between two reference variables occurs, only the
reference is copied and the actual value remains in the same memory location. This means that
there are two references to a single variable. A third category called pointers is available for use
only in unsafe codes
User-defined reference types refer to those types which we define using predefined value
types. They include
• Classes
• Interfaces
• Delegates
• Arrays
A variable must be declared before it is used in the program. Declaration does three
things.
1. It tells the compiler what the variable name is
2. It specifies what type of data the variable will hold
3. The place of declaration decides the scope of the variable
The syntax for variable declaration is
<data type> <variable list>;
Here, the data type must be a valid C# data type including char, int, float, double, or any
user-defined data type, etc., and variable list may consist of one or more identifier names
separated by commas.
Example:
Compiled By
Panchajanyeswari M Achar Page 152
Srinivas Institute of Management Studies V Semester BCA
int i, j, k;
char c, ch;
float f, salary;
double d;
Constants are defined using the const keyword. Syntax for defining a constant is:
The following program demonstrates defining and using a constant in your program:
using System;
namespace DeclaringConstants
{
class Program
{
static void Main(string[] args)
{
const double pi = 3.14159; // constant declaration
double r;
[Link]("Enter Radius: ");
r = [Link]([Link]());
double areaCircle = pi * r * r;
Compiled By
Panchajanyeswari M Achar Page 153
Srinivas Institute of Management Studies V Semester BCA
When the above code is compiled and executed, it produces the following result:
Enter Radius:
3
Radius: 3, Area: 28.27431
The scope of a variable is the region of code within which the variable can be accessed.
This depends on the type of the variable and place of its declaration. C# defines a several
categories of variables. They are
• Static variables
• Instance variables
• Array elements
• Value parameters
• Reference parameters’
• Output parameters
• Local variables
In object-oriented programming, methods are invoked using objects. Since value types
such as int and long are not objects, we cannot use them to call methods. C# enables us to
achieve this through boxing. Boxing means the conversion of a value type on the stack to a
object type on the heap. Conversely, the conversion from an object type back to a value type is
known as unboxing.
13.9.3 Boxing :
Any type, value or reference can be assigned to an object without an explicit conversion.
When the compiler finds a value type where it needs a reference type, it creates an object ‘box’
into which it places the value of the value type.
Example:
int i = 12;
Compiled By
Panchajanyeswari M Achar Page 154
Srinivas Institute of Management Studies V Semester BCA
object box = i;
if (box is int) {
[Link]("Box contains an int");
}
13.9.4 Unboxing
Unboxing is the process of converting the object type back to value type. Unboxing is an
explicit operation using C-style casting.
Example:
object box = 12; //boxing
int i = (int)box; // unboxing
Assignment
2 mark Questions:
1. Define variable.
2. Define constant
3. What are trigraph characters? Give example.
4. What is a backslash constant? Give example.
5. Define keyword. Give example.
6. What is a token in C#? Give example
7. List the character set in C#.
8. How do you declare a variable in C#? Give example
9. How do you assign a value to a variable? Give example.
10. How do you declare a variable as a constant? Give example
11. How do you define a symbolic constant in C#? Give example
12. Differentiate between keyword and identifier
13. Define boxing and unboxing in C#
5 mark Questions:
1. Explain the primary data types in C#.
2. Explain the various types of constants in C#.
3. Explain about tokens available in C#.
4. How do you declare a variable in C#? What are the rules to form a variable?
5. Write a note on user defined data types in C#.
Compiled By
Panchajanyeswari M Achar Page 155
Srinivas Institute of Management Studies V Semester BCA
CHAPTER 14
OPERATORS AND EXPRESSIONS
14.1 Introduction:
Compiled By
Panchajanyeswari M Achar Page 156
Srinivas Institute of Management Studies V Semester BCA
• Special Operators
All the basic arithmetic operators are supported by C#. These operators can manipulate
with any built in data types supported by C#. The various operators are tabulated as follows:
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Division
Compiled By
Panchajanyeswari M Achar Page 157
Srinivas Institute of Management Studies V Semester BCA
evaluated as true then the compiler assigns a non zero value and 0 otherwise. These expressions
are used in decision statements to decide the course of action of a running program.
Syntax: ae1 relational operator ae2
where ae1 and ae2 are arithmetic expressions
Operators Meaning
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
!= Not equal to
Operator Meaning
&& Logical And
|| Logical Or
! Logical Not
Assignment operators are used to assign the result of an expression to variable. The
operator used for assignment in C# is ‘=’. C# also supports short hand assignment operators like
Compiled By
Panchajanyeswari M Achar Page 158
Srinivas Institute of Management Studies V Semester BCA
v op = expression where v- variable and op- operator. Here op= is known as a short had
assignment operator.
v op=expression is equivalent to v=v op expression
E.g. The statement x+=y+1; is equivalent to x=x+y+1;
The advantage of short hand assignment operator is
Easy to read and write
Statements are more concise and efficient
C# has 2 very powerful operators that are not found in any other language. They are
increment/decrement operators i.e. ++ and --. The ++ operator is used to increment value of a
variable by 1. The -- operator is used to decrement value of a variable by 1. Both are unary
operators and can be written as follows: ++m, m++ , m—and –m. Both m++ and ++m mean the
same thing when they form statements independently. But, they behave differently when used in
expression on the right hand side of assignment operator.
E.g. Let a=5; x=a++; Here, this statement can be broken into 3 statements as follows
a=5; x=a; a=a+1;
In the above example, the value of a is assigned to x and then its value is incremented by 1. A
prefix operator first adds 1 to the operand and then the result is assigned to the variable on the
left. A postfix operator first assigns its value to the variable and then increments its value by 1.
E.g. m=10;
y=--m
Here the value of m is decremented by 1 and then assigned to y. Hence the value of y is 9.
Conditional operators are also called ternary operators. Conditional expressions can be
constructed in C# using the operator pair ‘?:’.
Syntax: expr?expr1:expr2;
Here expr is evaluated first. If the value is true, then expr1 is evaluated and becomes the value of
the expression. If the expression is false then, expr2 is evaluated and becomes the value of the
expression.
E.g. a=5;
b=10;
x=(a>b)?a:b;
The output of the above example is as follows- The value of b i.e. 10 is assigned to x.
Compiled By
Panchajanyeswari M Achar Page 159
Srinivas Institute of Management Studies V Semester BCA
These operators are used to manipulate data at bit level. These operators are used for
testing the bits or shifting the bits either to the left or right.
Operator Meaning
& Bitwise And
| Bitwise Or
^ Bitwise exclusive Or
<< Shift left
>> Shift Right
~ One’s complement
The Bitwise operators supported by C# are listed in the following table. Assume variable
A holds 60 and variable B holds 13 then:
Compiled By
Panchajanyeswari M Achar Page 160
Srinivas Institute of Management Studies V Semester BCA
moved right by the number of bits specified by the right give 15,
operand. which is
0000 1111
Compiled By
Panchajanyeswari M Achar Page 161
Srinivas Institute of Management Studies V Semester BCA
Basically the evaluation procedure involves 2 left to right passes. During the first pass the high
priority operators are applied as they are encountered and during the second pass, lower priority
operators are applied as they are encountered.
Example: Consider the following expression x= a-b/3+c*2-1
If the values of a=9, b=12,c=3
Now x= 9-12/3+3*2-1
Pass 1: x=9-4+6-1
Pass 2: x=5+6-1=10
Operator precedence determines the grouping of terms in an expression. This affects how
an expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Type conversion is basically type casting or converting one type of data to another type.
In C#, type casting has two forms:
Compiled By
Panchajanyeswari M Achar Page 162
Srinivas Institute of Management Studies V Semester BCA
Type Conversion
}
}
}
Compiled By
Panchajanyeswari M Achar Page 163
Srinivas Institute of Management Studies V Semester BCA
The System namespace defines a class called Math class with a rich set of static methods
that makes math-oriented programming easy and efficient. The following table lists some of the
mathematical methods defined in Math class.
Method Meaning
Ceil() x rounded up to the nearest integer
Sin() sine of the angle in radians
Log10() Base 10 logarithm
Floor() x rounded down to the nearest integer
Log() Natural log of x, x>0
Pow(X,Y) x raised to y (xy)
Sqrt(X) Square root of x ; x>=0
Example:
using System;
class Program
{
static int Main()
{
int number = -6844;
2 mark questions
1. What is the difference between pre-increment and post-increment operators
2. If the value of a=5 then, explain a—and –a.
3. What is short hand assignment in C#? Give example
4. What is the purpose of ternary operator? Give example
5. What do you mean by typecasting? Give example
6. List any four mathematical functions in C#.
7. What is the purpose of size of operator?
8. Why are bitwise operators used in C#?
9. If a=10, b=20 evaluate the following statements in C#
Compiled By
Panchajanyeswari M Achar Page 164
Srinivas Institute of Management Studies V Semester BCA
a. a+=10;
b. a+4/6*6/2;
c. b+3/2 *2/3;
d. a+=b;
e. c=a++;
f. d=--b;
5 mark Questions
1. Explain about arithmetic operators.
2. Write a note on bit-wise operators.
3. Explain about logical operators
4. Write a note on relational operators.
5. Explain about increment operators in C#.
6. Explain about decrement operators in C#.
Question Bank
UNIT – III
Short answer questions (2 marks)
1. Differentiate between value type and reference types.
2. How do you define constants variables in C#?
3. What does public static void means in the declaration of main method ?
public static void main()
{…….}
4. What are Command line arguments? Give example.
5. What is an alias? Where and how it is used?
Compiled By
Panchajanyeswari M Achar Page 165
Srinivas Institute of Management Studies V Semester BCA
6. How do we implement a program having more than on class with the Main method?
(multiple main methods)
7. List the special operators used in C# ,specify their purpose.
8. What is Mixed-mode arithmetic?
9. What is SOAP ?
10. What is Thread ? Write the different Thread states.
11. Write any two properties of a Thread.
UNIT IV
CHAPTER 15
DECISION MAKING AND BRANCHING
15.1 Introduction:
The program statements are executed sequentially. But, sometimes we need to change the
order of execution of statements depending on certain conditions. C# language possesses
Compiled By
Panchajanyeswari M Achar Page 166
Srinivas Institute of Management Studies V Semester BCA
decision making capabilities and supports statements called decision making statements. The
decision making statements supported by C# are as follows:
1. if statement
2. switch statement
3. Conditional operator statement
The if statement is a powerful decision making statement and is used to control the flow
of execution of statements. It is basically a two-way decision statement used in conjunction with
an expression. The computer evaluates the value of the expression first and depending on the
value of the expression it transfers control to a particular statement. The if statement can be
implemented in different forms depending on the complexity of the conditions to be tested. The
different forms of if statements are:
• Simple if
• If…else statement
• Nested if…else statement
• Elseif ladder
The if else statement is an extension of the simple if statement. The general format of it is
as follows:
if(test-expression)
{
True-block statements;
Compiled By
Panchajanyeswari M Achar Page 167
Srinivas Institute of Management Studies V Semester BCA
}
Else
{
False-block statements;
}
Statement x;
If the test expression is true, then the true block statements are executed otherwise the
false block statements are executed. Either of the two statements, i.e. true block or false block
statements only are executed, but not both. In both the cases, the control transfers to statement x
after executing the block.
Example
using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
Compiled By
Panchajanyeswari M Achar Page 168
Srinivas Institute of Management Studies V Semester BCA
When the above code is compiled and executed, it produces the following result:
Test
expression
?
Statement – x
if(test condition1)
{
if (test condition2)
statement 1;
else
statement 2;
}
else
statement 3;
statement x;
Compiled By
Panchajanyeswari M Achar Page 169
Srinivas Institute of Management Studies V Semester BCA
Example
using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
When the above code is compiled and executed, it produces the following result:
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
Compiled By
Panchajanyeswari M Achar Page 170
Srinivas Institute of Management Studies V Semester BCA
if(condition 1)
statement 1;
elseif(condition 2)
statement 2;
elseif(condition 3)
statement 3;
:
:
elseif(condition n)
statement n;
else
default statement;
statement x;
Here the conditions are evaluated from top. As soon as a true condition is encountered,
the statements associated with it are executed and the control is transferred to statement x. If all
the conditions are false, then the final else containing the default statement will be executed.
Example:
using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
Compiled By
Panchajanyeswari M Achar Page 171
Srinivas Institute of Management Studies V Semester BCA
{
/* if condition is true then print the following */
[Link]("Value of a is 10");
}
else if (a == 20)
{
/* if else if condition is true */
[Link]("Value of a is 20");
}
else if (a == 30)
{
/* if else if condition is true */
[Link]("Value of a is 30");
}
else
{
/* if none of the conditions is true */
[Link]("None of the values is matching");
}
[Link]("Exact value of a is: {0}", a);
[Link]();
}
}
}
When the above code is compiled and executed, it produces the following result:
C# language supports a built-in multi way decision statement known as switch statement.
The switch statement tests the value of a given variable against a list of case values and when a
match is found, the block of statements associated with that case are executed. The general form
of switch statement is as follows:
switch(expression){
case constant-expression :
statement(s);
Compiled By
Panchajanyeswari M Achar Page 172
Srinivas Institute of Management Studies V Semester BCA
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
Example:
Compiled By
Panchajanyeswari M Achar Page 173
Srinivas Institute of Management Studies V Semester BCA
using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
/* local variable definition */
char grade = 'B';
switch (grade)
{
case 'A':
[Link]("Excellent!");
break;
case 'B':
case 'C':
[Link]("Well done");
break;
case 'D':
[Link]("You passed");
break;
case 'F':
[Link]("Better try again");
break;
default:
[Link]("Invalid grade");
break;
}
[Link]("Your grade is {0}", grade);
[Link]();
}
}
}
When the above code is compiled and executed, it produces the following result:
Well done
Your grade is B
Compiled By
Panchajanyeswari M Achar Page 174
Srinivas Institute of Management Studies V Semester BCA
Statement Description
2 mark Questions:
1. Give the syntax of simple if with example.
2. What is the purpose of goto statement?
3. What is ternary operator? Give example.
4. Give the syntax of switch statement.
5 mark Questions:
1. Explain the various forms if statement with example.
2. Explain the working of switch statement with an example.
Compiled By
Panchajanyeswari M Achar Page 175
Srinivas Institute of Management Studies V Semester BCA
CHAPTER 16
16.1 Introduction
Looping is executing a sequence of statements until some conditions to terminate the loop are
satisfied. A program loop consists of 2 segments i.e. body of the loop and control statements.
The control statements test certain condition and then direct repeated execution of statements
contained in the body of the loop. A looping process includes the following steps
1. Setting and initializing of a counter
2. Execution of statements in a loop
3. Test for specified condition for executing the loop
4. Incrementing the counter
initialization;
while(test condition)
{
Body of the loop;
}
Here, the body of the loop can contain more than one statement. If the condition is initially false,
the body of the loop will not be executed at all.
Example:
using System;
Compiled By
Panchajanyeswari M Achar Page 176
Srinivas Institute of Management Studies V Semester BCA
namespace Loops
{
class Program
{
static void Main(string[] args)
{
/* local variable definition */
int a = 10;
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Compiled By
Panchajanyeswari M Achar Page 177
Srinivas Institute of Management Studies V Semester BCA
This loop is an exit controlled loop because the condition is checked after executing the
statements in the loop. Here the statements are executed first and then, checks the condition. The
body of the loop is executed at least once even if the condition is initially false. On reaching the
do statement the body of the loop is executed. The test condition in the while statement is
evaluated. If the condition is true, execution of the loop is repeated. This process continues as
long as the condition specified in the while statement is true. Once the condition becomes false,
the loop is terminated and the control goes to the statement after the while statement.
Compiled By
Panchajanyeswari M Achar Page 178
Srinivas Institute of Management Studies V Semester BCA
}
while (condition);
Example:
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
/* local variable definition */
int a = 10;
/* do loop execution */
do
{
[Link]("value of a: {0}", a);
a = a + 1;
} while (a < 15);
[Link]();
}
}
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
Compiled By
Panchajanyeswari M Achar Page 179
Srinivas Institute of Management Studies V Semester BCA
}
The execution of this loop is as follows:
• Initialization of the control variable is done using the assignment operator. More than one
assignment can be made here, but, they must be separated by a comma operator.
• The value of the control variable is tested in the test condition. The test condition is any
relational expression that determines when the loop will be terminated. The body of the
loop executes as long as the condition is true.
• After the body of the loop is executed the control is transferred back to the for statement.
Now the control variable is either incremented or decremented and its new value is tested
to check if it satisfies the loop condition. This process continues till the value of the
control variable fails to satisfy the test condition
Example:
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
for(i=0; i<=4; i++)
{
[Link](i);
}
[Link]();
}
}
}
When the above code is compiled and executed, it produces the following result:
0
1
2
3
4
Compiled By
Panchajanyeswari M Achar Page 180
Srinivas Institute of Management Studies V Semester BCA
The foreach statement repeats a group of embedded statements for each element in an
array or an object collection that implements the [Link]
or [Link]<T> interface. The foreach statement is used to
iterate through the collection to get the information that you want, but cannot be used to add or
remove items from the source collection to avoid unpredictable side effects. If you need to add or
remove items from the source collection, use a for loop.
The embedded statements continue to execute for each element in the array or collection.
After the iteration has been completed for all the elements in the collection, control is transferred
to the next statement following the foreach block. At any point within the foreach block, you can
break out of the loop by using the break keyword, or step to the next iteration in the loop by
using the continuekeyword. A foreach loop can also be exited by the goto, return,
or throw statements.
Example:
using System;
class Program
{
static void Main()
{
// Use a string array to loop over.
string[] flowers =
{
"Rose",
"Lily",
"Lotus",
"Tulip"
};
// Loop with the foreach keyword.
foreach (string value in flowers)
{
[Link](value);
}
}
}
Output:
Compiled By
Panchajanyeswari M Achar Page 181
Srinivas Institute of Management Studies V Semester BCA
Rose,
Lily,
Lotus,
Tulip
Like a while statement, except that it tests the condition at the end of
do...while loop
the loop body
You can use one or more loop inside any another while, for or
nested loops
do..while loop.
Compiled By
Panchajanyeswari M Achar Page 182
Srinivas Institute of Management Studies V Semester BCA
Assignment
2 mark Questions:
1. What is the purpose of break statement in C#?
2. What is the purpose of continue statement in C#?
3. Give the difference between break and continue statements.
4. Give the syntax of while loop.
5. Give the syntax of do..while loop.
6. Give the syntax of for loop.
7. Give the syntax of for-each loop.
5 mark Questions:
1. Explain the working of while loop with syntax and example
2. Explain the working of do..while loop with syntax and example
3. Explain the working of for loop with syntax and example
4. Explain the working of for each loop with syntax and example
Compiled By
Panchajanyeswari M Achar Page 183
Srinivas Institute of Management Studies V Semester BCA
CHAPTER 17
METHODS IN C#
17.1 Introduction:
Methods are declared inside the body of the class, normally after the declaration of the
data fields. The general form of a method declaration is
<Access Specifier> <Return Type> <Method Name>(Parameter List)
{
Method Body
}
• Access Specifier: This determines the visibility of a variable or a method from another
class.
Compiled By
Panchajanyeswari M Achar Page 184
Srinivas Institute of Management Studies V Semester BCA
• Return type: A method may return a value. The return type is the data type of the value
the method returns. If the method is not returning any values, then the return type is void.
• Method name: Method name is a unique identifier and it is case sensitive. It cannot be
same as any other identifier declared in the class.
• Parameter list: Enclosed between parentheses, the parameters are used to pass and receive
data from a method. The parameter list refers to the type, order, and number of the
parameters of a method. Parameters are optional; that is, a method may contain no
parameters.
• Method body: This contains the set of instructions needed to complete the required
activity.
Example:
Following code snippet shows a function FindMax that takes two integer values and
returns the larger of the two. It has public access specifier, so it can be accessed from outside the
class using an instance of the class.
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;
return result;
}
...
}
Compiled By
Panchajanyeswari M Achar Page 185
Srinivas Institute of Management Studies V Semester BCA
In the parameter list, the actual parameters are separated by commas that must match in
type, order and number with the formal parameter list of the method name declared in the class.
Example:
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;
return result;
}
static void Main(string[] args)
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
NumberManipulator n = new NumberManipulator();
Compiled By
Panchajanyeswari M Achar Page 186
Srinivas Institute of Management Studies V Semester BCA
}
}
When the above code is compiled and executed, it produces the following result:
Max value is : 200
A method can be called using only its name by another method of the same class. This is
called nesting of methods.
Example:
using System;
class Nesting
{
void Largest(int m, int n)
{
int large=Max(m,n);
[Link](large);
}
int Max(int a, int b)
{
int x= (a>b)?a:b;
return(x);
}
}
class NestTest
{
public static void main()
{
[Link] = new Nesting();
[Link](100,200);
}
}
Compiled By
Panchajanyeswari M Achar Page 187
Srinivas Institute of Management Studies V Semester BCA
• Value Parameters
• Reference parameters
• Output parameters
• Parameter arrays
Example:
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public void swap(int x, int y)
{
int temp;
[Link]();
}
}
}
When the above code is compiled and executed, it produces the following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
Example:
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public void swap(ref int x, ref int y)
{
int temp;
Compiled By
Panchajanyeswari M Achar Page 189
Srinivas Institute of Management Studies V Semester BCA
[Link]();
}
}
}
When the above code is compiled and executed, it produces the following result:
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100
Compiled By
Panchajanyeswari M Achar Page 190
Srinivas Institute of Management Studies V Semester BCA
Example:
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public void getValue(out int x )
{
int temp = 5;
x = temp;
}
When the above code is compiled and executed, it produces the following result:
Before method call, value of a : 100
After method call, value of a : 5
Compiled By
Panchajanyeswari M Achar Page 191
Srinivas Institute of Management Studies V Semester BCA
dimensional array type. For example, the types string[] and string[][] can be used as the type of a
parameter array, but the type string[,] cannot. It is not possible to combine the params modifier
with the ref and out modifiers.
Example:
using System;
namespace ArrayApplication
{
class ParamArray
{
public int AddElements(params int[] arr)
{
int sum = 0;
foreach (int i in arr)
{
sum += i;
}
return sum;
}
}
class TestClass
{
static void Main(string[] args)
{
ParamArray app = new ParamArray();
int sum = [Link](512, 720, 250, 567, 889);
[Link]("The sum is: {0}", sum);
[Link]();
}
}
}
When the above code is compiled and executed, it produces the following result:
The sum is: 2938
Compiled By
Panchajanyeswari M Achar Page 192
Srinivas Institute of Management Studies V Semester BCA
C# allows us to create more than one method with the same name but with different
parameter list and different definition. This is called method overloading. Method overloading is
used when methods are required to perform similar tasks but using different input parameters.
Example:
public class Class1
{
public void NumbersAdd(int a, int b)
{
[Link](a + b);
}
public void NumbersAdd(int a, int b, int c)
{
[Link](a + b + c);
}
}
Assignment
2 marks
5. Define a method in C#.
6. Give the syntax of declaring methods in C#
7. How do you invoke methods in C#?
8. List the various ways in which parameters can be passed in C# methods.
5 marks
1. Explain the concept of working with methods in C#.
2. Explain pass by value in C#
3. Explain pass by reference in C#
CHAPTER 18
18.1 Introduction:
Compiled By
Panchajanyeswari M Achar Page 193
Srinivas Institute of Management Studies V Semester BCA
Encapsulation provides the ability to hide the internal details of an object from its users.
The outside user cannot change the state of an object directly. The state of an object can be
altered indirectly using accessor and mutator methods. In C#, encapsulation can be implemented
using access modifier keywords public, private and protected. The concept of encapsulation is
also called data hiding or information hiding.
Inheritance is a concept where we build new classes using existing class definitions.
Through inheritance we can modify a class the way we to create new objects. The original class
is called the parent class and the modified class is called subclass, child class or derived class.
The concept of inheritance facilitates reusability of existing code and improves the integrity of
the program
Polymorphism is the ability to take more than one form. For example, an operation may
exhibit different behavior in different situations. The behavior depends on the different types of
data used in the operation.
A class definition starts with the keyword class followed by the class name; and
the class body, enclosed by a pair of curly braces. Following is the general form of a class
definition:
Compiled By
Panchajanyeswari M Achar Page 194
Srinivas Institute of Management Studies V Semester BCA
// box 1 specification
[Link] = 5.0;
[Link] = 6.0;
[Link] = 7.0;
// box 2 specification
[Link] = 10.0;
[Link] = 12.0;
[Link] = 13.0;
// volume of box 1
volume = [Link] * [Link] * [Link];
[Link]("Volume of Box1 : {0}", volume);
// volume of box 2
volume = [Link] * [Link] * [Link];
[Link]("Volume of Box2 : {0}", volume);
[Link]();
}
}
}
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
Compiled By
Panchajanyeswari M Achar Page 196
Srinivas Institute of Management Studies V Semester BCA
Data is encapsulated in a class by placing the data fields inside the body of the class
definition. These variables are called instance variables because they are created whenever the
class is instantiated. They are declared in the same way as local variables.
Example:
class Rectangle
{
int length;
int height;
}
A member function of a class is a function that has its definition or its prototype within
the class definition like any other variable. It operates on any object of the class of which it is a
member, and has access to all the members of a class for that object.
Member variables are attributes of an object (from design perspective) and they are kept
private to implement encapsulation. These variables can only be accessed using the public
member functions.
The general format of method declaration is
type method-name(parameter-list)
{
Method-body;
}
Example:
class Rectangle
{
int length;
int width;
public void GetData(int x, int y)
{
length = x;
width = y;
}
}
Compiled By
Panchajanyeswari M Achar Page 197
Srinivas Institute of Management Studies V Semester BCA
The following five accessibility levels can be specified using the access modifiers:
• public: Member is accessible from anywhere outside the class. Access is not restricted.
• protected: Member is visible only to its own class and its derived class.
• Internal: Access is limited to the current assembly or component that is being created but
not to the clients of that component.
• protected internal: Access is limited to the current assembly or types derived from the
containing class.
• private: Member is accessible only in the class containing the member.
Objects in C# are created using new operator. The new operator creates an object of the
specified class and returns a reference to that object.
Example:
Rectangle rect1; //declare
rect1 = new Rectangle(); // instantiate
18.8 Constructors:
}
public double getLength()
{
return length;
}
When the above code is compiled and executed, it produces the following result:
Object is being created
Length of line : 6
Overloaded constructors can be used to instantiate objects in exactly the same manner as
for classes with a single constructor. During compilation of the code, the compiler compares the
signature used for the new object to those available in the class. If there is a perfect match, the
corresponding constructor is used. Where there is no signature with the correct parameters, the
compiler will look for a constructor that can be used with implicit casting. If no such constructor
exists, a compiler error occurs.
We can now test the example code by modifying the program's main method as follows:
static void Main(string[] args)
{
Rectangle rect = new Rectangle(4, 6);
[Link]("Height: {0}", [Link]);
[Link]("Width: {0}", [Link]);
Compiled By
Panchajanyeswari M Achar Page 199
Srinivas Institute of Management Studies V Semester BCA
/* OUTPUT
*/
A static constructor is called before any object of the class is created. It is usually use to
assign initial values to static data members. A static constructor is declared by prefixing a static
keyword to the constructor definition
Example
class Sample
{
static Sample()
{
……
}
}
A copy constructor creates an object by copying the variables from another object. A
copy constructor is defined as follows:
public Item(Item item)
{
code = [Link];
price = [Link];
}
Compiled By
Panchajanyeswari M Achar Page 200
Srinivas Institute of Management Studies V Semester BCA
The copy constructor is invoked by instantiating an object of type Item and passing it to the
object to be copied.
Example:
Item item2 = new Item(item1);
18.8.4 Destructors
Example:
class Car
{
~Car() // destructor
{
// cleanup statements...
}
}
The this keyword refers to the current instance of the class and is also used as a modifier
of the first parameter of an extension method.
Example:
public Employee(string name, string alias)
{
// Use this to qualify the fields, name and alias:
[Link] = name;
[Link] = alias;
}
Compiled By
Panchajanyeswari M Achar Page 201
Srinivas Institute of Management Studies V Semester BCA
The readonly keyword is a modifier that you can use on fields. When a field declaration
includes a readonly modifier, assignments to the fields introduced by the declaration can only
occur as part of the declaration or in a constructor in the same class.
Example:
class Age
{
readonly int _year;
Age(int year)
{
_year = year;
}
void ChangeYear()
{
//_year = 1967; // Compile error if uncommented.
}
}
In this example, the value of the field year cannot be changed in the method ChangeYear, even
though it is assigned a value in the class constructor.
18.11 Properties
Properties are named members of classes, structures, and interfaces. Member variables or
methods in a class or structures are called Fields. Properties are an extension of fields and are
accessed using the same syntax. They use accessors through which the values of the private
fields can be read, written or manipulated.
Properties do not name the storage locations. Instead, they have accessors that read,
write, or compute their values. For example, let us have a class named Student, with private
fields for age, name and code. We cannot directly access these fields from outside the class
scope, but we can have properties for accessing these private fields.
18.11.1 Accessors
The accessor of a property contains the executable statements that helps in getting
(reading or computing) or setting (writing) the property. The accessor declarations can contain a
get accessor, a set accessor, or both. For example:
// Declare a Code property of type string:
public string Code
Compiled By
Panchajanyeswari M Achar Page 202
Srinivas Institute of Management Studies V Semester BCA
{
get
{
return code;
}
set
{
code = value;
}
}
Example:
Compiled By
Panchajanyeswari M Achar Page 203
Srinivas Institute of Management Studies V Semester BCA
Compiled By
Panchajanyeswari M Achar Page 204
Srinivas Institute of Management Studies V Semester BCA
Compiled By
Panchajanyeswari M Achar Page 205
Srinivas Institute of Management Studies V Semester BCA
18.12 Indexers
An indexer allows an object to be indexed like an array. When you define an indexer for
a class, this class behaves like a virtual array. You can then access the instance of this class using
the array access operator ([ ]).
Syntax
A one dimensional indexer has the following syntax:
element-type this[int index]
{
// The get accessor.
get
{
// return the value specified by index
}
Example
using System;
namespace IndexerApplication
{
class IndexedNames
Compiled By
Panchajanyeswari M Achar Page 206
Srinivas Institute of Management Studies V Semester BCA
{
private string[] namelist = new string[size];
static public int size = 10;
public IndexedNames()
{
for (int i = 0; i < size; i++)
namelist[i] = "N. A.";
}
public string this[int index]
{
get
{
string tmp;
return ( tmp );
}
set
{
if( index >= 0 && index <= size-1 )
{
namelist[index] = value;
}
}
}
Compiled By
Panchajanyeswari M Achar Page 207
Srinivas Institute of Management Studies V Semester BCA
names[2] = "Arjith";
names[3] = "Asif";
names[4] = "David";
names[5] = "Sunil";
names[6] = "Riya";
for ( int i = 0; i < [Link]; i++ )
{
[Link](names[i]);
}
[Link]();
}
}
}
When the above code is compiled and executed, it produces the following result:
Janani
Jahnavi
Arjith
Asif
David
Sunil
Riya
N.A
N.A
N.A
Assignment
2 marks
9. Define encapsulation
10. Define polymorphism
11. Define inheritance
12. Define a class
13. Define a constructor
14. Define a destructor
15. Define indexers
16. Why do you use a this keyword in C#?
5 marks
1. Explain the principles of OOPs
Compiled By
Panchajanyeswari M Achar Page 208
Srinivas Institute of Management Studies V Semester BCA
CHAPTER 19
INTERFACES
19.1 Introduction:
Interfaces define properties, methods and events, which are the members of the interface.
Interfaces contain only the declaration of the members. It is the responsibility of the deriving
Compiled By
Panchajanyeswari M Achar Page 209
Srinivas Institute of Management Studies V Semester BCA
class to define the members. It often helps in providing a standard structure that the deriving
classes would follow.
Syntax:
interface InterfaceName
{
Member declarations;
}
Here, interface is a keyword and interface name is any valid identifier in C#. Member
declarations will contain only the list of members without implementation code.
Example:
Like classes, interfaces can also be extended. An interface can be sub interfaced from
other interfaces. The new sub interface will inherit all the members of the super interface. This is
achieved as follows:
interface name2 : name1
{
Members of name2
}
Example:
interface Addition
{
int Add(int x, int y);
}
Here, the interface Compute will have both the methods and any class implementing the
interface Compute should implement both of them; otherwise, it is an error.
Compiled By
Panchajanyeswari M Achar Page 210
Srinivas Institute of Management Studies V Semester BCA
Interfaces are used as super classes whose properties are inherited by classes. It is
therefore necessary to create a class that inherits the given interface. This is done as follows:
Example:
using [Link];
using [Link];
using [Link];
namespace InterfaceApplication
{
return amount;
}
public void showTransaction()
{
[Link]("Transaction: {0}", tCode);
[Link]("Date: {0}", date);
[Link]("Amount: {0}", getAmount());
}
class Tester
{
static void Main(string[] args)
{
Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);
Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);
[Link]();
[Link]();
[Link]();
}
}
}
When the above code is compiled and executed, it produces the following result:
Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900
Most often we have situations where the base class implements an interface. In such
situations, when an object of the derived class is converted to interface type, the inheritance
hierarchy is searched until it finds a class that directly implements the interface.
An abstract class is a class that cannot be instantiated, but must be inherited from. An
abstract class may be fully implemented, but is more usually partially implemented or not
implemented at all, thereby encapsulating common functionality for inherited classes.
An interface, by contrast, is a totally abstract set of members that can be thought of as defining a
contract for conduct. The implementation of an interface is left completely to the developer.
Compiled By
Panchajanyeswari M Achar Page 212
Srinivas Institute of Management Studies V Semester BCA
Example:
interface A
{
Void Method();
}
abstract class B : A
{
……….
……….
public abstract void Method();
}
Here, class B does not implement the interface method; it simply redeclares as public abstract
method. It is the duty of the class that derives from B to override and implement the method.
Assignment
2 marks
17. Define an interface in C#
18. How do you define an interface in C#?
19. Define an abstract class.
20. How do you extend an interface in C#?
21. Define inheritance
5 marks
1. How do you work with interfaces in C#
2. Explain the concept of abstract classes in C#
CHAPTER 20
Compiled By
Panchajanyeswari M Achar Page 213
Srinivas Institute of Management Studies V Semester BCA
20.1 Introduction:
A delegate is a reference type, like the other reference types you've seen in this book, but
instead of referring to an object, a delegate refers to a method. This is called encapsulating the
method. When you create the delegate, you specify a method signature and return type; you can
encapsulate any matching method with that delegate. Creating and using delegates involve four
steps
• Delegate declaration
• Delegate method declaration
• Delegate instantiation
• Delegate invocation
A delegate declaration defines a class using the class [Link] as a base class.
Delegate methods are any functions whose signature matches the delegate signature exactly. The
delegate instance holds the reference to delegate methods. The instance is used to invoke the
methods indirectly. An important feature of delegate is that it can be used to hold reference to a
method of any class.
Here,
• The delegate key word represents that the declaration represents a class type derived
from [Link]
• The return type indicates the return type of the delegate
• Parameters identify the signature of the delegate
• The delegate-name is any valid C# identifier and represents the name of the delegate that
will be used to instantiate the delegate objects
• The modifier controls the accessibility of the delegate. Delegates can take the following
modifiers i.e. new, public, private, protected and internal
Compiled By
Panchajanyeswari M Achar Page 214
Srinivas Institute of Management Studies V Semester BCA
Once a delegate type has been declared, a delegate object must be created with
the new keyword and be associated with a particular method. When creating a delegate, the
argument passed to the new expression is written like a method call, but without the arguments
to the method. For example:
[Link]();
}
}
}
When the above code is compiled and executed, it produces the following result:
Value of Num: 35
Value of Num: 175
C# provides special syntax for invoking a delegate. When a delegate is invoked, it in turn
invokes the method whose reference has been encapsulated into the delegate. Invocation takes
the following form:
delegate_object(parameter_list)
The following example demonstrates the use of delegate. The delegate printString can be
used to reference methods that take a string as input and return nothing.
We use this delegate to call two methods, the first prints the string to the console, and the second
one prints it to a file:
using System;
using [Link];
namespace DelegateAppl
{
class PrintString
{
static FileStream fs;
static StreamWriter sw;
// delegate declaration
public delegate void printString(string s);
[Link], [Link]);
sw = new StreamWriter(fs);
[Link](s);
[Link]();
[Link]();
[Link]();
}
// this method takes the delegate as parameter and uses it to
// call the methods as required
public static void sendString(printString ps)
{
ps("Hello World");
}
static void Main(string[] args)
{
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
sendString(ps1);
sendString(ps2);
[Link]();
}
}
}
When the above code is compiled and executed, it produces the following result:
The String is: Hello World
Delegate objects can be composed using the "+" operator. A composed delegate calls the
two delegates it was composed from. Only delegates of the same type can be composed. The "-"
operator can be used to remove a component delegate from a composed delegate.
Using this useful property of delegates you can create an invocation list of methods that will be
called when a delegate is invoked. This is called multicasting of a delegate. The following
program demonstrates multicasting of a delegate:
using System;
return num;
}
20.7 Events
An event is a delegate type class member that is used by the object or class to provide a
notification to other objects that an event has occurred. The client object can act on an event by
adding an event handler to the event.
An event can be declared as follows:
Examples:
Compiled By
Panchajanyeswari M Achar Page 218
Srinivas Institute of Management Studies V Semester BCA
In the above examples, EventHandler and RateChange are delegates and Click and Rate are
events.
Example:
using System;
namespace SimpleEvent
{
using System;
}
public EventTest(int n )
{
SetValue(n);
}
public void SetValue(int n)
{
if (value != n)
{
value = n;
OnNumChanged();
}
}
}
public class MainClass
{
public static void Main()
Compiled By
Panchajanyeswari M Achar Page 219
Srinivas Institute of Management Studies V Semester BCA
{
EventTest e = new EventTest(5);
[Link](7);
[Link](11);
[Link]();
}
}
}
When the above code is compiled and executed, it produces the following result:
Event Fired!
Event Fired!
Event Fired!
Assignment:
2 marks Questions
1. Define delegate
2. Define an event
3. Define a multicast delegate.
4. How do you invoke a delegate in C#?
5. How do you declare an event in C#?
6. How do you declare a delegate in C#?
5 marks
1. Explain about events in C#
2. Explain the concept of delegates in C#
Question Bank
UNIT – IV
Short answer questions (2 marks)
1. What do you mean by Boxing/Unboxing ?
2. Write the basic steps used in the looping process .
3. How do we invoke methods in C#?
4. List the different types of Method Parameters used.
5. Distinguish between ref and out parameters.
6. List any four method modifiers used .
7. What are Static constructors?
8. What is a Delegate ? What is it used for?
9. List the steps involved in creating and using a delegates.
10. What is an Event ? Give the syntax of event declaration.
[Link] is a development framework for building web pages and web sites with
HTML, CSS, JavaScript and server [Link] supports three different development
models:Web Pages, MVC (Model View Controller), and Web Forms.
MVC is one of three [Link] programming models. MVC is a framework for building
web applications using a MVC (Model View Controller) design:
• The Model represents the application core (for instance a list of database records).
Compiled By
Panchajanyeswari M Achar Page 221
Srinivas Institute of Management Studies V Semester BCA
The MVC model also provides full control over HTML, CSS, and JavaScript.
The Model is the part of the application that handles the logic for the application data.
Often model objects retrieve data (and store data) from a database.
The View is the parts of the application that handles the display of the data.
Most often the views are created from the model data.
The Controller is the part of the application that handles user interaction.
Typically controllers read data from a view, control user input, and send input data to the model.
The MVC separation helps you manage complex applications, because you can focus on
one aspect a time. For example, you can focus on the view without depending on the business
logic. It also makes it easier to test an application. The MVC separation also simplifies group
development. Different developers can work on the view, the controller logic, and the business
logic in parallel.
Compiled By
Panchajanyeswari M Achar Page 222
Srinivas Institute of Management Studies V Semester BCA
The MVC programming model is a lighter alternative to traditional [Link] (Web Forms). It is
a lightweight, highly testable framework, integrated with all existing [Link] features, such as
Master Pages, Security, and Authentication.
MVC Folders
A typical [Link] MVC web application has the following folder content:
Compiled By
Panchajanyeswari M Achar Page 224
Srinivas Institute of Management Studies V Semester BCA
Application information
Properties
References
Application folders
App_Data Folder
Content Folder
Controllers Folder
Models Folder
Scripts Folder
Views Folder
Configuration files
[Link]
[Link]
[Link]
The folder names are equal in all MVC applications. The MVC framework is based on default
naming. Controllers are in the Controllers folder, Views are in the Views folder, and Models are
in the Models folder. You don't have to use the folder names in your application code.
Standard naming reduces the amount of code, and makes it easier for developers to understand
MVC projects.
The Content folder is used for static files like style sheets (css files), icons and images.
Visual Web Developer automatically adds a themes folder to the Content folder. The themes
folder is filled with jQuery styles and pictures. In this project you can delete the themes folder.
Visual Web Developer also adds a standard style sheet file to the project: the file [Link] in the
content folder. The style sheet file is the file to edit when you want to change the style of the
application.
Compiled By
Panchajanyeswari M Achar Page 225
Srinivas Institute of Management Studies V Semester BCA
The Controllers folder contains the controller classes responsible for handling user input and
responses.
MVC requires the name of all controller files to end with "Controller".
Visual Web Developer has created a Home controller (for the Home and the About page) and an
Account controller (for Login pages):
Compiled By
Panchajanyeswari M Achar Page 226
Srinivas Institute of Management Studies V Semester BCA
Compiled By
Panchajanyeswari M Achar Page 227
Srinivas Institute of Management Studies V Semester BCA
Note: The files named "modernizr" are JavaScript files used for supporting HTML
Compiled By
Panchajanyeswari M Achar Page 228
Srinivas Institute of Management Studies V Semester BCA
Part A (2x10=20)
1. a. How do you create hyperlinks in HTML? Give example.
b. Give the syntax of CSS element with an example
c. Give the doctype declaration and character set encoding in HTML5.
d. What is the purpose of runat attribute in HTML server controls.
e. What is the purpose of rangevalidator control in [Link]
f. List any four data bound controls in [Link]
g. Give the acronym of SOAP and UDDI
h. List the caching techniques available in [Link] 2.0
i. How can you add comments in a C# program?
j. Give the syntax of for each statement in C# with an example.
k. Give the syntax of declaring methods in C# with an example
l. What is a copy constructor in C#? Give example.
Part B
UNIT I
UNIT II
4. a. Explain any five differences between ASP and [Link]
b. Explain the adRotator control in [Link] with all its properties
c. Explain the RequiredField Validator control in [Link]
d. Explain the SQLDataSource control in [Link] with its methods and properties.
Compiled By
Panchajanyeswari M Achar Page 229
Srinivas Institute of Management Studies V Semester BCA
(5+4+5+6)
5. a. Explain the dropdown list control in [Link] with all its properties
b. Explain the characteristics of [Link]
c. Explain the ValidationSummary Control in [Link] with its properties.
d. Explain the building blocks of XML (5+5+5+5)
UNIT III
UNIT IV
8. a. Explain the else-if construct in C# with syntax and an example.
b. Explain the concept of invoking methods in C# with an example
c. Define an interface. How do you implement interfaces in C#? Give example
d. How do you declare and instantiate a delegate in C#? Give example (5+5+5+5)
Compiled By
Panchajanyeswari M Achar Page 230