0% found this document useful (0 votes)
24 views235 pages

Complete Notes

The document is a background study material for BCA V Semester students at Srinivas Institute of Management Studies, focusing on web development in .NET. It covers various topics including HTML, CSS, ASP.NET, C#, and web services, structured into chapters with assignment questions. The content is designed to provide foundational knowledge and practical skills in web development technologies and programming languages.

Uploaded by

prajwalprabhu025
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views235 pages

Complete Notes

The document is a background study material for BCA V Semester students at Srinivas Institute of Management Studies, focusing on web development in .NET. It covers various topics including HTML, CSS, ASP.NET, C#, and web services, structured into chapters with assignment questions. The content is designed to provide foundational knowledge and practical skills in web development technologies and programming languages.

Uploaded by

prajwalprabhu025
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Srinivas Institute of Management Studies

Pandeshwar, Mangalore – 575 001


BACKGROUND STUDY MATERIAL

WEB DEVELOPMENT IN .NET


BCA V Semester

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

Chapter 11 Introduction to Deployment


11.1 Introduction
11.2 Types of Deployment Projects
11.3 Caching
11.4 Threads
11.5 Securing [Link] Applications
11.6 Microsoft .NET Framework Security
11.7 Configuring an [Link] Web Application for Authentication
11.8 Overview of Authorization
Assignment questions
Chapter 12 Overview of C#
12.1 Introduction
12.2 Simple C# Program
12.3 Namespaces
12.4 Comments in C#
12.5 Using Aliases for Namespaces
12.6 Passing strings as objects to WriteLine Method
12.7 Structure of C# Program
Assignment questions
Chapter 13 Literals, Variables, Data Types
13.1 Introduction
13.2 Literals
13.3 Variables
13.4 Data Types
13.5 Declaration of Variables
13.6 Initialization of Variables
13.7 Constant Variables
13.8 Scope of Variables
13.9 Boxing and Unboxing
Assignment questions
Chapter 14
14.1 Introduction
14.2 Arithmetic Operators
14.3 Relational Operators
14.4 Logical Operators
14.5 Assignment Operators
14.6 Increment/decrement operators
14.7 Conditional operators
14.8 Bitwise Operators
14.9 Special Operators
14.10 Arithmetic Expressions
14.11 Precedence of Arithmetic Operators
14.12 Type Conversions
14.13 Mathematical Functions
Assignment questions
Chapter 15 Decision Making and Branching
15.1 Introduction
15.2 The if statement
15.3 The switch statement
Assignment
Chapter 16 Decision Making and Looping
16.1 Introduction
16.2 The while statement
16.3 The do-while statement
16.4 For loop
16.5 For–each loop
16.6 The break statement
16.7 The continue statement
Assignment
Chapter 17 Methods in C#
17.1 Introduction
17.2 Declaring Methods
17.3 Invoking Methods
17.4 Nesting of Methods
17.5 Method Parameters
17.6 Method Overloading
Assignment
Chapter 18 Classes and Objects
18.1 Introduction
18.2 Principles of OOPs
18.3 Defining a Class
18.4 Adding Variable
18.5 Adding Methods:
18.6 Member Access Modifiers
18.7 Creating Objects
18.8 Constructors
18.9 The this reference
18.10 The readonly members
18.11 Properties
18.12 Indexers
Assignment
Chapter 19 Interfaces
19.1 Introduction
19.2 Defining Interfaces
19.3 Extending an Interface
19.4 Implementing an Interface
19.5 Interfaces and Inheritance
19.6 Abstract Classes and Interfaces
Assignment
Chapter 20 Delegates and Events
20.1 Introduction
20.2 Delegate Declaration
20.3 Delegate instantiation
20.4 Delegate invocation
20.5 Using Delegates
20.6 Multicast Delegates
20.7 Events
Assignment
Chapter 21 [Link] with MVC – An Introduction
Srinivas Institute of Management Studies V Semester BCA

UNIT I
CHAPTER 1
INTRODUCTION TO HTML

1.1 Concepts of Hypertext

Hypertext is based on the concept of "Expanding Information". Blocks of information


(text or graphics) can be linked to other blocks of information. Once two blocks of
information have been linked together, they provide an instant "gateway" to the other. A
single block of information can lead to another and so on. Information can literally expand at
the user's request. A hypertext document is a NONLINEAR document with many links.

1.2 Versions of HTML

HTML 1.0 (1989 - 1994)

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.

HTML 2.0 (1995)

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

HTML 3.20 (1997)

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.

HTML 4.01 (1999)

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

1.3.1 Structure of HTML Program

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:

1.3.2 HTML Element Syntax


• An HTML element starts with a start tag / opening tag
• An HTML element ends with an end tag / closing tag
• The element content is everything between the start and the end tag
• Some HTML elements have empty content
Compiled By
Panchajanyeswari M Achar Page 3
Srinivas Institute of Management Studies V Semester BCA

• Empty elements are closed in the start tag


• Most HTML elements can have attributes
• Most HTML elements can be nested (can contain other HTML elements).
• HTML documents consist of nested HTML elements.

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.

1.4 Building HTML Documents

1.4.1 Body Element


The <body> element defines the body of the HTML document. The element has a start
tag <body> and an end tag </body>. The various attributes of body tag are listed below
Attribute Value Description
alink color Specifies the color of an active link in a document
Background URL Specifies a background image for a document
bgcolor color Specifies the background color of a document
link color Specifies the color of unvisited links in a document
text color Specifies the color of the text in a document
vlink color Specifies the color of visited links in a document

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.

Create Headings - The <hn> 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:

Create Paragraph - The <p> Element:

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:

You can use align attribute to align your paragraphs.


<html>
<body>
<p align="left">This is left aligned.</p>
<p align="center">This is center aligned.</p>
<p align="right">This is right aligned.</p>
<p align="justify">This is justified. This works when you have multiple lines in your paragraph
and you want to justify all the lines so that they can look more nice.</p>
</body>
</html>

This will produce following result:

Compiled By
Panchajanyeswari M Achar Page 6
Srinivas Institute of Management Studies V Semester BCA

Create Line Breaks - The <br> Element:

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:

Preserve Formatting - The <pre> Element:

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 - The <hr> Element

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.

Bold Text - The <b> Element:

Anything that appears in a <b>...</b> element is displayed in bold.

Italic Text - The <i> Element:

Anything that appears in a <i>...</i> element is displayed in italicized.

Underlined Text - The <u> Element:

Anything that appears in a <u>...</u> element is displayed with underline

Strike Text - The <strike> Element:

Anything that appears in a <strike>...</strike> element is displayed with strikethrough,


which is a thin line through the text.

Superscript Text - The <sup> Element:

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

Subscript Text - The <sub> Element:

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:

A HTML marquee is a scrolling piece of text displayed either horizontally across or


vertically down your web page depending on the settings. This is created by using HTML tag
<marquee>.

Compiled By
Panchajanyeswari M Achar Page 10
Srinivas Institute of Management Studies V Semester BCA

Syntax:

A simple syntax to use marquee is as follows:

<marquee attribute_name="attribute_value"....more attributes>


One or more lines or text message or image
</marquee>

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 >

Attributes of <img> tag:

Following are the attributes for <img> tag.


• width: sets width of the image. This will have a value like 10 or 20%etc.
• height: sets height of the image. This will have a value like 10 or 20% etc.
• border: sets a border around the image. This will have a value like 1 or 2 etc.
• src: specifies URL of the image file.
• alt: this is an alternate text which will be displayed if image is missing.
• align: this sets horizontal alignment of the image and takes value either left, right or
center.
• valign: this sets vertical alignment of the image and takes value either top, bottom or
center.
• hspace: horizontal space around the image. This will have a value like 10 or 20%etc.
• vspace: vertical space around the image. This will have a value like 10 or 20%etc.
• name: name of the image with in the document.
• id: id of the image with in the document.
• style: this will be used if you are using CSS.

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

• An unvisited link is underlined and blue


• A visited link is underlined and purple
• An active link is underlined and red

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

Srinivas Institute of Management Studies V Semester BCA

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:

1.4.4 Background and color controls


Colors are set using “RGB” color codes, which are, represented as hexadecimal values.
Each 2-digit section of the code represents the amount, in sequence, of red, green or blue
that forms the color. For example, a RGB

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:

1.4.5 Font tag and attributes

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:

1.4.6 List types

HTML supports three types of lists. They are


• Unordered list – An unordered list starts with the <ul> tag. Each list item starts
with the <li> tag. The list items are marked with bullets typically small black
circles
• Ordered list – An ordered list starts with the <ol> tag. Each list item starts with
the <li> tag. The list items are marked with numbers.
• Definition lists - A definition list is a list of terms, with a description of each term.
Definition list values appear within <dl> and </dl> tag. It consists of two parts:
Definition Term <DT> and the Definition Description <DD>

Example 1: Illustration of unordered lists

<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:

Example 2: Illustration of ordered lists

<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:

Example 3: Illustration of Definition lists


Compiled By
Panchajanyeswari M Achar Page 18
Srinivas Institute of Management Studies V Semester BCA

<html>
<body>
<dl>
<dt> Keyboard
<dd> It is an input device
<dt> Printer
<dd> It is an output device
<dl>
</body>
</html>
Output:

1.4.7 Table Layout

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

<td>Row 1, Column 2</td>


</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>

Table Heading - The <th> Element:

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

Table Cellpadding and Cellspacing:

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:

Colspan and Rowspan Attributes:

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.

Table height and width:

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.

Using Table Caption:

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:

1.4.8 Use of Frames

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.

The <frameset> Element:

• The <frameset> tag replaces the <body> element in frameset documents.


• The <frameset> tag defines how to divide the window into frames.
• Each frameset defines a set of rows or columns. If you define frames by using rows then
horizontal frames are created. If you define frames by using columns then vertical farmes
are created.
• The values of the rows/columns indicate the amount of screen area each row/column will
occupy.

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.

The <frameset> Element Attributes:

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:

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

The <frame> Element Attributes:

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.

The <noframes> Element:

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.

Frame's name and target attributes:

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:

1.4.9 Forms in web pages

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.

A simple syntax of using <form> is as follows:

<form action="back-end script" method="posting method">


form elements like input, textarea etc.
</form>
The various form attributes are:
• name: This is the name of the form.
• action: Here you will specify any script URL which will receive uploaded data.
• method: Here you will specify method to be used to upload data. It can take various
values but most frequently used are GET and POST.
The get method sends the data captured by form elements to the web server
encoded into a URL, which points to a web server. The data is appended to the URL.
This method is used when the amount of data sent to the web server is small. This is the
default method used
The post method sends the data captured by form elements to the web server as a
separate bit stream of data. This method is used when the amount of data sent to the web
server is large.

• 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

HTML Forms - Text Input Controls:

There are actually three types of text input used on forms:

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:

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:

Following is the list of attributes for <input> tag.


• type: Indicates the type of input control you want to create. This element is also used to
create other form controls such as radio buttons and checkboxes.

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.

Password input controls:

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:

Multiple-Line Text Input Controls:

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

HTML Forms - Creating Button:

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

You can use an image to create a button. Here is the syntax:

<form action="[Link] method="get">


<input type="image" name="imagebutton" src="URL" />
</form>

Here src attribute specifies a location of the image on your webserver.

HTML Forms - Checkboxes Control:

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

<input type="submit" value="Hobby Selected" />


</form>
</body>
</html>

Output:

HTML Forms - Radio box Control:

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:

HTML Forms - Select box Control:

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.

Following is the list of important attributes of <option>:


• value: The value that is sent to the server if this option is selected.
• selected: Specifies that this option should be the initially selected value when the page
loads.
• label: An alternative way of labeling options.

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:

HTML Forms - File Select Boxes:

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

5 marks and more


1. Explain the structure of HTML program with an example
2. Explain the <body> tag with its attributes
3. How do you create headings in HMTL?
4. Explain <hr> tag with its attributes
5. How do you create lists in HTML?
6. How do you create a hyperlink on a web page in HTML? Explain
7. How can you insert images in HTML? Explain
8. Explain <table> tag with all the attributes.
9. Explain the <marquee> element in HTML
10. How do you work with frames in HTML? Explain
11. Explain the <font> tag with its attributes
12. How do you work with forms in HTML? Explain.

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.

2.2 Advantages of CSS:

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

2.3 Comments in CSS:

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*/

2.4 Types of CSS

CSS can be added to HTML in the following ways:


 Inline - using the style attribute in HTML elements
 Internal - using the <style> element in the <head> section
 External - using an external CSS file

Syntax:

The CSS element syntax is

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

• The declaration block contains one or more declarations separated by semicolons.


• Each declaration includes a property name and a value, separated by a colon.
• A CSS declaration always ends with a semicolon, and declaration groups are surrounded
by curly braces

2.4.1 Inline Style Sheet:

• 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:

2.4.2 Internal Style Sheet:


• An internal style sheet can be used if one single document has a unique style. \
• Internal styles are defined in the <head> section of an HTML page, by using the <style>
tag
• <style> tag comes under the head tag. It is a paired tag

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:

2.4.3 External Style Sheet

• 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;
}

<!—Save this as [Link]-->


<html>
<head>
<link rel="stylesheet" type="text/css" href="[Link]">
</head>
<body>
Hello Everybody!!
<hr>
<h2>I am Jahnavi</h2>
<h3> Welcome to web technology </h3>
</body>
</html>

<!--Save this as [Link]-->

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

3.2 Features of HTML5

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.

3.3 HTML 5 Syntax:

DocType Declaration

HTML 5 uses a simple syntax to specify DTD(Doc Type Declaration) as follows:

<!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">

3.3.1 HTML 5 Document Structure:

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

<p>One article can have multiple sections</p>


</section>
</article>
<aside>
<p>This is aside part of the web page</p>
</aside>
<footer>
Created by Panchajanyeswari </footer>
</body>
</html>

Output:

3.3.2 HTML 4 Doctype Declaration:

All major web browsers operate in the following modes:


• Quirks mode – Here, the browsers violate the web format specifications in order to avoid
breaking of HTML pages authored according to practices prevalent in 1990s
• Standards mode – Browsers that had specification obedient HTML rendering engines
built into them, tried their best to give specifications conforming HTML document the
correct treatment. HTML 5 calls it no quirks mode
• Almost Standard mode – Browsers like Firefox, Safari and Opera have this type of mode.
It implements vertical sizing of table cells. HTML 5 calls it limited quirks mode.

3.3.3 HTML is Open to Interpretation:

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

Web Page Sectioning Algorithm:

HTML 5 has two outlining models – implicit model and explicit model. The explicit
model is based on the use of section and article element.

Working of HTML 5 explicit model:

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.

The Section element


This element represents a generic chunk of content within a web page. It represents a
thematic grouping of web page content typically with a heading

The article element

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

The nav element:

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

The aside element:

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.

The section element:

This element is used for grouping related content within the body of the web page. This
element can be nested.

3.4 WAI-ARIA and HTML5:

WAI-ARIA stands for Web Accessibility Initiative’s – Accessible Rich Internet


Applications. It is independent of HTML5. It is essentially designed to make the web content and
internet delivered applications more accessible to people with disabilities. The ARIA
specification defines how information about the complex controls can be conveyed to browsers
and makes them usable to all. ARIA provides the following mechanisms –
• Defining roles which describe the various widgets
• Defining roles for describing the structure of a web page
• Properties to describe the various control states

3.4.1 Role Attribute:

The role attribute is similar to class or id attribute in HTML. It is used to describe or


annotate the elements purpose in the document. It contains a lot of role attribute values like –
• Banner – This attribute value is used to identify a web page region that holds the heading
or internal title of a page. The content placed within a banner is site-oriented. i.e. it could
include logo or main heading of web page. It normally spans full width of the page.
• Complementary – This attribute value can be used to identify a section of the web page
content that supports the main content. Such a block is semantically meaningful on its
own. E.g. It can be used to display time, weather or related articles
• Contentinfo – This attribute value is used to describe the meta information about the
content of the web page.
• Main – This attribute value is used to identify the main content of the web page. It marks
the start of the content that is directly related to the central topic of the web page.
• Navigation - This attribute value is used to identify the collection of web site navigation
links used for navigating through the web page or between the related web pages.
• Note – This attribute is used to identify web page content that is ancillary to the main
content contained in the web page.

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.

3.5 Drawing using <canvas> element:

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 c = [Link]("sample"); The variable c is loaded with the canvas object


with this statement.

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.

3.5.1 Drawing Rectangles:

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

3.5.2 Drawing lines:

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:

3.5.3 Drawing Arcs:

We can draw arcs using the following method on the canvas


arc(x,y,r,start,stop)
Here
• (x,y) correspond to centre coordinates of the circle
• r is the radius of the circle
• Start, stop indicate the beginning and ending of the arc

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:

3.5.4 Drawing Text:

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

3.6 Video on the Web:

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

3.7 Geo-location in HTML 5:

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

3.7.1 Geo-location API:

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

The position object’s property with repsect to coords are


- Latitude – specifies the latitude of the site visitor in the world
- Longitude - specifies the longitude of the site visitor in the world
- Altitude - specifies the altitude of the site visitor in the world
The timestamp property tells the date and time when the position was calculated
3.8 Building Forms in HTML5:

3.8.1 Placeholder text:

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>

3.8.2 Email Address:

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>

3.8.3 Web Addresses:

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>

3.8.5 Date Pickers:

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”>

3.8.6 Color Pickers:

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?

5 marks and more Questions


1. Explain the structure of HTML5 document.
2. Explain the various modes of operations of browsers.
3. Explain the features of HTML5
4. Explain the role attribute in HTML5
5. Explain sectioning concept in HTML5
6. Explain the concept of drawing rectangles in HTML5
7. Explain the concept of drawing lines in HTML5
8. Explain the concept of drawing text in HTML5
9. Write a HTML5 code to generate a circle on the canvas

Compiled By
Panchajanyeswari M Achar Page 63
Srinivas Institute of Management Studies V Semester BCA

10. Explain the <video> tag in HTML5


11. Explain the concept of geo-location on the web using HTML5
12. Explain the various form elements available in HTML5

CHAPTER 4
CSS3

4.1 CSS Properties:

The following are the most commonly used CSS properties.


• Border-radius – This property rounds the corners of an element with specified radius
value
• Text-shadow – This property adds shadow to hypertext, with the options for directions of
the shadow, amount of blur and color of the shadow
• Box-shadow – This property adds shadow to an element. This property adds multiple
background images to an element
• Opacity - This property defines how opaque an element is. A value 1 means completely
opaque and the value 0 means completely transparent
• RGBA – This is not a CSS property but a color model that is introduced in 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">

<div>Hello BCA Students</div>

</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>

<div> I like this color</div>

</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">

<h1>Hello from Jahnavi!!</h1>

<p><b>Note:</b> Internet Explorer 9 and earlier versions, does not support the text-
shadow property.</p>
</body>
</html>

Output:

4.2 Enriching Forms with CSS3:

We can change the appearance of the form input elements using CSS3. We can make
them look visually appealing.

4.2.1 CSS3 Gradients:

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>

<h3>Linear Gradient - Top to Bottom</h3>


<p>This linear gradient starts at the top. It starts red, transitioning to blue:</p>

<div id="grad1"></div>

<p><strong>Note:</strong> Internet Explorer 9 and earlier versions do not support


gradients.</p>

</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>

<h3>Radial Gradient - Evenly Spaced Color Stops</h3>


<div id="grad1"></div>

</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

4.2.2 CSS Animations:

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;
}

/* Chrome, Safari, Opera */


@-webkit-keyframes myfirst {
from {background: red;}
to {background: yellow;}
}

/* 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

<p><b>Note:</b> This example does not work in Internet Explorer 9

and earlier versions.</p>

<div></div>

</body>
</html>

Output:

4.3 CSS Transforms:


CSS3 transforms can move, scale, turn, spin, and stretch elements. A transformation is an
effect that lets an element change shape, size and position. You can transform your elements
using 2D or 3D transformation.

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>

<div>Hello!! BCA Students</div>

<div id="div2">I am Jahnavi</div>

</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 */

-webkit-transform: rotate(45deg); /* Chrome, Safari, Opera */

}
</style>
</head>
<body>

<div>Hello how are you </div>

</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>

<div id="div2">Hi Jahnavi</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 {

-webkit-transform: translate(50px,100px); /* Chrome, Safari, Opera */

}
</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

Short answer questions (2 marks)

1. What are HTML tags?


2. Explain the two types of HTML tags (Singular and Paired).
3. What are Attributes ? Give an example.
4. Difference between <BR> and <P> tag.
5. Explain any two attributes of <HR> tag.
6. Write the usage of <DIV> tag with style attribute.
7. Write the usage of <SPAN> tag with style attribute.
8. Write the necessary tag to display the following text:
a) Programming in [Link] is Not Fun
b) Prove that x2 + y2 = z2
c) Chemical formula for water is H 2 O .
9. What are Lists ? Name the different types of Lists.
10. What are the advantages of using Style Sheets?

Compiled By
Panchajanyeswari M Achar Page 77
Srinivas Institute of Management Studies V Semester BCA

11. Differentiate between Inline and embedded styles


12. Write any 2 advantages of HTML5 over HTML4.
13. Write any 2 new inline elements used in HTML5 with its purpose.
14. How do you declare DOC TYPE in HTML5 ? What is its purpose?
15. What is WAI – ARIA ? What is its purpose?
16. How do you create CANVAS in HTML5? Give an Example (<CANVAS> tag)
17. Differentiate between strokeRect() and fillRect() method.
18. Write the necessary tags used to draw a triangle with red color ,whose coordinate values are
{10,50}, {100,100}, {10,100} .
19. What do you mean by Transforming Message?
20. Given an image, write the necessary statements used to rotate the image to 45 degree ,when
the mouse is placed over the image.

Long answer questions


1. Explain the structure of HTML document.
2. Explain any Five text formatting tags.
Explain the following Tags with example.
a) <BODY> {attributes :BGCOLOR, BACKGROUND,TEXT , SCROLL, LINK, ALINK,
VLINK)
b) <FONT> {attributes :FACE , COLOR , WEIGHT , SIZE )
c)<MARQUEE >{attributes: align, behavior, direction, scrolldelay, loop, scrollamount}
d) <DIV>{ attributes: align , clear , style}
e) <IMG>{ attributes : Border , Width , Height , Alt , Src ,Align}
f) <A>{ attributes :Href , Target , Name , Style}
g) <OL>{ START , STYLE , TYPE , VALUE}
h) <UL>{ TYPE ,STYLE }
i) <LI>
h) <DL >{ DT , DL,DD }
3. How to insert an image into a web page? Explain its attributes.
4. What are Hyperlinks ? What are the two types ? { links to external document , links to
specific location within
the same document}
5. What are LISTS ?Explain the different types .
6. Explain with example , how tables are created in HTML?
<TABLE>{ align,Border , BackGround , Border color ,cell padding , cell spacing ,width ,height}
<TR>>{ align,Border , BackGround , Border color}
<TH>{ align,Border , BackGround , Border color ,COLSPAN , ROWSPAN }
<TD>{ align,Border , BackGround , Border color ,COLSPAN , ROWSPAN }
<CAPTION>
7. Explain how Frames are created with example.
<FRAMESET>{ ROWS , COLS , BORDER, BORDER COLOR}
<FRAME> {Src, name, Scrolling }
8. What are Forms ? Explain the following Controls(input types) used in forms:
<TEXT>{ Size, Value , Name, ReadOnly , MaxLength ,disabled}
<TEXTAREA> { Cols , Rows , Size, Value , Name, ReadOnly , MaxLength,disabled}
Compiled By
Panchajanyeswari M Achar Page 78
Srinivas Institute of Management Studies V Semester BCA

<PASSWORD>{ Size, Value , Name, ReadOnly , MaxLength,disabled}


<SUBMIT>{ Size, Value , Name ,disabled}
<RESET>{ Size, Value , Name, disabled}
<BUTTON>{ Size, Value , Name, disabled}
<CHECKBOX>{Size, Value , Name, disabled}
<RADIO>{Size, Value , Name, disabled}
<SELECT>{Size, Name, Mulitple,disabled}
<OPTION>{ disabled , selected, value}
9. What are Style Sheets ? Explain the different types of Style Sheets?
10. List and specify the various structural elements used in HTML5
11. Explain the different sections used in HTML5 .
12. Explain the various Role attributes used to achieve WAI-ARIA.
13. Explain with example
i) Drawing Rectangle ii)Drawing line Art iii) filling LineArt
iv) Drawing arcs v) Drawing Texts vi) Drawing Bezier Curve
v) Drawing Quadratic curves.
14. Write a note on
i) Video on Web . II. Geo Location API III. Working-Off line
15. Explain the various input types used to design a form in HTML5 (place holder,
autofocus,email,
url , type=number , type=range ,type=datetime , type=time , type=color )
16. Explain the various CSS3 properties (text-shadow, box-shadow, border-radius, opacity,
RGBA}
17. Explain with an example ,how transforming a image is done in HTML5? (Consider HTML
unordered list to display 3 images , apply Scaling , Rotate , Skew and Translate)

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.

5.2 Differences between ASP and [Link]

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

5.3 Similarities between ASP and [Link]

 Products of Microsoft Corporation


 Used for developing dynamic websites
 Treated as server-side scripting
 HTML tags can be included directly
 Use javascript as client-side scripting

5.4 Characteristics of [Link]

• 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

5.5 Architecture of [Link]:

Web clients

Compiled By
Panchajanyeswari M Achar
[Link] Page 80
applications IIS

.NET
Framework
Srinivas Institute of Management Studies V Semester BCA

• All web clients communicate with [Link] applications through IIS(Internet


Information Services)
• IIS deciphers and optionally authenticates the request.
• If allow Anonymous option is turned on, no authentication takes place
• IIS finds the requested resource and if the client is authorized, returns the appropriate
resource
• An [Link] application can also use the low-level security features of the .NET
framework

5.6 [Link] Web Form Pages:

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

5.6.1 Advantages of web form pages:

• 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

5.7 Server Controls:

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)

5.8 HTML Server Controls:

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

5.9 Web Form Controls:

These are special [Link] tags that are understood by the server. These are also created
by the server and require runat=“server” attribute.

Syntax to create web form control


<asp:control_name id=“name” runat=“server”/>

E.g. Button, Checkbox, List box, radio button

5.10 Types of Web Controls

Compiled By
Panchajanyeswari M Achar Page 82
Srinivas Institute of Management Studies V Semester BCA

There are four types of web controls. They are


• Web server controls
• Validation web controls
• Data controls
• Rich web controls

5.10.1 Web server Controls

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

<asp:control_name id=“name” runat=“server”/>

E.g. Button, Checkbox, List box, radio button

5.10.2 Validation Web Controls

These are used for form validation. They do not correspond to any HTML tag. They
include
• RequiresFieldValidator
• CompareValidator
• RangeValidator
• RegularExpressionValidator
• CustomValidator
• ValidationSummary

5.10.3 Data Controls

These controls are used to display data from a data source such as a table. They include
• DataGrid
• DataList
• DataRepeater

5.10.4 Rich Web Controls

These are customized controls that provide high-level functionality


• Calender
• AdRotator

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 public properties of WebControl class are:

AccessKey, Attributes, BackColor, BorderColor, BorderStyle, BorderWidth, CssClass, Enabled,


Font, EnableTheming, ForeColor, Height, IsEnabled, SkinID, Style, TabIndex, ToolTip, Width

6.2 TextBox Control:

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

6.3 Button Control

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

6.4 Label Control

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

Text The text to display in the label

6.5 Image Control

The Image control is used to display an [Link] exists within


[Link] namespace.

Property Description

AlternateText An alternate text for the image

DescriptionUrl The location to a detailed description for the image

GenerateEmptyAlternateText Specifies whether or not the control creates an empty


string as an alternate text
ImageAlign Specifies the alignment of the image

ImageUrl The URL of the image to display for the link

6.6 ImageButton Control

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

CausesValidation Specifies if a page is validated when an ImageButton


control is clicked
CommandArgument Additional information about the command to perform

CommandName The command associated with the Command event


GenerateEmptyAlternateText Specifies whether or not the control creates an empty
string as an alternate text
OnClientClick The name of the function to be executed when the

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

BorderColor Sets a border color to the dropdown list


BorderStyle Sets border style to the dropdown list
BorderWidth Sets border style to the dropdown list

6.8 CheckBox Control

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

6.9 CheckBoxList Control

The CheckBoxList control is used to create a number of check boxes simultaneously.


Each selectable item in a CheckBoxList control is defined by a ListItem element. This control is
useful when we need to bind the data from data source to check box.

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

6.10 RadioButton Control

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

6.11 RadioButtonList Control

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

6.12 Panel Control

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

6.13 AdRotator Control

[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

6.14 Calender Control

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

ShowTitle A Boolean value that specifies whether the title of the


calendar should be shown
TitleFormat The format for the title of the calendar
TitleStyle The style of the title of the calendar
TodayDayStyle The style for today's date
TodaysDate Today's date
UseAccessibleHeader Specifying whether to use the <th> element for the day
headers instead of the <td> element
VisibleDate The date that specifies the month that is currently visible in
the calendar
WeekendDayStyle The style for weekends
OnDayRender The name of the function to be executed when when each
day cell is created
OnSelectionChanged The name of the function to be executed when the user
selects a day, week, or month
OnVisibleMonthChanged The name of the function to be executed when the user
navigates to a different month

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

7.2 The BaseValidator Class:

The [Link] class is the base class for all the


validation controls. It provides the basic implementation needed for all the controls. The
inheritance hierarchy for [Link] class is as follows:

[Link]
[Link]
[Link]
[Link]
[Link]

Properties of BaseValidator Class

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

IsValid A Boolean value that indicates whether the control specified by


ControlToValidate is determined to be valid
Text The message to display when validation fails

7.3 The RequiredFieldValidator Control:

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:

7.4 The RangeValidator Control

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:

• ControlToValidate – Contains the input control to validate


• Minimum Value – Holds the minimum value of the valid range
• Maximum Value – Holds the maximum value of the valid range

Property Description

Compiled By
Panchajanyeswari M Achar Page 94
Srinivas Institute of Management Studies V Semester BCA

MaximumValue Specifies the maximum value of the input control


MinimumValue Specifies the minimum value of the input control

Output:

7.5 The RegularExpressionValidator Control

The RegularExpressionValidator control is used to ensure that an input value matches a


specified pattern. It checks whether the text in the input control matches the format specified by
the regular expressions like email-id, date format. This control exists within the
[Link] namespace
Property Description
ValidationExpression Specifies the expression used to validate input control. The expression
validation syntax is different on the client than on the server. JScript is
used on the client. On the server, the language you have specified is
used

Output:

7.6 The CompareValidator Control

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:

7.7 The CustomValidator Control

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

ValidateEmptyText Sets a boolen value indicating whether empty text should be


validated or not

Output:

7.8 The ValidationSummary Control

The ValidationSummary control is used to display a summary of all validation errors


occurred in a Web page at one place. The error message displayed in this control is specified by
the ErrorMessage property of each validation control. If the ErrorMessage property of the
validation control is not set, no error message is displayed for that validation [Link] control
exists within the [Link] namespace.

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

A database is a collection of records or information that is used to store in a computer in a


systematic way. SQL is used to work with the database in order to store, retrieve and manipulate
data in it. The ActiveX Data Object technology of the .NET framework is dedicated to facilitate
working with the database. The [Link] data access technology equips .NET application with
capability of robust data integration. There are two types of data access:
 Connected Data Access – This model is the only way to access data from the database
earlier in the web application. Here, we have to manage the open connection with the
database. It requires continuous open connection with the data base to fetch data. The
various database operations can be performed only when there is an open connection with
the database. After performing the operations we have to close the connection explicitly.
But in web applications, multiple web users are hosted simultaneously. Hence
maintaining a connected data access consumes all the resources thereby, reducing the
efficiency and system performance.
 Disconnected Data Access – [Link] is an example of this model. Here, the .NET
development environment define a methodology to create a copy of the database objects
like tables, views, relations and data types in the local memory of the [Link]
application. The application works on the copy of data stored in the local memory of the
application. The application works in the detached mode with the database. The actual
connection to the database is made only when the final read, write or update operation is
performed on the database. This is the strongest feature of the .NET framework
The .NET framework creates a data layer called the [Link] data layer, which
contains all the physical data storage services. Various operations performed on the
database by the services of this layer are
• Connecting to database or XML file
• Querying the database by using SQL e.g. retrieving salaries of employees
• Making changes to the database tables e.g. increasing the salary of employees
• Inserting new data or deleting existing data e.g. adding record of new employee or
deleting a retired employee

8.2 [Link] Objects:

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

available data adapters are OledbAdapter, OdbcAdapter, OracleDataAdapter,


AccessDataAdapter and SQLDataAdapter
• Command Object – Requires reading, adding, updating and deleting records in a data
source. For each of these operations, the data adapter contains a command object. Data
adapters support four types of command objects: SelectCommand, InserttCommand,
UpdateCommand and DeletetCommand.
• DataSet Object – Stores data in a disconnected cache. The structure is similar to that of
relational databases. It represents a complete set of data including related tables,
constraints and relationships. Datasets are supported with DataSet objetcs
• DataTable Object – Used to store a data table from a dataset. DataTable object contains
two important properties, namely Columns and Rows. The Columns property is a
collection of DataColumn objects that represent the columns of data in a table. The Rows
property is a collection of DataRow objects that represent the rows of data in a table.
• DataReader Object – Holds a read-only or forward only set of data from a database. The
use of this object can increase the speed with which data is retrieved from the database,
as only one row will remain in the memory at a time.
• DataView Object – Represents a customized view of a single table that can be filtered,
searched or sorted. A dataview supported by the DataView class is a data snapshot that
takes up few resources
• Constraint Object – Checks data integrity. A constraint supported by the Constraint class
is a rule that can be used when rows are inserted, updated or deleted to check the affected
table after performing the operation.
• DataRelation Object – Specifies a relation between the parent and the child tables based
on a key that is shared by both the tables
• DataRow Object – Corresponds to a particular row in a data table. We can use the item
property to get or set a value in a particular field in a row
• DataColumn Object – Represents the columns in a table. Each object has a DataType
property that specifies a kind of data each column contains such as integers or string
values

8.3 The SQLDataSource Control

The SQLDataSource Control is used to establish a connection with a database such as


SQL Server. This data source control loads the provider for SQL server. The wizard launched by
the control helps the users to do the following:

Compiled By
Panchajanyeswari M Achar Page 100
Srinivas Institute of Management Studies V Semester BCA

• Creating provider specific connection with the SQL server


• Building SQL query or use stored procedures
• Fetching data from SQL server database

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

8.4 The Object DataSource Control

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

Public Properties of the control


Properties Description
EnableCaching Enables the caching of ObjectDataSource
control in the application
InsertParameters Obtains a collection of parameters that will be
used in the InsertMethod property
SelectParameters Obtains a collection of parameters that will be
used in the SelectMethod property

Public methods of the control


Methods Description
Databind Allows you to bind the data source to
ObjectDataSource control
Select Allows the user to retrieve the records from the
object to which the ObjectDataSource control

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

8.5 The XMLDataSource Control

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.

Public Properties of the control


Property Description
Data Gets or sets a block of XML data that the data
source control binds to.
TransformFile Specifies the Stylesheet transformation for the
referenced XML file
XPath Defines the XPath expression for XML file

Public methods of the control


Method Description
DataBind Binds the datasource to the XmlDataSource
control
GetXmlDocument Retrieves the specified XML document to be
loaded as data source
ToString Returns a string representation of the object

8.6 The LinqDataSource 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

Public Properties of the control

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.

Public methods of the control

Method Description
Delete Deletes data from database
Insert Inserts data into database
Update Updates data into database

8.7 The AccessDataSource Control:

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

8.8 Data bound Controls:

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.

8.8.1 The DataList 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.

8.8.2 The FormView Control

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

8.8.3 The DetailsView 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.

8.8.4 The ListView and DataPager Controls

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

5 marks and more


1. Explain the [Link] Objects available in [Link]
2. Explain SQLDataSource Control available in [Link]
3. Explain Object DataSource Control available in [Link]
4. Explain XMLDataSource Control available in [Link]
5. Explain LinqDataSource Control available in [Link]
6. Explain AccessDataSource Control available in [Link]
7. Explain the Data bound Controls available in [Link]

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

9.2 Differences between XML and HTML


XML HTML
Describes the data Displays the data
Tags are not pre-defined Tags are pre-defined
Case sensitive Not case sensitive
Displays error message if there is error in the Doesn’t display error message if there is error
code in the code
XML designed to transport and store data HTML designed only to display data
Uses XML parser to execute the program No additional software required to run the
program

9.3 Structuring Data in XML:

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.

9.4 XML is used to create new internet Languages:

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

9.5 XML Documents form a Tree Structure

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>

9.6 XML with DTD

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

9.7 Building Blocks of XML document:

Compiled By
Panchajanyeswari M Achar Page 107
Srinivas Institute of Management Studies V Semester BCA

All XML documents are made up of the following building blocks:


 Elements
 Attributes
 Entities
 PCDATA
 CDATA

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

Attributes provide extra information about elements. They provide characteristics of an


element. Attributes are always placed inside the opening tag of an element. Attributes always
come in name/value pairs.

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: "&nbsp;". 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.

The following entities are predefined in XML:


Entity References Character
&lt; <
&gt; >
&amp; &

Compiled By
Panchajanyeswari M Achar Page 108
Srinivas Institute of Management Studies V Semester BCA

&quot; "
&apos; '

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 &amp; &lt; and &gt;
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

5 marks and more


1. List the differences between XML and HTML
2. What is DTD? Explain the various types
3. Explain the building blocks of XML document.

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 ?

Long answer questions


1. Write the different characteristics of [Link].
2. Explain the architecture of [Link].
3. Explain HTML Server controls with example.
4. Explain [Link] – Web server Controls.
5. Write the purpose of the following controls with example:
a) TEXTBOX {CausesValidation, MaxLength, ReadOnly, Rows, Cols, Runat, Text,
TextMode, OnTextChanged}
b) BUTTONS {CausesValidation, CommandArgument, CommandName, OnClientClick, Text }
c) LABEL { AssociatedControlId , Text}
d) DropDownList { BorderColor, BorderStyle,BorderWidth,SelectedIndex}
e) CheckBox { CausesValidation, Checked, Text, TextAlign , CheckedChanged(event }
f) CheckBoxList { CellPadding , CellSpacing , RepeatColumns, RepeatDirection ,
RepeatLayout}
g) RadioButton {GroupName}
h)RadioButtonList { CellPadding , CellSpacing , RepeatColumns, RepeatDirection ,
RepeatLayout}
i) Panel { BackImageUrl , Direction , GroupingText, HorizontalAlign , ScrollBars }
j) .AdRotator {AdvertisementFile, AlternateTextField, ImageUrlField, NavigatorUrlField,
Target}

Compiled By
Panchajanyeswari M Achar Page 110
Srinivas Institute of Management Studies V Semester BCA

k) Calendar { DayHeaderStyle, DayStyle, SelectedDayStyle,TitleStyle, TodayDayStyle,


WeekendDayStyle,showNextPrevMonth ,ShowTitle}
6. Explain the following validators with example.
a) RequiredFieldValidator
b) RangeValidator
c) RegularExpressionValidator
d) CompareValidator
e) CustomValidator
f) ValidationSummary
7. Explain the various [Link] Objects.
8. Explain the following Controls. (purpose, attributes, methods used)
a) SqlDataSource b) ObjectDataSource c) XmlDataSource d) AccessDataSource
e)FormView
9. Explain Integration of CSS with XML with example.
10. What is DTD ? Explain the different types (internal and external DTD).
11. Explain the building blocks of XML documents.

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

applications running on different platforms. These applications can exchange data by


using Web services.
 Easy Integration: Using Web services, you can easily integrate business applications
developed on different software and hardware platforms resulting in low setup costs. In
addition, you can integrate Web applications with applications such as spreadsheets or
back-end database to provide online information.

A Web service has the following elements:


 XML: XML is used to exchange data over the Internet. To enable data interchange, you
require a standard data representation format that can be understood by any platform.
Because XML is a plain-text format that can be understood by any type of hardware
device over the Web, it is able to fulfill this requirement.
 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 the client application to a
web method and the data returned by the Web method to be 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 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 parameter are extracted
from the SOAP packet and the appropriate Web method is invoked.
 Web Services Description Language (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. For this reason, you need a standard
method to describe the methods that are called by a Web service. This information should
be readily accessible to the Web service clients during the design phase. WSDL is a
markup language that describes a Web service.
 Universal Description, Discovery and Integration (UDDI): It provides a standard
mechanism to register and discover a Web service. When a Web 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, which contains pointers to the Web service and the WSDL document for the
Web service.

10.2 Managing States of an [Link] Application

Compiled By
Panchajanyeswari M Achar Page 113
Srinivas Institute of Management Studies V Semester BCA

State is quite an innovative concept in Web development. It is an innovative concept


because it eliminates the drawback of losing state data on page-reload. By using states with your
Web application, you can preserve the state of a Web application both at the server or client end,
whenever the application or controls make a round-trip to the server. The state of a Web
application actually stores the changes that have been made to the Web application. If you are
not using states then these changes get discarded. As of now, you might be thinking that the
whole concept of storing states is optional. But under certain circumstances, it becomes quite
imperative to use states with your applications. For instance, it is necessary to store states for
Web applications, such as an e-commerce shopping site or an internet site of a company to keep
track of the user requests, such as the items chosen by the user on a shopping site or the days
requested for the vacation on the internet site.
An application can have three types of states: application, session and view. Before going
into detail about these three types of application states, let us have a look at the various means of
storing state information:

 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

10.2.1 The Application-State

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.

10.2.2 The Session-State

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.

10.2.3 The View-State

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.

10.3 Enabling Technologies Used in Web Services

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

To cater to these requirements, various standards such as eXtensible Markup


Language(XML) . Simple Object Access Protocol(SOAP), and Web Services Description
Language(WSDL) are used for developing and accessing Web services. In addition, the
Universal Description Discovery and Integration(UDDI) initiative is used to allow client
applications to discover the Web services provided by various Web service providers. Let us
look at each of these enabling technologies in detail.

10.3.1 XML

A client application passes arguments to a method exposed by a Web services. The


method performs some action on the arguments and returns the results to the client application.
The data returned by the Web service can be used by the client application, regardless of the
hardware and software platform used to develop the application. To enable this kind of data
interchange, you require a standard data representation format that can be understood by any
platform. Since XML is a plain-text format that can be understood by any kind of device, it
caters to this requirement.

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

Locates a Web service

Client Web
Application Services

Communication through SOAP


messages
CHAPTER 11
Assignment
2 marks Questions
1. Define SOAP
2. Define UDDI
3. Define WSDL
4. List any two benefits of web services
5. List the elements of web services
6. List the states in [Link] application
5 marks Questions
Compiled By
Panchajanyeswari M Achar Page 118
Srinivas Institute of Management Studies V Semester BCA

1. Explain the benefits of web services


2. Explain the elements of web services
3. Explain the various states in [Link] application
4. Write short notes on SOAP
5. Write short notes on UDDI
6. Write short notes on WSDL
CHAPTER 11
INTRODUCTION TO DEPLOYMENT

11.1 Introduction:

There are four phases in the development of an application:


 Designing
 Implementing
 Testing
 Deployment

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.

11.2 Types of Deployment Projects

Deployment projects are the implementation of deployment techniques. It is always better


to use deployment projects in visual [Link] if you are deploying a complex web application
on the destination server. This is because deployment projects help you to specify the
components for deployment, such as, indicating what files are to be included, stating the method
suggesting how the components should be deployed, and stating the destination indicating where
they should be located.

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

Public Properties of [Link] class


Property Description

Count Obtains the number of items stored in the cache


EffectivePrivateBytesLimit Obtains the number of kilobytes available for
the cache
Item Obtains the cache item at the specified key

Public Methods of [Link] class


Property Description

Add Adds a specified item to the cache object

Compiled By
Panchajanyeswari M Achar Page 121
Srinivas Institute of Management Studies V Semester BCA

Get Retrieves the specified item from the cache


object
GetEnumerator Retrieves a directory enumerator to iterate
through the key settings and their values
contained in the cache
Insert Inserts an item into the Cache object
Remove Removes the specified item from the Cache
object

11.3.1 Caching Techniques


[Link] 2.0 provides three types of caching techniques:
 Output Caching (also called Page Level Caching)
 Partial-Page Output Caching
 Data Caching

[Link] Output Caching

Output caching or Page Level caching is the simplest technique of caching in


[Link]. In output caching, if a Web page is requested by the client machine for the first time,
it is accessed from the Web Server and sent to the client machine; also a copy of the Web page is
stored in the cache. Now if the same Web page is requested further, the Web page is not accessed
from the server instead the copy of the Web page which is stored on the cache is sent to the client
machine. If a copy of the Web page is not found in the cache, the Web page is accessed from the
server and sent to the client machine; also a copy of the Web page is stored in the cache for later
use.
Output caching is also very useful when you have static pages. For example, in cases
where the content of the published article on your website does not change, using Output caching
will be very effective. This is because the engine will cache everything that is rendered (or
displayed) on the Web page. For subsequent requests, it will send a copy of the Web page which
is stored in the cache to the client machine and thus it reduces the load on the Web server
because the processor does not get busy in rendering the page every time a request comes in.

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

<%@ OutputCache Duration=“90” Location =“Any | Client |” -


+“Downstream | Server None” VaryByParam=“none” %>

The @ OutputCache directive has few more attributes. All the attributes supported by
@ OutputCache directive are given in Table As-10.3.

Table AS-10.3: Attributes Supported by @ OutputCache Directive


Attribute Description
CacheProfile The CacheProfile attribute contains the name of
the cache settings to associate with the page;
this is an optional attribute and by default
contains an empty string

Attributes Supported by @Output Cache Directive


Attribute Description
Duration(required) The Duration attribute is used to define the time
duration in seconds for the web page or the User
control that is being cached.
Location The Location attribute is used to define the
location where cache is created; The possible
values are.
 Any
 Client
 Downstream
 Server
 None
NoStore The NoStore attribute contains a Boolean value
that determines whether to prevent secondary
storage of important information.
Shared The Shared attribute is used to set the Boolean
value to allow sharing of the cached control with
multiple pages.
SqlDependency The SqlDependency attribute contains a string
value that identifies a set of database and table
name pairs on which the Output cache of page
depends.
VaryByControl The VaryByControl attribute is used with the
User controls; this attributes contains a
Compiled By
Panchajanyeswari M Achar Page 123
Srinivas Institute of Management Studies V Semester BCA

semicolon-separated list of string used to vary the


Output cache; these strings represent ID of
property value of [Link] Server controls on a
User control; if you are working with the User
controls, this attribute is necessary unless you are
using the VaryByParam attribute(this attributes is
not supported for [Link] web pages).
VaryByCustom The VaryByCustom attributes is used to define
the custom strings for custom caching
requirements.
VaryByHeader The VaryByHeader attributes is used to define
semicolon-separated list of HTTP headers used
to vary the Output cache.
VaryByParam(Required) The VaryByParam attribute is used to define a
Semicolon-separated list of strings used to vary
the Output cache.

[Link] Partial-Page Output Caching


It is not always that you require caching the complete page. Sometimes you need to
implement caching on only some of the contents of a Web page. Other contents of the Web page
will be refreshed each time the page is requested. This is called partial caching or fragment
caching. The steps to apply the partial caching are as follows:

 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:

<%@ OutputCache Duration=”500” VaryByParam=”None” %>

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.

[Link] Data Caching

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.

11.4.1 Creating Thread:

A thread is created by creating a Thread object, giving its constructor a ThreadStart


reference.
ThreadStart childthread = new ThreadStart(childthreadcall);

11.4.2 Thread States


A thread can have one of the following states:
• Ready or Run-able state—A thread in this state has all resources it needs, excluding the
processor. It awaits its turn in the ready queue (a queue of ready-to-use threads) to be
allocated the processor.
• Running state—A thread in this state has all resources it needs, inclusive of the processor.
Hence, a thread in this state is said to be in the running or executing state. Note that in a
single processor, you can at any point in time have only one thread in the running state.
• Wait state—A thread in this state waits for the IO to be complete. Once the IO activity
for the thread is complete, the thread is scheduled again to the ready queue.

The ThreadState enum in the [Link] namespace in C# contains the various


supported thread states in .NET. The following are the members of the ThreadState enum:

• 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

11.4.3 Using the [Link] Class

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:

Thread thread = new Thread(new ThreadStart(DoWork));


<br>[Link]();

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.

Here’s what a typical thread method looks like:


public void DoWork()<br>\\{<br> while(some condition)<br> \\{<br>
//Some code<br> \\}<br>\\}

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.

11.4.4 Suspending and Resuming Threads

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:

if ([Link] [Link] ) <br>\\{ <br>


[Link](); <br>\\}<br>

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]);

11.4.5 Joining Threads

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>

11.4.6 Terminating Threads

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:

if ([Link]) <br>\\{ <br> [Link](); <br>\\}

11.4.7 The Thread Priority:

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];

11.4.7 Thread Properties & Methods:

The important methods of Thread class are:

Property Description

CurrentContext Gets the current context in which the thread is executing.

CurrentCulture Gets or sets the culture for the current thread.

CurrentPrinciple Gets or sets the thread’s current principal(for role-based security).

CurrentThread Gets the currently running thread.

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

IsBackground Gets or sets a value indicating whether or not a thread is a background


thread
IsThreadPoolThread Gets a value indicating whether or not a thread belongs to the managed
thread pool
ManagedThreadID Gets a unique identifier for the current managed thread

Name Gets or sets the value of the thread

Priority Gets or sets a value indicating the scheduling priority of a thread

ThreadState Gets a value containing the states of the current thread

Compiled By
Panchajanyeswari M Achar Page 129
Srinivas Institute of Management Studies V Semester BCA

The important methods of Thread class are:

Methods Description

Abort Raises a ThreadAbortException in the thread on which it is invoked,


to begin the process of terminating the thread. Caliing this method
usually terminates the thread.
AllocateDataSlot Allocates an unnamed data slot on all the threads. For better
performance, use fields that are marked with the ThreadStaticAttribute
attribute instead.
AllocateNamedDataSlot Allocates a named data slot on all threads. For better performance, use
fields that are marked with the ThreadStaticAttribute attribute instead.
BeginCriticalRegion Notifies a host that execution is about to enter a region of code in
which the effects of a thread abort or unhandled exception might
jeopardize other tasks in the application domain
BeginThreadAffinity Notifies a host that managed code is about to execute instructions that
depend on the identity of the current physical operating system thread
EndCriticalRegion Notifies a host that execution is about to enter a region of code in
which the effects of a thread abort or unhandled exception are limited
to the current task.
EndThreadAffintiy 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
ThreadStaticAttrinbute attribute machine instead.
AllocateNamedDataSlot Allocates a named data slot on all threads. For better performance, use
fields that are marked with the ThreadStaticAttribute attribute instead.
BeginCriticalRegion Notifies a host that execution is about to enter a region of code in
which the effects of a thread abort or unhandled exception might
jeopardize other tasks in the application domain.
BeginThreadAffinity Notifies a host that managed code is about to execute instructions that
depend on the identity of the current physical operating system thread.
EndCriticalRegion Notifies a host that execution is about to enter a region of code in
which the effects of a thread abort or unhandled exception are limited
to the current task.

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.

GetDomainID Returns a unique application domain identifier

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

Sleep Makes the thread pause for a period of time.

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

processors or the state of processor cache. This method has different


overload forms.
VolatileWrite() Writes a value to a field immediately, so that the value is visible to all
processors in the computer. This method has different overloaded
forms.
Yield Causes the calling thread to yield execution to another thread that is
ready to run on the current processor. The operating system selects the
thread to yield to.

11.4.8 Thread Synchronization

The following summarise the .NET tools available for coordinating or synchronizing the
action of threads:

[Link] Simple Blocking Methods


• Sleep - Block for a given time period.
• Join - wait for another thread to finish.

[Link] Locking Constructs

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

[Link] Signaling Constructs

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

[Link] Non-Blocking Synchronization Constructs

• Interlocked-To perform simple non-blocking atomic operations.


• Volatile-To allow safe non - blocking access to individual fields of a lock.

11.5 Securing [Link] Web Applications

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.

[Link] addresses the security needs of web applications using:


• Microsoft .NET Framework security
• Internet Information Service (IIS)

11.6 Microsoft .NET Framework Security

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

11.6.1 Security policy in the .NET Framework

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.

11.6.2 Configuring an [Link] Application for Security

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

common tags used to configure security are:


• <Authentication>
• <Authorization>
• <Impersonation>

11.7 Configuring an [Link] Web Application for Authentication

The <authentication> section specifies the method used by an application to authenticate a


user requesting access to a restricted resource. The mode attribute of the <authentication> tag
is used to specify the authentication type to be used. Various options of the mode attribute
are:-
 Windows: This mode specifies that the user will be authenticated using any form of IIS
authentication. The IIS authentication includes basic, digest, integrated windows, and
certificates.
 Forms: This mode specifies that the user will be authenticated using form-based
authentication method.
 Passport: This mode specifies that the user will be authenticated using Microsoft Passport
authentication method. Passport authentication relies on cookie based authentication and
single signing authentication service provided by Microsoft.
 None: This mode specifies that no authentication mechanism is set and that any anonymous
user can access the web application.

11.7.1 Implementing Windows Authentication

To configure an [Link] web application for windows authentication, you need to


change the mode attribute of the <authentication> element to Windows as illustrated in the
following syntax:
<authentication mode =”Windows”/>
Windows authentication relies on the fact that the user is a valid user on the server under
Windows. When the user-base is very large, the implementation of windows authentication
becomes very complicated. Windows authentication is very secure but makes the design very
inflexible. This has an adverse effect on the scalability of a web application. For example, the
privileges defined for all the users should fall in line with the definition of windows set of
permission which restricts the design to a small group of users, such as administrator and power
users.

11.7.2 Implementing Forms Authentication

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 forms element has the following four attributes:


 Name: This specifies the HTTP cookie that will be used for authentication.
.ASPXFORMSAUTH is the default value of the name attribute.
 LoginUrl: This specifies the URL to which the user request is redirected for logon when
no valid authentication cookie is found. The default value is [Link].
 Protection: This specifies the type of protection that a Web application uses to protect the
cookie. The valid values of this attribute are A11, None, Encryption, and Validation. The
default value of this attribute is A11.
 Timeout: This specifies the life span of cookie after which the cookie used for
authentication expires. The value is specified in minutes.
 Path: This specifies the path of cookie.

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.

11.7.2 The FormsAuthentication Class


The FormsAuthentication class is defined in the [Link] namespace and is
used to implement form authentication when the configuration file is used to store user
credentials.
The following table lists some of the commonly used methods of the FormsAuthentication
class:
Methods Description
Authenticate The Authenticate() method validates the user
Credentials passed to it and returns a
boolean value indicating whether the
authentication process was successful or not.
RedirectFromLoginPage The RedirectFromLoginPage() method
redirects an authenticated user back to the
specified URL.
SignOut The SignOut() method removes the
authentication cookies created on the
machine of an authenticated user.

11.8 Overview of Authorization

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.

11.8.1 Configuring an [Link] Web Application for Authorization

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.

Attributes of <allow> and <deny> are:


 user: This attribute enables you to assign a list of users to be granted or denied access.
The symbol ”?” is used to denote anonymous and the symbol “*” denotes all users.
 roles: This attribute enables you to assign a list of roles to be granted or denied access.
 verbs: This attribute enables you to specify a list action that should be either allowed or
denied from being performed .Possible values that verbs can have are GET, HEAD,
POST, DEBUG. While assigning more than one value to the verbs attribute, each value
should be separated by a comma.
For example, to permit access permission only to users with the accounts
mydomain\Johns and mydomain\Anna and roles Admins, you can specify the code for
the <authorisation>element as illustrated in the following example:
<authorization>
<allow users=”mydomain\Johns, mydomain\Anna” roles=”Admins”>
<deny users=”*”/>
</authorization>

11.8.2 Configuring an [Link] Web Application for Impersonation

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

3. If authorized to access resources, the [Link] application returns the requested


resources to the client through IIS.

Impersonation is used to avoid authentication and authorization issues in the application


code. By default, impersonation is disabled in [Link] and unless overridden, all applications
inherit this setting. When impersonation is not enabled, the account used for executing [Link]
resources is controlled by the <processModel> element in the [Link] file. However, you
can enable impersonation in an [Link] application by adding the following line of code in the
[Link] file:
<identity impersonate=”true” name=”domain1\student” password=”password”>

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

C# (pronounced as C sharp) is a new programming language developed by Microsoft as a


part of their .NET strategy to provide web-based services. It is a fully object-oriented language
like Java and is the first component oriented language. The major highlights of the language are
 It is derived from C/C++ family
 It is the only component-oriented language
 It is designed for .NET framework
 It combines the best features of commonly used languages : productivity of Visual Basic,
the power of C++ and elegance of Java
 Major parts of .NET are coded in C#

12.2 Simple C# Program

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”);
}
}

12.2.1 Class Declaration

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.

12.2.2 The Braces

C# is a block structured language i.e. code blocks are always enclosed within { and }.
Every class definition is enclosed in braces.

12.2.3 The Main Method

The third line


public static void Main()
defines a method named Main. Every C# executable program must include the Main method in
one of the classes. A C# application can have any number of classes but only one class can have
Main method to initiate the execution.
The meanings of the keywords that appear in the statement are
 public – It is an access modifier that tells C# compiler that the main method is accessible
to everyone
 static – It declares that Main method is global and it can be called without creating an
instance of the class. The compiler stores the address of the method as the entry point and
uses this information to begin execution before any objects are created
 void – The keyword void is a type modifier that the main method does not return any
value

12.2.4 The Output Line:

The only executable statement in C# is


[Link](“Hello from Jahnavi”);
C# is an object oriented language. Hence every method should be a part of an object. The
WriteLine method is a static method of Console class, which is located in the namespace System.
This line prints the string
Compiled By
Panchajanyeswari M Achar Page 142
Srinivas Institute of Management Studies V Semester BCA

Hello from Jahnavi


to the screen. The WriteLine method always appends a new-line character to the end of the
string. Every C# statement should end with a semi-colon.

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 */

12.5 Using Aliases for Namespaces

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”);
}
}

12.6 Passing strings as objects to WriteLine Method:

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”;

The content of s can be printed using the WriteLine method.

[Link](s);

Example:
using System;
Class Sample2
{
public static void Main()
{
string name = “Hello Jahnavi”;
[Link](name);
}
}

12.7 Structure of C# Program

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

3. How can you use alias for namespaces?


5marks Questions

1. Explain the structure of C# program with an example

CHAPTER 13
LITERALS, VARIABLES, DATA TYPES

13.1 Introduction:

A C# program is basically a collection of classes. A class is defined by a set of


declaration statements and methods containing instructions called a s executable statements.
These instructions are formed using certain symbols and words according to rigid rules known
as syntax rules. The smallest, non-reducible element in a program is called as a token. C#
program is a collection of tokens, comments and whitespaces. The five types of tokens in C# are
• Keywords
• Identifiers
• Literals
• Operators
• Punctuators

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

Numeric Literals Character Literals


constants

Integer Literals Real Literals Single Character String Literals


Literals

13.2.1 Integer 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

78 /* Illegal: 8 is not an octal digit */

13.2.2 Real Literals:


A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent
part. You can represent floating point literals either in decimal form or exponential form.
Here are some examples of floating-point literals:

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.

13.2.3 Boolean Literals

There are two Boolean literals in C#. They are true and false. They are used as values for
relational expressions.

13.2.4 Single Character Literals

A single character constant contains a single character enclosed within single quotes.
Examples are ‘x’, ‘5’, ‘ ’

13.2.5 String Literals

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”

13.2.6 Backslash constants:

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

13.4 Data Types

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

13.4.3 Value types

The value types in C# can be grouped into two categories


 User-defined types (Complex types)
 Predefined types (Simple types)
We can define our own complex types known as user-defined value types which include
struct type and enumerations. Predefined value types are also known as simple types or
primitive types. They are further divided into
 Numeric types
 Boolean types
 Character types
The table below gives a list of predefined data types

Type Represents Range Default


Value
Bool Boolean value True or False False
Byte 8-bit unsigned integer 0 to 255 0
Char 16-bit Unicode character U +0000 to U +ffff '\0'
Decimal 128-bit precise decimal (-7.9 x 1028 to 7.9 x 1028) / 100 to 28 0.0M
values with 28-29
significant digits
Double 64-bit double-precision (+/-)5.0 x 10-324 to (+/-)1.7 x 10308 0.0D
floating point type
Float 32-bit single-precision -3.4 x 1038 to + 3.4 x 1038 0.0F
floating point type
Int 32-bit signed integer type -2,147,483,648 to 2,147,483,647 0
Long 64-bit signed integer type -923,372,036,854,775,808 to 0L
9,223,372,036,854,775,807
Sbyte 8-bit signed integer type -128 to 127 0
Compiled By
Panchajanyeswari M Achar Page 151
Srinivas Institute of Management Studies V Semester BCA

Short 16-bit signed integer type -32,768 to 32,767 0


Uint 32-bit unsigned integer type 0 to 4,294,967,295 0
Ulong 64-bit unsigned integer type 0 to 18,446,744,073,709,551,615 0
Ushort 16-bit unsigned integer type 0 to 65,535 0

13.4.4 Reference types

The reference types can also be divided into


 User-defined types
 Predefined types

User-defined reference types refer to those types which we define using predefined value
types. They include
• Classes
• Interfaces
• Delegates
• Arrays

Predefined reference types include two data types:


• Object type
• String type
The object type is the ultimate base type of all other intrinsic and user-defined types in
C#. We can use an object reference to bind an object of any particular type. C# creates its own
string type for creating and manipulating strings.

13.5 Declaration of Variables:

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;

13.6 Initialization of Variables:


Variables are initialized (assigned a value) with an equal sign followed by a constant expression.
The general form of initialization is:
variable_name = value;
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists
of an equal sign followed by a constant expression as:
<data_type> <variable_name> = value;
Some examples are:

int d = 3, f = 5; /* initializing d and f. */


byte z = 22; /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x'; /* the variable x has the value 'x'. */

13.7 Constant Variables:

Constants are defined using the const keyword. Syntax for defining a constant is:

const <data_type> <constant_name> = value;

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

[Link]("Radius: {0}, Area: {1}", r, areaCircle);


[Link]();
}
}
}

When the above code is compiled and executed, it produces the following result:
Enter Radius:
3
Radius: 3, Area: 28.27431

13.8 Scope of Variables:

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

13.9 Boxing and Unboxing:

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:

An operator is a symbol that tells the compiler to perform specific mathematical or


logical manipulations. C# is rich in built-in operators and provides the following type of
operators:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Assignment Operators
• Increment/decrement operators
• Conditional operators
• Bitwise Operators

Compiled By
Panchajanyeswari M Achar Page 156
Srinivas Institute of Management Studies V Semester BCA

• Special Operators

14.2 Arithmetic 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

14.2.1 Integer Arithmetic:


When both the operands in the expression are integers, then the operation is known as
integer arithmetic.
For example if the values of a=14 and b=4 then
a+b=18 , a-b=10, a*b=56 , a/b=3, a%b=2
During modulo division, the sign of the result is the sign of the first operand.
E.g. -14%3=-2 , 14%-3=2
14.2.2 Real Arithmetic:
An arithmetic operation involving only real operands is called real arithmetic. A real
value can assume value either in decimal or exponential notation. % operator cannot be used
with real operands
E.g. If a=2.4 and b=1.2 then
a+b=3.6 , a-b=1.2, a*b=2.88 a/b=2.0

14.2.3 Mixed mode Arithmetic:


When one of the operands is real and the other is an integer, the expression is called
mixed mode arithmetic expression. The result is always a real number
E.g. : 15/10.0=1.5 , 15/10=1.5

14.3 Relational Operators:

Comparisons can be done using relational operators. A relational expression contains a


combination of arithmetic expressions, variables or constants along with relational operators. A
relational expression can contain only two values i.e. true or false. When the expression is

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

14.4 Logical Operators:

An expression that combines two or more relational expressions is called a logical


expression and the operators used to combine them are called logical operators.
Syntax:
R1 operator R2
where, R1 and R2 are relational expressions

Operator Meaning
&& Logical And
|| Logical Or
! Logical Not

Relational Relational R1&&R2 R1||R2


Expression R1 Expression R2
0 0 0 0
0 Non zero 0 Non zero
Non zero 0 0 Non zero
Non zero Non zero Non zero Non zero

14.5 Assignment Operators:

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

14.6 Increment/Decrement Operators:

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.

14.7 Conditional Operator:

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.

14.8 Bitwise Operators:

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:

Operator Description Example


& Binary AND Operator copies a bit to the result if it exists (A & B)
in both operands. will give
12. which is
0000 1100
| Binary OR Operator copies a bit if it exists in either (A | B) will
operand. give 61,
which is
0011 1101
^ Binary XOR Operator copies the bit if it is set in one (A ^ B) will
operand but not both. give 49,
which is
0011 0001
~ Binary Ones Complement Operator is unary and has the (~A ) will
effect of 'flipping' bits. give -61,
which is
1100 0011
in 2's
complement
due to a
signed
binary
number.
<< Binary Left Shift Operator. The left operands value is A << 2 will
moved left by the number of bits specified by the right give 240,
operand. which is
1111 0000
>> Binary Right Shift Operator. The left operands value is A >> 2 will

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

14.9 Special Operators:

C# supports the following special operators.


Operator Description Example
sizeof() Returns the size of a data type. sizeof(int), will return
4.
typeof() Returns the type of a class. typeof(StreamReader);
& Returns the address of an variable. &a; will give actual
address of the
variable.
* Pointer to a variable. *a; will pointer to a
variable.
?: Conditional Expression If Condition is true ?
Then value X :
Otherwise value Y
is Determines whether an object is of a certain If( Ford is Car) //
type. checks if Ford is an
object of the Car class.
as Cast without raising an exception if the cast Object obj = new
fails. StringReader("Hello");
StringReader r = obj
as StringReader;

14.10 Arithmetic Expressions:

An arithmetic expression is a combination of variables, constants and operators arranged


as per the syntax of the language. Expressions are evaluated using assignment statements of the
form
variable=expression;
Expressions are always evaluated from left to right, using the rules of precedence of operators, if
parenthesis are missing
High Precedence - * / %
Low Precedence - + -

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

14.11 Precedence of Arithmetic Operators:

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.

Category Operator Associativity


Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right

14.12 Type Conversions:

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

• Implicit type conversion - these conversions are performed by C# in a type-safe manner.


Examples are conversions from smaller to larger integral types and conversions from
derived classes to base classes. The process of assigning a smaller type to a larger one is
called widening or promotion. The process of assigning a larger type to a smaller one is
called narrowing.
• Explicit type conversion - these conversions are done explicitly by users using the pre-
defined functions. Explicit conversions require a cast operator.

Type Conversion

Implicit Conversion Explicit Conversion

Arithmetic Operations Casting Operations

Example for Explicit Type conversion:


namespace TypeConversionApplication
{
class ExplicitConversion
{
static void Main(string[] args)
{
double d = 5673.74;
int i;

// cast double to int.


i = (int)d;
[Link](i);
[Link]();

}
}
}

14.13 Mathematical Functions:

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;

[Link]("Original Value = {0}", number);


[Link]("Absolute Value = {0}\n", [Link](number));
return 0;
}
}
This would produce:
Original Value = -6844
Absolute Value = 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.

Long answer questions


1. How does C# differ from Java ?
2. Explain the different types of programs developed using C# (Executable , Libraries).
3. Explain the different Data Types (value and reference type with taxonomy of C# data type
fig).
4. Explain the different Value types used in C#.
5. What is Literal? Explain.
6. What are command line arguments ? Explain with example.
7. Explain Scope of variable with example.
8. What is Operator ? List the different types , explain any 4 types.
9. Explain Implicit conversion with example.
10. Explain Explicit conversion with example.
11. Explain the different elements of web service.
12. Explain the different states of [Link].
13. Write a note on UDDI.
14. Explain WSDL.
15. Write a note on Deployment .
16. What is Caching ? Explain the different types.
17. Explain the security mechanism used in [Link].

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

15.2 The if 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

15.2.1 Simple if statement:

The general form of simple if statement is as follows


if(test expression)
{
statement block;
}
statement x;
The statement block may be a single statement or a group of statements. If the test
expression is true, the statement block will be executed; otherwise the control jumps to statement
x. However, if the condition is true both the statement block as well as statement x are executed
in a sequence.

15.2.2 if..else statement:

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)
{

/* local variable definition */


int a = 100;
/* check the boolean condition */
if (a < 20)
{
/* if condition is true then print the following */
[Link]("a is less than 20");
}
else
{
/* if condition is false then print the following */
[Link]("a is not less than 20");
}
[Link]("value of a is : {0}", a);
[Link]();
}
}
}

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:

a is not less than 20;


value of a is : 100

Test
expression
?

True – block False – block


statements statements

Statement – x

15.2.3 Nested if..else statement:


When a series of decisions are involved, we may have to use more than one if..else
statement one within the other. This form of if..else statement is known as nested if..else
statement. The general format of this statement is as follows:

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

If condition 1 is initially false, statement 3 will be executed; otherwise it continues to


evaluate condition 2. If condition 2 is true then statement 1 is executed; otherwise statement 2
will be executed and then the control transfers to statement x.

Example
using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{

//* local variable definition */


int a = 100;
int b = 200;

/* check the boolean condition */


if (a == 100)
{
/* if condition is true then check the following */
if (b == 200)
{
/* if condition is true then print the following */
[Link]("Value of a is 100 and b is 200");
}
}
[Link]("Exact value of a is : {0}", a);
[Link]("Exact value of b is : {0}", b);
[Link]();
}
}
}

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

15.2.4 The Else-if Ladder:

A multi path decision is a chain of if statements in which each else is an if statement.


This construct is known as an else-if ladder. The general format of else-if ladder is as follows:

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)
{

/* local variable definition */


int a = 100;

/* check the boolean condition */


if (a == 10)

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:

None of the values is matching


Exact value of a is: 100

15.3 The switch statement:

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 */

/* you can have any number of case statements */


default : /* Optional */
statement(s);
}

The expression can either be an integer expression or a character expression. Value1,


value 2,….value n are constants known as case labels. Each of these values should be unique
within a switch statement. Case labels must end with a colon(:). When the switch statement is
executed, the value of the expression is successively compared against the values value1, value
2,….value n. If a match is found, the block of statements that follow the case are executed. The
break statement in each block signifies the end of that case and causes exit from the switch
statement. The default case is an optional one. The statements in this case are executed when no
case labels match with the value of that expression.

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

An if statement consists of a boolean expression followed by


if statement
one or more statements.

An if statement can be followed by an optional else statement,


if...else statement
which executes when the boolean expression is false.

You can use one if or else if statement inside another if or else


nested if statements
if statement(s).

A switch statement allows a variable to be tested for equality


switch statement
against a list of values.

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

DECISION MAKING AND LOOPING

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

C# supports 3 loop constructs to perform looping operations. They are as follows


• While statement
• Do…while statement
• For statement
16.2 The while statement:
The while statement is an entry-controlled loop. Here, the test condition is evaluated first
and if the condition is true the body of the loop is executed. After executing the statements
contained in the body of the loop, the test condition is again evaluated to check if it is true. This
process is repeated until the test condition becomes false; and the control is transferred out of the
loop. The general form of while statement is

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;

/* while loop execution */


while (a < 20)
{
[Link]("value of a: {0}", a);
a++;
}
[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
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

16.3 The do…while statement:

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.

The general form of do while statement is as follows:


do
{
statements;

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

16.4 For statement:


This statement is also an entry-controlled loop that provides a concise loop control
structure. The general form of for loop is as follows:
for(initialization; test condition; increment/decrement)
{
Body of the loop;

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

16.5 For Each statement:

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

Loop Type Description

Repeats a statement or group of statements while a given condition is


while loop
true. It tests the condition before executing the loop body.

Execute a sequence of statements multiple times and abbreviates the


for loop
code that manages the loop variable.

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.

16.6 Break statement:


In order to exit out of a loop, we use the break statement. When a break statement is
encountered inside a loop, the loop is immediately exited and the program continues with the
statement following the loop. When a break statement is encountered in a nested loop then, it
will only exit from the loop containing the break statement i.e. a break statement is used to exit
from a single loop only.
Syntax:
break;

Compiled By
Panchajanyeswari M Achar Page 182
Srinivas Institute of Management Studies V Semester BCA

16.7 Continue statement:


The continue statement causes the loop to be continued with the next iteration after
skipping any statements. The continue statement tells the compiler to skip the following
statements and continue with the next iteration.
Syntax:
continue;
Whenever the continue statement is encountered, the other statements are ignored by the
compiler and the control directly passes to the test condition to execute the next iteration. In case
of for loop, the increment section is executed before the test condition is evaluated.
The difference between break and continue statements is that the break statement causes
the loop to be terminated where as the continue statement continues to execute the loop with the
next iteration.

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:

In object oriented programming, objects are used as building blocks in developing a


program. They are runtime entities. They may represent a person, place, bank account or any
item that the program can handle. Objects encapsulate data and code to manipulate that data. The
code designed to work on data is called methods in C#. Methods give objects their behavioral
characteristics. They are sued not only to access and process data contained in the object but also
to provide responses to any messages received from other objects.

17.2 Declaring Methods:

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
}

Following are the various elements of a method:

• 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;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}
...
}

17.3 Invoking Methods:

Compiled By
Panchajanyeswari M Achar Page 185
Srinivas Institute of Management Studies V Semester BCA

The process of activating a method is known as calling or invoking a method. The


invoking is done using the dot(.) operator.
The general format is
[Link] name(actual-parameter list);

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;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}
static void Main(string[] args)
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
NumberManipulator n = new NumberManipulator();

//calling the FindMax method


ret = [Link](a, b);
[Link]("Max value is : {0}", ret );
[Link]();

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

17.4 Nesting of Methods:

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);

}
}

17.5 Method Parameters:

The different kinds of parameters are

Compiled By
Panchajanyeswari M Achar Page 187
Srinivas Institute of Management Studies V Semester BCA

• Value Parameters
• Reference parameters
• Output parameters
• Parameter arrays

17.5.1 Value parameters:

Value parameter is also called In parameter. A parameter declared with no modifiers is a


value parameter. A value parameter corresponds to a local variable that gets its initial value from
the corresponding argument supplied in the method invocation. A method is permitted to assign
new values to a value parameter. Such assignments only affect the local storage location
represented by the value parameter-they have no effect on the actual argument given in the
method invocation.

Example:
using System;

namespace CalculatorApplication
{
class NumberManipulator
{
public void swap(int x, int y)
{
int temp;

temp = x; /* save the value of x */


x = y; /* put y into x */
y = temp; /* put temp into y */
}

static void Main(string[] args)


{
NumberManipulator n = new NumberManipulator();
/* local variable definition */
int a = 100;
int b = 200;

[Link]("Before swap, value of a : {0}", a);


[Link]("Before swap, value of b : {0}", b);
Compiled By
Panchajanyeswari M Achar Page 188
Srinivas Institute of Management Studies V Semester BCA

/* calling a function to swap the values */


[Link](a, b);

[Link]("After swap, value of a : {0}", a);


[Link]("After swap, value of b : {0}", b);

[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

17.5.2 Reference parameters:

A parameter declared with a ref modifier is a reference parameter. Contrastingly to value


parameter, a reference parameter does not make a new storage location. Instead, a reference
parameter represents the same storage location as the variable given as the argument in the
method invocation. Within a method, a reference parameter is always considered definitely
assigned.

Example:
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public void swap(ref int x, ref int y)
{
int temp;

temp = x; /* save the value of x */


x = y; /* put y into x */
y = temp; /* put temp into y */

Compiled By
Panchajanyeswari M Achar Page 189
Srinivas Institute of Management Studies V Semester BCA

static void Main(string[] args)


{
NumberManipulator n = new NumberManipulator();
/* local variable definition */
int a = 100;
int b = 200;

[Link]("Before swap, value of a : {0}", a);


[Link]("Before swap, value of b : {0}", b);

/* calling a function to swap the values */


[Link](ref a, ref b);

[Link]("After swap, value of a : {0}", a);


[Link]("After swap, value of b : {0}", b);

[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

17.5.3 Output parameters:

A parameter declared with an out modifier is an output parameter. Similar to a reference


parameter, an output parameter does not create a new storage location. Instead, an output
parameter represents the same storage location as the variable given as the argument in the
method invocation. Every output parameter of a method must be definitely assigned before the
method returns. Output parameters are typically used in methods that produce multiple return
values.

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;
}

static void Main(string[] args)


{
NumberManipulator n = new NumberManipulator();
/* local variable definition */
int a = 100;

[Link]("Before method call, value of a : {0}", a);

/* calling a function to get the value */


[Link](out a);

[Link]("After method call, value of a : {0}", a);


[Link]();
}
}
}

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

17.5.4 Parameter arrays:

A parameter declared with a params modifier is a parameter array. If a formal parameter


list includes a parameter array, it must be the last parameter in the list and it must be of a single-

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

17.6 Method Overloading:

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

CLASSES AND OBJECTS

18.1 Introduction:

Compiled By
Panchajanyeswari M Achar Page 193
Srinivas Institute of Management Studies V Semester BCA

C# is a true object-oriented language. Anything we wish to represent in C# must be


encapsulated in a class that defines the state and behavior of the basic program components
called the objects. Classes create objects and objects use the methods to communicate between
them.

18.2 Basic Principles of OOP:

All object oriented languages employ three core principles, namely


• Encapsulation
• Inheritance
• Polymorphism

These are also referred to as the pillars of OOP

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.

18.3 Defining a Class

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

<access specifier> class class_name


{
// member variables
<access specifier> <data type> variable1;
<access specifier> <data type> variable2;
...
<access specifier> <data type> variableN;
// member methods
<access specifier> <return type> method1(parameter_list)
{
// method body
}
<access specifier> <return type> method2(parameter_list)
{
// method body
}
...
<access specifier> <return type> methodN(parameter_list)
{
// method body
}
}
Note:
• Access specifiers specify the access rules for the members as well as the class
itself, if not mentioned then the default access specifier for a class type is internal.
Default access for the members is private.
• Data type specifies the type of variable, and return type specifies the data type of
the data, the method returns, if any.
• To access the class members, you will use the dot (.) operator.
• The dot operator links the name of an object with the name of a member.

The following example illustrates the concepts discussed so far:


using System;
namespace BoxApplication
{
class Box
{
public double length; // Length of a box
public double breadth; // Breadth of a box
Compiled By
Panchajanyeswari M Achar Page 195
Srinivas Institute of Management Studies V Semester BCA

public double height; // Height of a box


}
class Boxtester
{
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box(); // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// 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

18.4 Adding Variable

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;
}

18.5 Adding Methods:

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;
}
}

18.6 Member Access Modifiers

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.

18.7 Creating Objects

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:

A class constructor is a special member function of a class that is executed whenever we


create new objects of that class.
A constructor will have exact same name as the class and it does not have any return type.
Following example explains the concept of constructor:
using System;
namespace LineApplication
{
class Line
{
private double length; // Length of a line
public Line()
{
[Link]("Object is being created");
}

public void setLength( double len )


{
length = len;
Compiled By
Panchajanyeswari M Achar Page 198
Srinivas Institute of Management Studies V Semester BCA

}
public double getLength()
{
return length;
}

static void Main(string[] args)


{
Line line = new Line();
// set line length
[Link](6.0);
[Link]("Length of line : {0}", [Link]());
[Link]();
}
}
}

When the above code is compiled and executed, it produces the following result:
Object is being created
Length of line : 6

18.8.1 Overloaded Constructors

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]);

Rectangle square = new Rectangle(5);


[Link]("Height: {0}", [Link]);

Compiled By
Panchajanyeswari M Achar Page 199
Srinivas Institute of Management Studies V Semester BCA

[Link]("Width: {0}", [Link]);


}

/* OUTPUT

Rectangle Constructor Called


Height: 4
Width: 6
Square Constructor Called
Height: 5
Width: 5

*/

18.8.2 Static Constructors

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()
{
……
}
}

18.8.3 Copy Constructors

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);

Now, item2 is a copy of item1.

18.8.4 Destructors

A destructor is opposite to a constructor. It is a method called when an object is no more


required. The name of the destructor is the same as class name but preceded by a tilde(~).Like
constructor, a destructor has no return type.

Example:
class Car
{
~Car() // destructor
{
// cleanup statements...
}
}

18.9 The this Reference:

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;
}

18.10 The readonly members

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;
}
}

// Declare a Name property of type string:


public string Name
{
get
{
return name;
}
set
{
name = value;
}
}

// Declare a Age property of type int:


public int Age
{
get
{
return age;
}
set
{
age = value;
}
}

Example:

Compiled By
Panchajanyeswari M Achar Page 203
Srinivas Institute of Management Studies V Semester BCA

The following example demonstrates use of properties:


using System;
namespace tutorialspoint
{
class Student
{

private string code = "N.A";


private string name = "not known";
private int age = 0;

// Declare a Code property of type string:


public string Code
{
get
{
return code;
}
set
{
code = value;
}
}

// Declare a Name property of type string:


public string Name
{
get
{
return name;
}
set
{
name = value;
}
}

// Declare a Age property of type int:

Compiled By
Panchajanyeswari M Achar Page 204
Srinivas Institute of Management Studies V Semester BCA

public int Age


{
get
{
return age;
}
set
{
age = value;
}
}
public override string ToString()
{
return "Code = " + Code +", Name = " + Name + ", Age = " + Age;
}
}
class ExampleDemo
{
public static void Main()
{
// Create a new Student object:
Student s = new Student();

// Setting code, name and the age of the student


[Link] = "001";
[Link] = "Jahnavi";
[Link] = 9;
[Link]("Student Info: {0}", s);
//let us increase age
[Link] += 1;
[Link]("Student Info: {0}", s);
[Link]();
}
}
}
When the above code is compiled and executed, it produces the following result:
Student Info: Code = 001, Name = Jahnavi, Age = 9
Student Info: Code = 001, Name = Jahnavi, Age = 10

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
}

// The set accessor.


set
{
// set the value specified by index
}
}

18.12.1 Use of Indexers

Declaration of behavior of an indexer is to some extent similar to a property. Like


properties, you use get and set accessors for defining an indexer. However, properties return or
set a specific data member, whereas indexers returns or sets a particular value from the object
instance. In other words, it breaks the instance data into smaller parts and indexes each part, gets
or sets each part.
Defining a property involves providing a property name. Indexers are not defined with names,
but with the this keyword, which refers to the object instance.

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;

if( index >= 0 && index <= size-1 )


{
tmp = namelist[index];
}
else
{
tmp = "";
}

return ( tmp );
}
set
{
if( index >= 0 && index <= size-1 )
{
namelist[index] = value;
}
}
}

static void Main(string[] args)


{
IndexedNames names = new IndexedNames();
names[0] = "Janani";
names[1] = "Jahnavi";

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

2. Explain about overloaded constructors


3. How do you work with classes in C#?Explain
4. Explain the concept of constructors

CHAPTER 19

INTERFACES
19.1 Introduction:

An interface in C# is a reference type. It is basically a class with the following


differences
• All the members in an interface are implicitly public and abstract
• An interface cannot contain constant fields, constructors and destructors
• Its members cannot be declared static
• Since the methods in an interface are abstract, they do not include implementation code
• An inheritance can inherit multiple interfaces

19.2 Defining Interfaces

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:

public interface ITransactions


{
// interface members
void showTransaction();
double getAmount();
}

19.3 Extending an Interface

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);
}

interface Compute : Addition


{
int Sub (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

19.4 Implementing an Interface

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:

class classname : interface name


{
Body of classname
}

Example:

using [Link];
using [Link];
using [Link];

namespace InterfaceApplication
{

public interface ITransactions


{
// interface members
void showTransaction();
double getAmount();
}
public class Transaction : ITransactions
{
private string tCode;
private string date;
private double amount;
public Transaction()
{
tCode = " ";
date = " ";
amount = 0.0;
}
public Transaction(string c, string d, double a)
{
tCode = c;
date = d;
amount = a;
}
public double getAmount()
{
Compiled By
Panchajanyeswari M Achar Page 211
Srinivas Institute of Management Studies V Semester BCA

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

19.5 Interfaces and Inheritance:

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.

19.6 Abstract Classes and Interfaces:

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

DELEGATES AND EVENTS

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.

20.2 Delegate Declaration:

The syntax for delegate declaration is

modifier delegate return-type delegate-name(parameters);

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

A delegate may be defined in the following places:


 Inside a class
 Outside a class
 As a top level object in a namespace

20.3 Delegate instantiation

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:

public delegate void printString(string s);


...
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
Following example demonstrates declaration, instantiation and use of a delegate that can be used
to reference methods that take an integer parameter and returns an integer value.
using System;

delegate int NumberChanger(int n);


namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}

public static int MultNum(int q)


{
num *= q;
return num;
}
public static int getNum()
{
return num;
}

static void Main(string[] args)


{
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
//calling the methods using the delegate objects
nc1(25);
[Link]("Value of Num: {0}", getNum());
nc2(5);
[Link]("Value of Num: {0}", getNum());
Compiled By
Panchajanyeswari M Achar Page 215
Srinivas Institute of Management Studies V Semester BCA

[Link]();
}
}
}

When the above code is compiled and executed, it produces the following result:
Value of Num: 35
Value of Num: 175

20.4 Delegate invocation

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)

20.5 Using Delegates

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);

// this method prints to the console


public static void WriteToScreen(string str)
{
[Link]("The String is: {0}", str);
}
//this method prints to a file
public static void WriteToFile(string s)
{
fs = new FileStream("c:\\[Link]",
Compiled By
Panchajanyeswari M Achar Page 216
Srinivas Institute of Management Studies V Semester BCA

[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

20.6 Multicast Delegates

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;

delegate int NumberChanger(int n);


namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
Compiled By
Panchajanyeswari M Achar Page 217
Srinivas Institute of Management Studies V Semester BCA

return num;
}

public static int MultNum(int q)


{
num *= q;
return num;
}
public static int getNum()
{
return num;
}

static void Main(string[] args)


{
//create delegate instances
NumberChanger nc;
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
nc = nc1;
nc += nc2;
//calling multicast
nc(5);
[Link]("Value of Num: {0}", getNum());
[Link]();
}
}
}
When the above code is compiled and executed, it produces the following result:
Value of Num: 75

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:

modifier event type event-name;

Examples:

public event EventHandler Click;


public event RateChange Rate;

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 class EventTest


{
private int value;

public delegate void NumManipulationHandler();

public event NumManipulationHandler ChangeNum;

protected virtual void OnNumChanged()


{
if (ChangeNum != null)
{
ChangeNum();
}
else
{
[Link]("Event fired!");
}

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

Long answer questions


1. What are the benefits provided by CLR to programs developed using C#?
Compiled By
Panchajanyeswari M Achar Page 220
Srinivas Institute of Management Studies V Semester BCA

2. Explain the structure of C# program.


3. Explain Boxing and Unboxing with example.
4. What are the various forms of ‘if’ statement ? Explain with example.
5. Differentiate Switch and if statement.
6. What is “fallthrough” in switch statement ? How is it achieved in C#?
7. Explain the following loops with syntax and example:
while ii) do…while iii) for iv) foreach
9. List the additional features of ‘for ‘ loop.
10. Differentiate between
i) while and do..while ii) break and continue iii) for and foreach
11. What are Nested loops ? Explain with example.
12. Explain with example , how methods are declared in C# .
13. What is nesting of methods? Give an example.
14. What are Method parameters ? Explain the different types.
15. What are Parameter Arrays? Explain with example.
16. Explain Method Overloading with example
17. Explain with syntax and example , how a class is defined? Also list the categories of class
members.
18. Explain Static members.
19. What is Constructor? Explain with syntax and example .
20. Explain Overloaded Constructor.
21. Differentiate between Constant members and Read-only members.
22. What is a Property? Explain with example implementing a property.
23. Differentiate between Interface and class.
24. What is Interface? Explain the defining , extending and implementing interface.
25. Explain with syntax and example , how delegates are declared.
26. Explain Delegate Methods.

VALUE ADDED CHAPTER

[Link] with MVC

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

The MVC Programming Model

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 View displays the data (the database records).


• The Controller handles the input (to the database records).

The MVC model also provides full control over HTML, CSS, and JavaScript.

The MVC model defines web


applications with 3 logic layers:

The business layer (Model logic)


The display layer (View logic)
The input control (Controller logic)

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.

Web Forms vs MVC

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.

Visual Studio Express contains:


• MVC and Web Forms
• Drag-and-drop web controls and web components
• A web server language (Razor using VB or C#)
• A web server (IIS Express)
• A database server (SQL Server Compact)
• A full web development framework ([Link])

Creating the Web Application


If you have Visual Web Developer installed, start Visual Web Developer and select New
Project. Otherwise just read and learn.

In the New Project dialog box:


• Open the Visual C# templates
• Select the template [Link] MVC 3 Web Application
• Set the project name to MvcDemo
• Set the disk location to something like c:\w3schools_demo
• Click OK
When the New Project Dialog Box opens:
Compiled By
Panchajanyeswari M Achar Page 223
Srinivas Institute of Management Studies V Semester BCA

• Select the Internet Application template


• Select the Razor Engine
• Select HTML5 Markup
• Click OK
Visual Studio Express will create a project much like this:

Exploring the Application Folders

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.

Below is a brief summary of the content of each folder:

The App_Data Folder


The App_Data folder is for storing application data.

The Content Folder

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

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

The Models Folder


The Models folder contains the classes that represent the application models. Models hold and
manipulate application data.
We will create models (classes) in a later chapter of this tutorial.

The Views Folder


The Views folder stores the HTML files related to the display of the application (the user
interfaces). The Views folder contains one folder for each controller.
Visual Web Developer has created an Account folder, a Home folder, and a Shared folder (inside
the Views folder).
The Account folder contains pages for registering and logging in to user accounts.
The Home folder is used for storing application pages like the home page and the about page.
The Shared folder is used to store views shared between controllers (master pages and layout
pages).

The Scripts Folder

Compiled By
Panchajanyeswari M Achar Page 227
Srinivas Institute of Management Studies V Semester BCA

The Scripts folder stores the JavaScript files of the application.


By default Visual Web Developer fills this folder with standard MVC, Ajax, and jQuery files:

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

WEB DEVELOPMENT IN .NET


NEW CREDIT BASED Fifth Semester BCA Degree Examination
October/November 2014

Time: 3 hours Max Marks: 100


Note: Answer any TEN questions from Part A and ONE full question in each unit of Part B

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

2. a. Explain the <img> element in HTML with any five attributes.


b. Explain the various transformations that can be applied in CSS3
c. Explain the structure of HTML5 document with an example
d. Explain the concept of applying gradients in CSS3 (5+5+5+5)

3. a. How do you work with frames in HTML. Explain


b. Explain any five new features that are introduced in HTML5
c. Explain any five form elements available in HTML5
d. Explain the concept of drawing rectangles in HTML5 with canvas element.
(5+5+5+5)

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

6. a. Explain the types of deployment projects available in visual [Link]


b. Explain the security mechanisms implemented in [Link]
c. Explain about the various literals supported by C#
d. Explain about the type conversions in C# with examples (5+5+5+5)

7. a. Write short notes on implementing threads in .NET environment


b. Explain different deployment techniques are available for deploying an application
c. Explain any five differences between C# and Java
d. Explain the arithmetic operators available in C# with examples (5+5+5+5)

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)

9. a. Explain the do–while statement in C# with syntax and example


b. Explain the different types of method parameters in C#
c. How do you overload a constructor in C#? Give example
d. Write a note on indexers in C#. (5+5+5+5)

Compiled By
Panchajanyeswari M Achar Page 230

You might also like