Download as pdf or txt
Download as pdf or txt
You are on page 1of 61

UNIT – I

Short answer questions (2 marks)


1. List any two structural elements of HTML5 with its purpose.
<figure> This element can be used to explain main text with diagram.
<footer> This element can be used to describe the web page footer section.

2. How do you create CANVAS in HTML5? Give an Example (<CANVAS> tag)


The html5 canvas element is used to display graphics in web pages. The html5 syntax for creating such
an element is as follows:
<canvas width=”xxxpixel” hight=”yyypixels”>…</canvas>..

3. Differentiate between strokeRect() and fillRect() method.


Drawing Rectangle:
There are two types of rectangle.
• To draw hollow rectangles the strokeRect function is used.
stroke Rect(float x, float y, float w, float h);
• To draw filled-in rectangles the fillRect function is used.
fillRect (float x, float y, float w, float h);
The fill color of the rectangle is set with the fillstyle attribute. Using rgba() we specify a color
and pass this to fillstyle attribute to the rectangle created. The rgba() requires 4 values. The red,
green, blue value specified in numeric value and visibility factor defined by either 0 or 1. Where
0 means rectangle is invisible and 1 means it is visible.

4. Write the necessary tags used to draw a line with red color, whose coordinate values are {10,50}, {100,100}.
Ans:canvas.beginPath();
Canvas.strokeStyle=’rgba(800,0,0,1)’;
Canvas.moveTo(10,50);
Canvas.lineTo(100,100);
Canvas.closePath();
Canvas.stroke();

5. Write the syntax of rgba() used in canvas with an example?


Using rgba() we specify a color and pass this to fillstyle attribute to the rectangle created. The rgba() requires 4
values. The red green blue value specified in numeric value and visibility factor defined by either 0 or 1. Where
0 means rectangle is invisible and 1 means it is visible.
Syntax:Canvas.strokeStyle=’rgba(800,0,0,1)’;

6. List any two HTML5 form input controls with their purpose.
email This accepts only email value. This type is used for input fields that should contain an e-mail address.
If you try to submit a simple text, it forces to enter only email address in email@example.com format.
url This accepts only URL value. This type is used for input fields that should contain a URL address. If
you try to submit a simple text, it forces to enter only URL address either in http://www.example.com
format or in http://example.com format.

7. What is the purpose of readonly and placeholder attributes in HTML5 form inputs?
1. The readonly attribute
It is a boolean attribute. When present, it specifies that an input field is read-only. A read-only input field cannot
be modified. The readonly attribute can be set to keep a user from changing the value until some other
conditions have been met (like selecting a checkbox, etc.). Then, a JavaScript can remove the readonly value,
and make the input field editable.
Syntax:<input readonly>
Ex:<input type="text" id="country" name="country" value="Norway" readonly><br/>
2. The Placeholder Text:
HTML5 permits the place for placeholder text within the input field. Placeholder text is a text displayed in the
input field as long as that field is empty and form cursor is not on the field. When user clicks on input field the
placeholder text will disappear.
Example:
<form>
<input name="firstname" placeholder="Enter First Name"> <input type="submit" value="search">
</form>

8.What is the purpose of autocomplete and disabled attributes?


autocomplete
The autocomplete attribute specifies whether or not an input field should have autocomplete enabled.
Autocomplete allows the browser to predict the value. When a user starts to type in a field, the browser should
display options to fill in the field, based on earlier typed values.
disabled attribute
The disabled attribute is a boolean attribute. When present, it specifies that the <input> element should be
disabled. A disabled input element is unusable and un-clickable. The disabled attribute can be set to keep a user
from using the <input> element until some other condition has been met (like selecting a checkbox, etc.). Then, a
JavaScript could remove the disabled value, and make the <input> element usable.

9. What are video containers? List any two of them.


Video and audio containers:
We think of video files as "AVI files" or "MP4 files." In reality, "AVI" and "MP4" are just container
formats. Just as a ZIP file can contain any sort of file within it. Video container formats only define how to
store things within them, not what kind of data is stored. A video file usually contains multiple tracks: a
video track (without audio), plus one or more audio tracks (without video). Tracks are usually interrelated.
An audio track contains markers within it to help synchronize the audio with the video. Individual tracks can
have metadata, such as the aspect ratio of a video track or the language of an audio track. Containers can
also have metadata, such as the title of the video itself, cover art for the video, episode numbers, and so on.
There are lots of video container formats: MPEG-4 and ogg
10. Write any two attributes of audio tag with their purpose?
1.The controls attribute is a boolean attribute.When present, it specifies that audio controls should be
displayed.Audio controls should include: Play, Pause, Seeking, Volume/
e.g
<audio controls>
<source src="horse.ogg" type="audio/ogg"></audio>
2.same as video attributes
11. Write any two attributes of video tag with their purpose?
1.The src attribute specifies the location (URL) of the video file.To play the video in old Internet Explorer
and Safari, we must use an MPEG4 file.To make it work in all browsers - add several <source> elements
inside the <video> element. Each <source> elements can link to different video files.
The browser will use the first recognized format:
<video autoplay controls loop muted>
<video src="pr6.webm" width="320 height="240" preload></video>
2.The autoplay attribute is a boolean attribute. When present, the video will automatically start playing.
Add muted after autoplay to let your video file start playing automatically (but muted).
3. The muted attribute is a boolean attribute. When present, it specifies that the audio output of the video
should be muted.
4.The loop attribute is a boolean attribute. When present, it specifies that the video will start over again,
every time it is finished

12. Differentiate between value type and reference types.


The Value types are stored on the stack and when a value of variable is assigned to another variable, the
value is actually copied. This means two identical copies are available in the memory.
Reference types are stored on heap, and when the assignment between two reference variable occurs,
only the reference is copied; the actual value remains in the same memory location. This means there are 2
references to a single value.
13. List the special operators used in C#, with their purpose.
is The is operator is used to determine whether an object reference can be converted to a
specific type or interface.
as The as operator is very similar to the is operator, but instead of just determining whether an
object is a specific type or interface, it also performs the explicit conversion to that type or
interface.
typeof The typeof operator returns the type of the object, which is an instance of the System.Type
class. Typeof is useful to avoid having to create an instance of an object just to obtain the type
object.
sizeof Sizeof operator determines the size of the type.
new New operator is used to create new objects with reference in heap.

. (dot) The. (dot) operator is used to access class members.

checked The checked operator evaluates the contained expression in a checked context for overflow.

14. How do you write comments in C#?


C# supports both the single-line (//) and multiline (/*…*/) comment syntaxes.
Example: One-line comments begin with two slashes and remain in effect for the rest of the line: { // this is
an opening brace.
Regular comments begin with a slash followed by an asterisk and remain in effect until an asterisk followed
by a slash is found. Regular comments can span multiple lines: /* This is a regular comment in C#. It
contains multiple lines of text, Separated by NewLine characters. */

15. Define literals. List any two literal types used in C#.
Literals are value constant assigned to variable (or result of expression) in a program. C# supports several
types of literals.
Two literal types used in C#.
Boolean -There are 2 Boolean literals true and false.
String Literals- A string literal is a sequence of character enclosed between double quotes. Example: “hello”

16. What are called predefined reference types? List them.


Predefined reference types
1. Object type
The object class type is the ultimate base class of all other types. Every type in C# directly or indirectly
derives from the object class type. The object keyword is simply an alias for the predefined
System.Object class. Writing the keyword object is exactly the same as writing System.Object, and vice
versa.
2. String type
The string type is a sealed class type that inherits directly from object. Instances of the string class
represent Unicode character strings. Values of the string type can be written as string literals. The string
keyword is simply an alias for the predefined System.String class. Writing the keyword string is exactly
the same as writing System.String, and vice versa.

17. What do you mean by Boxing/Unboxing?


Boxing and Unboxing:
In object-oriented programming, methods are invoked using objects. Since value types such as int and long
are not object, we cannot use them to call methods. C# enables us to achieve this technique known as
boxing. Boxing means the conversion of a value type on the stack to an object type on the heap. The
conversion form an object type back to a value type is known as unboxing.

18. List the different types of Method Parameters used.


• Value parameters
• Output parameters
• Reference parameters
• Parameter array

19. Distinguish between ref and out parameters.


Output parameters are parameters whose values are not set when the method is called. Instead, the method
sets the values and returns the values to the caller through the output parameter.
Reference parameters supply values by reference: In other words, the method receives a reference to the
variable specified when the method is called. Reference parameters are specified in parameter lists with the
keyword ref. The ref keyword must precede the parameter's type in the parameter list

20. Write the syntax of conditional operator used in C# with an example.


The conditional operator evaluates a boolean expression, and, depending on its resultant value (either true
or false), executes one of two expressions as defined here
Syntax:
ConditionalOperator = <<condition>> "?" <<Expr If condition true>> ":" <<Expr If condition true> >

21. Differentiate break and continue statements used in C#?


The break statement
C# also enables us to use the break statement to break out of the current block of statements. Usually, the
break statement is used to break out of an iteration statement block:
int x = 0;
while(x < 10) {
System.Console.WriteLine(x);
if(x == 5)
break;
x++;
}
System.Console.Write("Out of the loop.");

The continue statement returns control to the Boolean expression that controls an iteration statement, as
shown in the following code:
int a;
for(a = 0; a < 10; a++)
{
if(a == 5)
continue;
System.Console.Write(a);
}
The preceding code prints the following to the console: 012346789

22. What is the purpose of goto statement in C#? Give an example.


The goto statement unconditionally transfers control to a labeled statement. We can label any statement in C#.
Statement labels are identifiers that precede a statement. A colon follows a statement label. A label identifier follows
the goto keyword, and the goto statement transfers control to the statement named by the label identifier, as shown in
the following code:
int g = 0;
while(g < 10)
{ System.Console.WriteLine(g);
if(g == 5)
goto Done;
g++;
} System.Console.WriteLine("Hello Done!");
Done:
System.Console.Write("Out of the loop.");
The preceding code prints the following to the console: 0 1 2 3 4 Out of the loop

23. What do you mean by overloaded constructors?


Overloading Constructors: You can overload constructors in C# just like regular methods. Consider the
Point class. It has a constructor that takes (x, y) coordinates. Constructor overloading is subject to the same
rules as method overloading. The following code shows the Point class with overloaded,
public class Point {
public int x ;
public int y ;
public Point() {
x=0;y=0;
}
public Point( int x, int y )
{
this.x = x ;
this.y = y ; } // Other methods removed for simplicity
}

24. What do you mean by polymorphism?


Polymorphism may exhibit different behaviour in different situations. The perform depends on the type of
data used in the operation.
25. What do you mean by copy constructor?
Copy Constructor in C#
The constructor which creates an object by copying variables from another object is called a copy
constructor. The purpose of a copy constructor is to initialize a new instance to the values of an existing
instance.
Syntax
public employee(employee emp)
{
name=emp.name;
age=emp.age;
}

26. What do you mean by destructors? How they are defined in C#?
C# classes may have a destructor as well as constructors.
In C#, destructors for all objects are invoked prior to program termination. Destructors look like methods
with no return type or access modifiers. They are named after their class and their names are preceded by a
tilde (~) symbol.
The following is a destructor for the Point class.
~Point()
{
// Clean up here
}
Destructors take no parameters and return no values. We must never attempt to invoke a destructor directly.
C# destructors are a syntactic shortcut for the Object.Finalize() method.

27. What do you mean by ‘this’ reference in C#?


In c# programming, this is a keyword that refers to the current instance of the class. There can be 3 main
usage of this keyword in C#.
o It can be used to refer current class instance variable. It is used if field names (instance variables)
and parameter names are same, that is why both can be distinguish easily.
o It can be used to pass current object as a parameter to another method.
o It can be used to declare indexers.
28. Compare constant with read-only members used in C#?
Readonly members: Fields are data members of a class. They are variables contained within a class and, in
object-oriented terms, manage the class's state. Fields defined in a class can be accessed by any method
defined in the same class. We can define a field just as any variable is defined. Fields have a type and an
identifier. We may also define a field without an initial value. To mark fields as read-only, prefix the
declaration with the readonly keyword. If you use the readonly keyword, it should appear just before the
field's type.
class MyClass
{
public readonly;
int Field1;
public static void Main()
{}
}
5marks.

5. Explain different Data Types (value and reference type with taxonomy of C# data type fig). (6)
Ans:

• Numeric types
• Boolean types
• Character types

array

As the name suggests, the data type is the type of data you are going to store in your variable. The data type is used to
suggest the compiler or interpreter which kind of data it is going to process and how much memory will be required for
that data.
Syntax:datatype <variable_name> = value;
Examples of C# Data Types: int intVal = 55;
1. Value Types
Directly stores the value of a variable in memory.
Accepts both signed and unsigned literals.
There are two types of value data types in C#:
*Predefined data types like int, char, bool, etc.
*User-defined data types like enum, struct, etc.
//declaring enum
enum Days { Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday };
//declaring structure
struct Student
2. Reference Types
They store the address of variable i.e. they contain the reference to a variable.
If the data is changed by one variable, the other variable will automatically get the updated value.There are two types of
reference data types in C#:
*Predefined types like Object, String
*User-defined types like Class, Interface

6. What is Literal? Explain. (5)


Literals
Literals are value constant assigned to variable (or result of expression) in a program.Constants can be termed as
those immutable values known at compile-time, and values cannot be changed during the program's life. In other
words, constants are used for declaring any C# identifier whose values remain the same during the entire program
run. C# supports several types of literals as shown in fig:

9. Explain Scope of variable with example. (5)


Ans: Scope of Variables: The scope of variable is the region of the code within which the variables can be accessed.
This depends on the type of the variable and place of its declaration.
C# defines several categories of variables. They include
• Static variables • Instance variables • Array elements • Value parameters • Reference parameters
• Output parameters • Local variables
consider the code,
class ABC {
static int m;
int n;
void fun(int x, ref int y, out int z, int [] a)
{ int j=10;
… … } This code contain the following variables, m as static variable
n as an instance variable
x as a value parameter
y as a reference parameter
z as an output parameter
j as local variable
Static and instance variables are declared at the class level and known as fields or field variables. The scope of these
variables begins at the place of their declaration and ends when the Main () method terminates. The variable x, y, z are
parameter of the function fun(). The value parameter x will exist till the end of the method.

10. List and explain any four types of operators, with example. (5)
Ans: C# provides all the basic arithmetic operators. They are listed in the table. They can operate on any built in data
type. we can not use these operators on boolean type. The unary minus operator, multiples with -1.
Integer Arithmetic: When both the operands in a single arithmetic expression such as a+b are integers. The expression is
called integers expression, and the operation is called integer arithmetic. Real Arithmetic: An arithmetic operation
involving only real operands is called real arithmetic. A real operand may assume values either in decimal or
exponential notations. Example : A+B=20; R-S=10; x/y=45;
Mixed Mode Arithmetic: When one of the operands is real and other is integer, the expression is called a mixed-mode
arithmetic expression. If either operand is one of the real types, then the other operand is converted to real and real
arithmetic is performed. The result will be a real. For Example: 15/10.0 produces the result
Operator Description Example

+ Adds two operands A + B = 30

- Subtracts second operand from the first A - B = -10

* Multiplies both operands A * B = 200

/ Divides numerator by de-numerator B/A=2

% Modulus Operator and remainder of after an integer division B%A=0

Relational:
> Checks if the value of left operand is greater than the value of right operand, if yes then (A > B) is not
condition becomes true. true.

< Checks if the value of left operand is less than the value of right operand, if yes then condition (A < B) is true.
becomes true.

>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes (A >= B) is not
then condition becomes true. true.

<= Checks if the value of left operand is less than or equal to the value of right operand, if yes (A <= B) is
then condition becomes true. true.
Logical operator: C# has logical operator. The logical operator && and || are used when we use to form compound
conditions by combining two or more relations. An example a>b&& x==10 An expression of this kind termed as
logical expression or a compound relation expression.
Called Logical AND operator. If both the operands are non zero then condition becomes true.
&& (A && B) is
false.

Called Logical OR Operator. If any of the two operands is non zero then condition becomes true.
|| (A || B) is true.

Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is
! !(A && B) is
true.
true then Logical NOT operator will make false.

Assignment:

= Simple assignment operator, Assigns values from right side operands to left C = A + B assigns value of
side operand A + B into C

+= Add AND assignment operator, It adds right operand to the left operand and C += A is equivalent to C =
assign the result to left operand C+A

-= Subtract AND assignment operator, It subtracts right operand from the left C -= A is equivalent to C =
operand and assign the result to left operand C-A

*= Multiply AND assignment operator, It multiplies right operand with the left C *= A is equivalent to C =
operand and assign the result to left operand C*A

/= Divide AND assignment operator, It divides left operand with the right C /= A is equivalent to C =
operand and assign the result to left operand C/A

Increment and decrement operator :


The increment (++) and decrement (--) operators come in two flavors: prefix and postfix. In the prefix case, the
increment or decrement operator is placed before a simple data type variable. For example: ++a // a = a + 1 In the
postfix case, the increment or decrement operator is placed after a simple data type variable. For example: a-- // a = a - 1
These operators have the side effect of changing the value of a simple data type variable by plus one for an increment
and minus one for a decrement. The prefix operator increments or decrements the simple data type variable before the
expression in which it appears is evaluated. The postfix operator increments or decrements the simple data type variable
after the expression in which it appears is evaluated.

11. Explain Boxing and Unboxing with example. (6)


Boxing and Unboxing: In object oriented programming, methods are invoked using objects. Since value types
such as int and long are not object, we cannot use them to call methods. C# enables us to achieve this technique
known as boxing. Boxing means the conversion of a value type on the stack to an object type on the heap. The
conversion form an object type back to a value type is known as unboxing. The concept of boxing and unboxing is
central to C# type system. It provides a bridge between value-types and reference-types by permitting any value of
a value-type to be converted to and from type Object. Boxing and Unboxing enables a unified view of the type
system wherein a value of any type can ultimately be treated as an object.
Boxing:
Boxing Any type, value or reference can be assigned to an object without an explicit conversion. When the
compiler finds the 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 m=100;
object om= m; // creates a box to hold m
When executed, code creates a temporary reference type “box” for the object on heap. We can also use a c style
cast for boxing.
int m=100;
object om = (object) m; // c style casting
The boxing operation create s a copy of the value of the m integer to the object om. Both the variable m and om
exists but the value of om resides on the heap.
UnBoxing:
Unboxing is the process of converting the object type back to the value type. We can unbox a variable that has
previously been blocked. Unboxing is an explicit operation using c style casting.
int m=10;
object om = m; // box m int
n = (int) om; // unbox om back to an integer .
When performing unboxing c# checks that the value type we request is actually stored in the object under
conversion. When unboxing a value, we have to ensure that the value type is larger than enough to hold the value
of the object; otherwise the operation may result in the runtime error.
Example for boxing and unboxing:
class Test {
static void Main(){
int i = 123;
object o = i; // boxing
int j = (int) o; // unboxing
}}

12. What are the various forms of ‘if’ statement? Explain with example. (5)
The if statement: The if statement is a powerful decision making statement and is used to control the flow of
execution of the statements.
It is a two way decision making statement and used with an expression it takes the following form, if(expression){
statement
}
the if statement may be implemented in different forms depending on the complexity of the condition to be tested.
1. simple if statement
2. if …else statement
3. nested if ..else statement
4. else… if ladder
The general form of a simple if statement is,
if(boolean-expression) {
Statement-block;
}Statement–x;
The statement block may be a single statement or a group of statements. If the expression is true the statement
block is executed otherwise the statement block will be skipped the next statement-x are executed in sequence.
Example:
if(x>10)
System.Console.WriteLine (“X is greater than 10”);
if( avg > 70) {
Grade=”distinction”;
}
The if…else statement: The if…else construct is the most frequently used flow control statement. It tests a
condition and if that condition is true, it executes either the next code statement or several code statements if they
are enclosed in curly braces. If the condition does not evaluate to true, then it either skips the code segment, or
executes code in an else statement.
The general form is,
if(boolean-expression){
True-block statements;
}
else {
False-block statement;
}
Example:
if(x == 1) System.Console.WriteLine("X is equal to 1.");
else
System.Console.WriteLine("X is not equal to 1.");
Nesting of if statements
When a series of decisions are involved, we may have to use more than one if… else statement in nested form. To
nest if statement, we place a second if statement within the first. We can nest within the if section or the else
section. Example:
if( gender == ‘m’ ) {
// it is a male
}
else {
if ( gender == ‘f’ ){
// it is a female }
else {
//neither a male or a female
}}
The else if ladder
There is another way of writing if statements when multiple decisions are involved. A multiple decision is chain of
ifs in which the statement associated with each else is an if. It takes the following general form, The General form
of if—else—if is as follows,
if(condition 1)
{ Statement-block1; }
else if (condition 2)
{ Statement-block 2; }
else if (condition 3)
{ Statement-block3; } … …
else
{ default-statement; }
Statement-x;
Example:
if (Grade >= 90 )
Console.WriteLine( "A" );
else if (Grade >= 80 )
Console.WriteLine( "B" );
else if (Grade >= 70 )
Console.WriteLine( "C" );
else if (Grade >= 60 )
Console.WriteLine( "D" );
else Console.WriteLine( "F" )

13. Differentiate Switch and if statement. (4)


Ans: C# has built-in multi way decision statement known as switch. The switch statement tests the value of given
variable (or expression) against a list of case values and when a match is found , a block of statement associated with
that case is executed. The general form of switch statement is as shown below,
switch(expression)
{ case value-1:
block-1 break;
case value-2: block-2 break;
case value-N: block-N break;
default: default-block; break;
The expression must be integer type or char or a string type. value-1, value-2… are constants or constant expression are
known as case labels.
switch(marks)
{ case 7: System.Console.WriteLine(“A”);
break;
case 6: System.Console.WriteLine(“B”); break;
case 4: System.Console.WriteLine(“C”); break;
case 3: System.Console.WriteLine(“D”); break;
default : System.Console.WriteLine(“E”); break; }

14. What is “fallthrough” in switch statement ? How is it achieved in C#? (5)


Fallthrough in switch statement In C# programming language, In absence of the break statement in a case block, if
the control moves to the next case block without any problem it is known as ‘falthrough’. Falthrough is permitted
in c, c++, and java. The C# does not permit automatic falthrough, if the case block contains executable code.
However, it is allowed if the case block is empty.
For example: if we want to consecutive case block to be executed continuously, we have to force the process by
using goto statements. The above code can be written like this,
switch(m) { case 1: x=y;
goto case 2;
case 2: x=y+1;
goto default;
default: x=y + m; break; }

15. Explain the following loops with syntax and example:


(i) while: The while statement The while loop executes a segment of code 0 or more times, based on the
outcome of a boolean control expression. The while loop is called an indeterminate loop and is usually
used when the program will be unaware of the number of iterations of the loop until it has been entered.
The following code demonstrates the while loop. Initialization
while(test condition)
{ // Body of the loop }
While is an entry-controlled loop statement. The test condition is evaluated and if the condition is true,
then the body of the loop is executed.
Example: while (i < 10)
{ Console.WriteLine(i);
i++; }
while(n<=10)
{ if(n%2==0)
{ n++; }
else { Console. Write(“” +n);
n++; }
Gives the output as, 1 3 5 7 9
ii) do…while: The do-while loop executes a segment of code 1 or more times. It is similar to the while
loop, except that the control condition is evaluated after the loop body had run once. The general form of
do-while, Initialization
do { body of the loop //
while(test condition);}
Example:
sum=0;
do { sum=sum+1; i=i+2;
while( sum<10);

iii) for: The for statement The C# provides another entry condition controlled loop known as for loop. The
general format of for statement is as follows,
for(initialization ; test condition ; increments)
{ Body of the loop //statements. }
Example:
int n, sum=0;
for(n=1;n<=10;n++)
{Sum = sum + n * n; }
We can use nesting of for loops, ie one for loop inside the other for loop.

iv) foreach: The foreach statement The foreach statement is similar to for loop but implemented
differently. It enables us to iterate the elements in array and collection classes such as List and HashTable.
We can use the foreach statement to iterate over the elements in a collection.
The general form of for each statement is,
foreach (type variable in expression)
{ // body of the loop }
The type and variable declare the iteration variable. During execution, the iteration variable represents the
array element for which iteration is currently being performed. The in is a keyword.
Example : public static void Main (string [] args)
{ foreach (string s in args)
{ Console.WriteLine(s); } }

16. What are Nested loops? Explain with example. (if)

17. Explain with an example, how methods are declared in C#. (5)
Ans: A method is a group of statements that together perform a task. Every C# program has at least one class with a
method named Main.
To use a method, you need to −
*Define the method
*Call the method
Defining Methods in C#
When you define a method, you basically declare the elements of its structure. The syntax for defining a method in C# is
as follows −
<Access Specifier> <Return Type> <Method Name>(Parameter List)
{ Method Body}
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)
{ int result;

if (num1 > num2)


result = num1;
else
result = num2;
return result;
}
} //calling the FindMax method
ret = n.FindMax(a, b);
Console.WriteLine("Max value is : {0}", ret );
Console.ReadLine();

18. What is nesting of methods? Give an example. (5)


Multiple Main Methods:
C# includes a feature that enables us to define more than one class with main method. Since Main Method is the
entry point for program execution, there are now more than one entry points. In fact, there should be only one. This
problem can resolved by specifying which main is to be used to the compiler at the time of execution as shown
bellow. C:> CSC MultipleMain.cs /main: classname Example:
using System;
class ClassA{
Public static void Main(){
Console.WriteLine(“ClassA”);
}}
class ClassB{
Public static void Main() {
Console.WriteLine(“ClassB”);
}}

19. What are Method parameters? Explain the different types. (5)
Method Parameters: All parameters specified in function member declarations are considered to be value
parameters unless they are preceded by the ref or out keyword. C# allows four types of parameters in a parameter
list:
• Value parameters • Output parameters • Reference parameters • Parameter arrays
▪ Value parameters Input parameters are parameters whose value is sent into the method. All the parameters
used up to this point have been input parameters. The values of input parameters are sent into the function, but
the method's body cannot permanently change their values. Input parameters are passed by value into methods.
The method basically sees a copy of the parameter's value, but is not allowed to change the value supplied by
the caller.
▪ Pass-by-value By default method parameters are passed by value. A parameter declared with no modifier is
passed by value and is called a value parameter. When a method is invoked, the value of actual parameters is
assigned to the corresponding formal parameters. The values of the value parameters can be changed with in the
method. The value of the actual parameter that is passed by value to method is not changed by any change made
to the corresponding formal parameter within the body of the method.
▪ Pass-by-reference Reference parameters supply values by reference: In other words, the method receives a
reference to the variable specified when the method is called. Reference parameters are specified in parameter
lists with the keyword ref. The ref keyword must precede the parameter's type in the parameter list. When you
call a method with a reference parameter, you must declare a variable to hold the reference parameter's value.
▪ The Output Parameters Output parameters are parameters whose values are not set when the method is called.
Instead, the method sets the values and returns the values to the caller through the output parameter.

20. What are Parameter Arrays? Explain with example. (5)


Parameter arrays enable us to specify that our method accept a variable number of arguments. We specify the
parameter array in our parameter list by using the C# keyword params, followed by the type of variable that should
be supplied by the caller. The type specification is followed by square brackets, which are followed by the
identifier of the parameter array. The use of a parameter array allows the caller of a method to provide a variable
number of arguments when invoking a method; these are passed into the method in the form of an array.
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 = app.AddElements(10, 20, 30, 40, 50);
Console.WriteLine("The sum is: {0}", sum);
Console.ReadKey(); } }} The output is 150

21. Explain Method Overloading with an example. (5)


Methods overloading: C# allows us to create a more than one method with same name, but with different
parameter lists and different definitions. This is called method overloading. Method overloading is used when
methods are required to perform similar tasks but using different input parameter. C# enables you to define
multiple methods with the same name in the same class, as long as those methods have different parameter lists.
This is referred to as overloading the method name. Example1:
int add(int x, inty){}
int add (int a, int b, int c){}
double add(float x, float y) {}
Example2:
Class MethodOverload {
public static void Main(){
MethodOverload m;
m = new MethodOverload ();
m.Add(3, 4);
m.Add(3.5, 4.75);
}
void Add(int i, int j){
int Sum;
System.Console.WriteLine("adding two integers");
Sum = i + j;
System.Console.WriteLine(Sum);
}
void Add(double x, double y) {
double Sum;
System.Console.WriteLine("adding two doubles");
Sum = x + y;
System.Console.WriteLine(Sum);
} } //end of class

22. Explain with syntax and example, how a class is defined? Also list the categories of class members. (5)
Defining a Class A class is a user-defined data type with template that serves to define its properties. Once the
class type has been defined we can create variables of that type using declarations that are similar to the basic type
declaration. In C# variables are termed as instance of classes, which are the actual objects.
The basic form of class definition is:
class ClassName{
variable declaration;// method declarations
}
The class is keyword and ClassName is any c# valid identifiers. A class can be an empty class.

23. Explain Static members used inside the class in C#.

24. What is Constructor? Explain with syntax and example. (5)


Constructors: A constructor is a special member function of the class. We identify it as a constructor by giving it
the same name as its class. It cannot return a value, nor can it declare a return type—not even a return type of void.
C# supports a special type of method, called constructor, that enables and object to initialize itself when it is
created. Constructor has the same name as class itself. They do not specify a return type, not even void they do not
return any value. Constructors are usually public because they provide to create objects. In C#, there is no default
constructor created for objects. For classes, a default (e.g., parameter less) constructor may be written if needed. A
constructor can invoke a constructor of the base type by using the base. Example:
class Hello{
public int x; public int y;
Hello(int x, int y) // constructor with 2 parameters
{
this.x =x;this.y =y;}}

25. Explain Overloaded Constructors in c#. (5)


Overloading Constructors: You can overload constructors in C# just like regular methods. Consider the Point
class. It has a constructor that takes (x, y) coordinates. Constructor overloading is subject to the same rules as
method overloading.
The following code shows the Point class with overloaded,
public class Point {
public int x ;
public int y ;
public Point(){
x=0;y=0;
}
public Point( int x, int y ){
this.x = x ; this.y = y ;
} // Other methods removed for simplicity }

26. How constant members and read-only members are created and used in C#? Explain with an example. (6)
Constant members:C# enables you to place multiple constant definitions on the same line, provided that all of the
constants share the same type. You can separate your class constant definitions with a comma, as follows:
class MyClass{
public const int One = 1, Two = 2, Three = 3;
public static void Main() { } }
Readonly members: Fields are data members of a class. They are variables contained within a class and, in object
oriented terms, manage the class's state. Fields defined in a class can be accessed by any method defined in the
same class. We can define a field just as any variable is defined. Fields have a type and an identifier. We may also
define a field without an initial value. To mark fields as read-only, prefix the declaration with the readonly
keyword. If you use the readonly keyword, it should appear just before the field's type.
class MyClass
{ public readonly int Field1;
public static void Main() { } }
The value of a read-only field may be set when the field is declared or in the constructor of the class. Its value
cannot be set at any other time. Any attempt to change the value of a readonly field is caught by the C# compiler
and appears as an error.

UNIT – II
Short answer questions (2 marks)
1. What is ASP.NET?
ASP.NET is the latest version of Active Server Pages(ASP). 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.
2. Write any two differences between ASP and ASP.NET.
(in 5 marks)
3. What are Server controls? Name the different types of it.
SERVER CONTROLS: Server controls are tags that are understood by the server.
There are three kinds of server controls
 HTML Server Controls-Traditional HTML tags.
 Web Server Controls-New ASP.NET tags.
 Validation Server Controls-for input validation.

4. Name the different types of web controls (four types).


Web Server Controls: Web server controls are special ASP.NET tags understood by the server. Like HTML
server controls, web server controls are also created on the server and they require a runat=“server” attribute to
work.However, web server controls do not necessarily map to any existing HTML elements and they may
represent more complex elements.
There are four types of web controls.
 Web sever controls
 Validation web controls
 Data controls
 Rich web controls

5. Write the syntax of creating Web Server Control.


The syntax for creating a Web server control is:
<asp:control_name id=“some_id” runat=“server”/>

6. List any two Web Server Controls, also specify their purpose.

Web Server Control Description

AdRotator Displays a sequence of images.


Button Displays a push button
Calendar Displays a calendar
CalenderDay A day in a calendar control.
CheckBox Displays a check box
CheckBoxList Creates a multi-selection check box group.
DataGrid Displays fields of a data source in a grid.
DataList Displays items from a data source by using templates.
DropDownList Creates a drop-down list.
HyperLink Creats a Hyperlink.
Image Displays an image.
ImageButton Displays a clickable image.
Label Displays static content which is programmable.
LinkButton Creates a hyperlink button.
ListBox Creates a single or multi-selection drop-down list.
ListItem Creates an item in a list.

7. List any two HTML Server Controls, also specify their function.
Control Description

Anchor Controls an <a> HTML element

Button Controls a <button> HTML element


Form Controls a <form> HTML element
image Controls an <image> HTML element

8. Name any four validation controls.


They include:
 RequiresFieldValidator
 CompareValidator
 RangeValidator
 RegularExpressionValidator
 CustomValidator
 Validation Summary

9. List any two data controls.


They include;
 DataGrid
 DataList
 DataRepeater

10. What are rich controls? List them.


They are customized controls that provide high-level functionality to developers.
They include:
 Calender
 AdRotator

11. What is the purpose of TextMode and MaxLength properties of textbox control in ASP.NET?
maxlength attribute specifies the maximum length of the text that can be typed in the text box. It is used to set
maximum number of characters that can be entered.
Text: It is used to set text to be shown for the control. A text box control can accept one or more lines of text
depending upon the settings of the TextMode attribute.

12. What are buttons? List their types in ASP.NET?


Ans: ASP.NET Web Forms Button:This control is used to perform events. It is also used to submit client request to the
server. To create Button either we can write code or use the drag and drop facility of visual studio IDE.
• Button : It displays text within a rectangular area.
• Link Button : It displays text that looks like a hyperlink.
• Image Button : It displays an image.

13.What are the different options are used to specify the RepeatLayout property of the CheckBoxList. : Answer For
both 13&14
RepeatLayout This attribute specifies whether the table tags or the normal html flow to use while formatting the
list when it is rendered. The default is Table.

Flow 1 Items are displayed without a table structure. Rendered markup consists of a span element and
items are separated by br elements.
OrderedList 3 Items are displayed without a table structure. Rendered markup consists of an ol element that
contains li elements.
This value is new as of ASP.NET 4 and is a valid option only for
the CheckBoxList and RadioButtonList controls.
Table 0 Items are displayed in a table.
This option causes the control to render HTML that might not conform to accessibility
standards. For more information, see Accessibility in Visual Studio and ASP.NET.

UnorderedList 2 Items are displayed without a table structure. Rendered markup consists of a ul element that
contains li elements.
This field is new as of ASP.NET 4 and is a valid option only for
the CheckBoxList and RadioButtonList controls.

14.What are the different options are used to specify the RepeatLayout property of the RadioButtonList.
RepeatLayout This attribute specifies whether the table tags or the normal html flow to use while formatting the
list when it is rendered. The default is Table.

15.What are Panel Controls? Why it is used?


The Panel control is used as a container for other controls. This control is often used to generate controls by code
and to display or hide groups of controls as per the condition. It controls the appearance and visibility of the controls it
contains.

16.Name the control used for banner advertisement in ASP.Net? Explain any one attribute of it.
Ans: Adrotator.
17.Write the usage of CompareValidator.
Ans: ASP.NET CompareValidator Control:This validator evaluates the value of an input control against another input
control on the basis of specified operator.We can use comparison operators like: less than, equal to, greater than etc.

18.What are validation controls? List any two of them.


ASP.NET Validation: To perform validation, ASP.NET provides controls that automatically check user input and
require no code. We can also create custom validation for our application.
ASP.NET validation controls are:

19. What are the advantages of disconnected data access architecture?


Ans: In disconnected architecture, the data retrieved from database can be accessed even when connection to
the database was closed. It was built on classes connection, dataadapter, commandbuilder and dataset and
dataview.

20. What are data bound controls? List any two such controls used for complex binding?
Databound controls are used to display data to the end-user within the web applications and using databound
controls allows you to manipulate the data within the web applications very easily.
Databound controls are bound to the DataSource property. Databound controls are composite controls that
combine other ASP.NET Controls like Text boxes, Radio buttons, Buttons and so on.

21. What is the purpose of the following objects used in ADO.NET:


a) Command Object: The ADO Command object is used to execute a single query against a database. The
query can perform actions like creating, adding, retrieving, deleting or updating records.
If the query is used to retrieve data, the data will be returned as a RecordSet object. This means that the
retrieved data can be manipulated by properties, collections, methods, and events of the Recordset
object.
b) DataSet Object:The DataSet object is central to supporting disconnected, distributed data scenarios
with ADO.NET. The DataSet is a memory-resident representation of data that provides a consistent
relational programming model regardless of the data source. It can be used with multiple and differing
data sources, with XML data, or to manage data local to the application.
c) DetailsView:A DataView enables you to create different views of the data stored in a DataTable, a
capability that is often used in data-binding applications. Using a DataView, you can expose the data in
a table with different sort orders, and you can filter the data by row state or based on a filter expression.
d) ListView: A ListView is a type of AdapterView that displays a vertical list of scroll-able views and
each view is placed one below the other. Using adapter, items are inserted into the list from an array or
database. For displaying the items in the list method setAdaptor() is used. setAdaptor() method conjoins
an adapter with the list. Android ListView is a ViewGroup that is used to display the list of items in
multiple rows and contains an adapter that automatically inserts the items into the list.

Long answer questions


1. Write the different characteristics of ASP.NET. (5)
CHARACTERISTICS OF ASP.NET
 The ASP.NET page framework is a programming framework that runs on a web server to produce and manage
ASP.NET web form pages dynamically.
 These pages are extensions of standard HTML forms. They render dynamic, interactive and database-driven
content.
 The ASP.NET page framework creates an abstraction of the traditional client-server web interaction so that we
can program our application using traditional methods and tools that support rapid application development and
object-oriented programming.(OOP)
 Web forms pages can expose HTML elements as server-side objects with properties, methods and events.
 The ASP.NET page framework and web forms pages also support ASP.NET (server) controls that encapsulates
common UI functionality, easy to use and reusable controls.

2. Differentiate ASP with ASP.NET (5)


ASP ASP.NET
Mixed-up coding: ASP code is mixed up with HTML Support for separation of code and content.
code. ASP are unstructured and difficult to maintain
or understand
Platform Dependence Platform Independence
Poor support for user interface Simplified development due to good user interface.
No backward compatibility Backward Compatibility: ASP.NET maintains
backward compatibility with earlier versions of
ASP, COM(component object model) and with all
windows operating systems.
File extension is .asp File extension is .aspx
Supports only scripting languages: only support ASP.NET applications can be developed using any
scripting language like JavaScript, vbscript. one of the .NET compatible programming
languages.
Poor Reusability: ASP pages are interpreted and Good Reusability.
executed on the web server, line by line from top to
bottom. each page is therefore written in a sequential
manner to meet specific objectives, which makes it
difficult to re-use the page in another application.
Lack of true component model. Support by .NET framework.
Lack of event-driven programming model. Good support of event-driven programming model.
Not simple to write code. Simplified Development: ASP.NET minimizes the
amount of coding required to develop an
application by using server-side controls
(components) and event-driven programming.

3. Explain the architecture of ASP.NET with a neat diagram. (5)


ARCHITECTURE OF ASP.NET
It provides an overview of the ASP.NET infrastructure and subsystem relationships as they are related to the
subject of security.
The following illustration shows the relationship among the security systems in ASP.NET.

As illustrated above,
o All web clients communicate with ASP.NET applications through IIS.
o IIS deciphers(decodes) and optionally authenticates the request.
o If allow Anonymous options is turned on, no authentication occurs.
o IIS also finds the requested resource (such as an ASP.NET application) and if the client is authorized returns the
appropriate resource.
o In addition to the built-in ASP.NET security features, an ASP.NET application can use the low-level security
features of .NET framework.

4. Write the advantages of ASP.NET web form pages. (5)


Advantages of ASP.NET 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
between round trips.
 They are flexible through the use of ASP.NET controls. These controls provide RAD capability for web
development allowing us to create rich user interfaces quickly.
 They are supported in Visual Studio 7.0 with powerful RAD tools for coding and designing the pages.
 They are compatible with any .NET complaint programming language.
 They provide all the benefits of the .NET framework including a managed environment, type safety and
inheritance.
 They are flexible because we can add user-created and third party controls to them.
 They are reusable.
5. What are HTML Server controls? List any five HTML server controls with their purpose. (5)
HTML SERVER CONTROLS
 HTML server controls are HTML tags understood by the server.
 HTML elements in ASP.NET files are by default treated as text. To make these elements programmable, add a
runat=“server” attribute to the HTML element.
 This attribute indicates that the element should be treated as a server control. The id attribute is added to
identify the server control. The id reference can be used to manipulate the server control at run time.
HTML Server Control Description
Anchor Controls an <a> HTML element
Button Controls a <button> HTML element
Form Controls a <form> HTML element
Image Controls an <image> HTML element
Controls a <select> HTML element.
select

6. Explain ASP.NET Web server Controls. (5)


ASP.NET – Web Server Controls
Web server controls are special ASP.NET tags understood by the server.
Like HTML server controls, web server controls are also created on the server and they require a runat=“server”
attribute to work.
However, web server controls do not necessarily map to any existing HTML elements and they may represent
more complex elements.
The syntax for creating a Web server control is:
<asp:control_name id=“some_id” runat=“server”/>
We can use button server control in the following file for the click event. In an .aspx file.
Types of Web Server Controls
There are four types of web controls.
 Web sever controls
 Validation web controls
 Data controls
 Rich web controls
Web sever controls
Like HTML server controls, web server controls also created on the server and they require a runat=“server”
attribute to work.
However, web server controls do not necessarily map to any existing HTML elements and they may represent
more complex elements.

7. Explain different types of buttons used in ASP.NET with their properties and example. (6)
Button is used as normal click button, submitting form data, resetting the form data to its initial value.
According to the usage of button, you can render the button in three types. By using the Type property, you
can easily render the button in following types.
There are three type of button control in asp.net.
1. Simple Push Button – Simple Push Button displays text on a button control.
2. Link Button – Link button displays text that looks like a link or hyperlink.
3. Image Button – Image Button displays an image on a button control.
Button Control Syntax :
The Simple Push Button code is like: <asp:Button ID=“Button1“ runat=“server“ Text=“Button“ />
The LinkButton code is like:
<asp:LinkButton ID=“LinkButton1“ runat=“server“>LinkButton</asp:LinkButton>
The ImageButton code is like:
<asp:ImageButton ID=“ImageButton1“ runat=“server“ />
Properties Description

ID Identification name of button control.

Text It is used to display text in a control.

BackColor It is used to set background color of button control.

Enable true/false – used to enable or disable control.

Visible true/false – It is used to hide or visible control on web page.

Important Properties of Button control

CommandName A string value passed to code behind when button Command event is fired.

OnClientClick The JavaScript function name or any client side script code function name.

For Image Button

ImageUrl Set image path to display image on image button control.

AlternateText Alternate text will be displayed when image cannot be displayed on web page.
Code:
<html>
<body>
<form runat="server">
<asp:Button id="b1" Text="Submit" runat="server" />
</form>
</body>
</html>
All server side control has its own properties and events. below list shows properties of Button control .

8. Explain ImageControl of ASP.NET with its properties. (5)


The image control is used for displaying images on the web page, or some alternative text, if the image is not
available.The image is sourced from either a location on the server or from a URL on the internet. ASP.NET provides its
own tag for the Image control which is run at the server and the generated HTML code is returned as a response to the
browser. So, thinking from the HTML perspective, the Image control generates the HTML <img> tag along with the
attributes such as source, height, width, styles, etc.
Basic syntax for an image control:
<asp:Image ID="Image1" runat="server">
It has the following important properties:
Properties Description
AlternateText Alternate text to be displayed in absence of the image.
<asp:Image ID=“myFlowerImage” AlternateText="Flower Image" runat=“server” />
BorderColor, These properties get or set the border styling for the control. <asp:Image ID=“myFlowerImage”
BorderStyle and BorderWidth="5" BorderColor="Blue"
BorderWidth BorderStyle="dashed" runat=“server” />
font This property gets or sets the font of the text to be displayed with the control. There are plenty of
styles and options such as bold, italics, underline, strikeout, etc.
visible This property determines whether the control will be displayed on the UI or hidden. The default is
true.
<asp:Image ID=“myFlowerImage” Visible="false" runat=“server” />
enabled This property gets or sets the value indicating whether the control is enabled or disabled. The
default value is true.
<asp:Image ID=“myFlowerImage” Enabled="false" runat=“server” />
ImageAlign Alignment options for the control.
<asp:Image ID=“myFlowerImage” ImageAlign=“Right” runat=“server” />
ImageUrl Path of the image to be displayed by the control.
<asp:Image ID=“myFlowerImage” ImageUrl=“~/Content/myFlowerImage.jpg” runat=“server” />

9. Explain the following controls with an example using these properties: (any two) (6)
a) TEXTBOX (CausesValidation, MaxLength, ReadOnly, Rows, Cols, Runat, Text, TextMode, OnTextChanged)
Text box controls are typically used to accept input from the user. A text box control can accept one or more
lines of text depending upon the settings of the TextMode attribute.
< asp:TextBoxID="TextBox1" runat="server" ></asp:TextBox>
Common Properties of the Text Box .
Properties Description
TextMode Specifies the type of text box. SingleLine creates a standard text box, MultiLIne creates a text box that
accepts more than one line of text and the Password causes the characters that are entered to be masked.
The default is SingleLine.
Text The text content of the text box.
MaxLength The maximum number of characters that can be entered into the text box.
Wrap It determines whether or not text wraps automatically for multi-line text box; default is true.
ReadOnly Determines whether the user can change the text in the box; default is false, i.e., the user can change the
text.
Columns The width of the text box in characters. The actual width is determined based on the font that is used for the
text entry.
Rows The height of a multi-line text box in lines. The default value is 0, means a single line text box.

b) BUTTONS (CausesValidation, CommandArgument, CommandName, OnClientClick, Text ) Button in ASP


.NET is the basic controls in ASP .NET. Usually, this is used to display a normal push button. This button may
be a submitted button or maybe a command button. By default, its control is a submit button. It provides three
basic button controls. They are button,link,image button.This control is used to perform events. It is also used to
submit client request to the server. To create Button either we can write code or use the drag and drop facility
of visual studio IDE.This is a server side control and asp provides own tag to create it.
The example is given below.
< asp:ButtonID="Button1"runat="server"Text="Submit"BorderStyle="Solid"ToolTip="Submit"/>

BackColor Gets or sets the background color of the Web server control.
(Inherited from WebControl)
BorderColor Gets or sets the border color of the Web control.
(Inherited from WebControl)
BorderStyle Gets or sets the border style of the Web server control.
(Inherited from WebControl)
BorderWidth Gets or sets the border width of the Web server control.
(Inherited from WebControl)
CausesValidation Gets or sets a value indicating whether validation is performed when the Button control is
clicked.
CommandArgument Gets or sets an optional parameter passed to the Command event along with the
associated CommandName.
CommandName Gets or sets the command name associated with the Button control that is passed to
the Command event.
Text Gets or sets the text caption displayed in the Button control.

c) LABEL (AssociatedControlId , Text)


Label controls provide an easy way to display text which can be changed from one execution of a page
to the next. If you want to display text that does not change, you use the literal text. To
create label either we can write code or use the drag and drop facility of visual studio 2017.This is
server side control, asp provides own tag to create label. The example is given below.
< asp:LabelID="Label1" runat="server" Text="Label" ></asp:Label>

AssociatedControlID Gets or sets the identifier for a server control that the Label control is associated with.
Text Gets or sets the text content of the Label control.

d) DropDownList (BorderColor, BorderStyle,BorderWidth,SelectedIndex)

BorderColor Gets or sets the border color of the Web control.


BorderStyle Gets or sets the border style of the Web server control.
BorderWidth Gets or sets the border width of the Web server control.
The DropDownList is a web server control which is used to create an HTML Select component. It allows us to
select an option from the dropdown list.
It can contain any number of items.
<asp:DropDownList id="DropDownList1" runat="server"
DataSource="<% databindingexpression %>"
DataTextField="DataSourceField"
DataValueField="DataSourceField"
AutoPostBack="True|False"
OnSelectedIndexChanged="OnSelectedIndexChangedMethod">
<asp:ListItem value="value" selected="True|False">
Text
</asp:ListItem>
</asp:DropDownList>

e)CheckBox ( CausesValidation, Checked, Text, TextAlign, CheckedChanged(event ))


It is used to get multiple inputs from the user. It allows user to select choices from the set of choices. It takes user input
in yes or no format. It is useful when we want multiple choices from the user. To create CheckBox we can drag it from
the toolbox in visual studio. This is a server side control and ASP.NET provides own tag to create it.
The example is given below:< asp:CheckBox ID="CheckBox2" runat="server" Text="J2EE"/>
Checked It is used to set check state of the control either true or false.

CausesValidation Gets or sets a value indicating whether validation is performed when the CheckBox control is
selected.

Text Gets or sets the text label associated with the CheckBox.

TextAlign Gets or sets the alignment of the text label associated with the CheckBox control.

CheckedChanged Occurs when the value of the Checked property changes between posts to the server.

f)CheckBoxList (CellPadding , CellSpacing , RepeatColumns, RepeatDirection , RepeatLayout}


Creates a multi selection check box group that can be dynamically created by binding the control to a data source.
What is CheckBoxList in asp net?
ASP.NET CheckBoxList is a web control that can be used to collate the items that can be checked, thus giving the user
the ability to select multiple items simultaneously. This list of items in the CheckBoxList can be dynamically generated
using the Data Binding functions.
CellPadding Gets or sets the distance (in pixels) between the border and contents of the cell.

CellSpacing Gets or sets the distance (in pixels) between cells.


RepeatColumns Gets or sets the number of columns to display in the CheckBoxList control.

RepeatDirection Gets or sets a value that indicates whether the control displays vertically or
horizontally.
RepeatLayout Gets or sets a value that specifies whether the list will be rendered by using
a table element, a ul element, an ol element, or a span element.

g) RadioButton {GroupName)
It is an input control which is used to takes input from the user. It allows user to select a choice from the group of
choices.To create RadioButton we can drag it from the toolbox of visual studio. This is a server side control and
ASP.NET provides own tag to create it.
The example is given below.
< asp:RadioButtonID="RadioButton1" runat="server" Text="Male" GroupName="gender"/>
GroupName Gets or sets the name of the group that the radio button belongs to.

h)RadioButtonList( CellPadding , CellSpacing , RepeatColumns, RepeatDirection , RepeatLayout)


RadioButtonList Control is same as DropDownList but it displays a list of radio buttons that can be arranged either
horizontally or vertically.
You can select only one item from the given RadioButtonList of options.
<asp:RadioButtonList ID="businesstype" runat="server" >
<asp:ListItem Selected="True" Value="0">B to B</asp:ListItem>
<asp:ListItem Value="1">B to C</asp:ListItem>
</asp:RadioButtonList>

CellPadding Gets or sets the distance (in pixels) between the border and the contents of the table cell.

CellSpacing Gets or sets the distance (in pixels) between adjacent table cells.
RepeatColumns Gets or sets the number of columns to display in the RadioButtonList control.

RepeatDirection Gets or sets the direction in which the radio buttons within the group are displayed.

RepeatLayout Gets or sets a value that specifies whether the list will be rendered by using
a table element, a ul element, an ol element, or a span element.

i) Panel (BackImageUrl , Direction , GroupingText, HorizontalAlign , ScrollBars )


The Panel control works as a container for other controls on the page. It controls the appearance and visibility of
the controls it contains. It also allows generating controls programmatically.
The basic syntax of panel control is as follows:
<asp:Panel ID= "Panel1" runat = "server"></asp:Panel>
The Panel control is derived from the WebControl class.
BackImageUrl Gets or sets the URL of the background image for the panel control.
Direction Gets or sets the direction in which to display controls that include text in a Panel control.

GroupingText Gets or sets the caption for the group of controls that is contained in the panel control.

HorizontalAlign Gets or sets the horizontal alignment of the contents within the panel.

ScrollBars Gets or sets the visibility and position of scroll bars in a Panel control.

j) AdRotator (AdvertisementFile, AlternateTextField, ImageUrlField, NavigatorUrlField, Target) The AdRotator


control randomly selects banner graphics from a list, which is specified in an external XML schedule file. This
external XML schedule file is called the advertisement file. The AdRotator control allows you to specify the
advertisement file and the type of window that the link should follow in the AdvertisementFile and the Target
property respectively.
The basic syntax of adding an AdRotator is as follows:
<asp:AdRotator runat = "server" AdvertisementFile = "adfile.xml" Target = "_blank"/>

AdvertisementFile Gets or sets the path to an XML file that contains advertisement information.
AlternateTextField Gets or sets a custom data field to use in place of the AlternateText attribute for an
advertisement.
imageUrlField Gets or sets a custom data field to use in place of the ImageUrl attribute for an
advertisement.
NavigateUrlField Gets or sets a custom data field to use in place of the NavigateUrl attribute for an
advertisement.
Target Gets or sets the name of the browser window or frame that displays the contents of the
Web page linked to when the AdRotator control is clicked

k)Calendar( SelectionMode, DayHeaderStyle, DayStyle, SelectedDayStyle,TitleStyle, TodayDayStyle,


WeekendDayStyle ,showNextPrevMonth ,ShowTitle)
It is used to display selectable date in a calendar. It also shows data associated with specific date. This control
displays a calendar through which users can move to any day in any year. We can also set Selected Date property
that shows specified date in the calendar.
To create Calendar we can drag it from the toolbox of visual studio.
s<asp:Calender ID = "Calendar1" runat = "server"></asp:Calender>

Properties Description

DayHeaderStyle Gets the style properties for the section that displays the day of the week.

DayStyle Gets the style properties for the days in the displayed month.

SelectedDayStyle Gets the style properties for the selected dates.

SelectionMode Gets or sets the selection mode that specifies whether the user can select a single
day, a week or an entire month.

ShowTitle Gets or sets a value indicating whether the title section is displayed.

Titlestyle Get the style properties of the title heading for the Calendar control.

TodayDayStyle Gets the style properties for today's date on the Calendar control.
WeekendDayStyle Gets the style properties for the weekend dates on the Calendar control

10. Explain the following validators with example. (6)


a) RequiredFieldValidator: This validator is used to make an input control required. It will throw an error if user
leaves input control empty.It is used to mandate form control required and restrict the user to provide data.
The RequiredFieldValidator control ensures that the required field is not empty. It is a simple validation
control,which check to see if the data is enterd for the input control.
The syntax of the control is as given:
<asp:RequiredFieldValidator ID=”Rfv"
runat="server" ControlToValidate ="textbox1"
ErrorMessage="Please choose a candidate"/>
</asp:RequiredFieldValidator>

b) RangeValidator :This validator evaluates the value of an input control to check that the value lies between
specified ranges.it checks to see if a control values is within the a valid range.
It allows us to check whether the user input is between a specified upper and lower boundary. This range can be
numbers, alphabetic characters and dates.
The RangeValidator control verifies that the input value falls within a predetermined range.
The syntax of the control is as given:
<asp:RangeValidator ID="rv" runat="server" ControlToValidate="txtbox2"
ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
MinimumValue="6" Type="Integer">
</asp:RangeValidator>

c) RegularExpressionValidator :This validator is used to validate the value of an input control against the pattern
defined by a regular expression.
Using this control we can check user’s input based on a pattern that we define using a regular expression it is
used to validity Complex expressions for example email phone number.
<asp:RegularExpressionValidator ID="REV" runat="server" ErrorMessage="string"
ValidationExpression="textbox3">
</asp:RegularExpressionValidator>

d) CompareValidator :The CompareValidator control compares a value in one control with a fixed value or a
value in another control. We can use comparison operators like: less than, equal to, greater than etc.
Properties Description

Type It specifies the data type.

ControlToCompare It specifies the value of the input control to compare with.

ValueToCompare It specifies the constant value to compare with.


<asp:CompareValidator ID=”CV" runat="server" ErrorMessage="CompareValidator"
ControlToValidate="txtbox2" >
</asp:CompareValidator>

e) CustomValidator: The CustomValidator control allows writing application specific custom validation routines
for both the client side and the server side validation.
The client side validation is accomplished through the ClientValidationFunction property. The client side
validation routine should be written in a scripting language, such as JavaScript or VBScript, which the browser
can understand.
The server side validation routine must be called from the control's ServerValidate event handler. The server side
validation routine should be written in any .Net language, like C# or VB.Net.
The basic syntax for the control is as given:
<asp:CustomValidator ID="Cv1" runat="server"
ClientValidationFunction=.cvf_func. ErrorMessage="CustomValidator">
</asp:CustomValidator>

f) ValidationSummary :The ValidationSummary control does not perform any validation but shows a summary of
all errors in the page. The summary displays the values of the ErrorMessage property of all validation controls
that failed validation.
The following two mutually inclusive properties list out the error message:
ShowSummary : shows the error messages in specified format.
ShowMessageBox : shows the error messages in a separate window.
The syntax for the control is as given:
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
DisplayMode = "BulletList" ShowSummary = "true" HeaderText="Errors:" />

11. List and explain any six ADO.NET objects. (6)


1) DataSet: Shared by both the System.Data.ADO and the System.Data.SQL namespaces, the ADO.NET DataSet
object is the core component of the ADO.NET architecture. DataSet, an in-memory database cache for use in
disconnected operations, contains a complete collection of tables, relationships, and constraints. ADO.NET posts
changes to DataSet's contents in batch to the target data source. DataSet corresponds to ADO's disconnected
Recordset object.
2) SQLDataSetCommand: The SQLDataSetCommand object represents a database query or stored procedure that
you use to populate the ADO.NET DataSet object. SQLDataSetCommand corresponds, in part, to the functionality
that ADO's Command object provides.
3) SQLCommand: The SQLCommand object represents a T-SQL statement or stored procedure that SQL Server
will execute. SQLCommand corresponds to another piece of functionality that ADO's Command object provides.
4) SQLParameter: You use the SQLParameter object to pass parameters to the SQLCommand or
SQLDataSetCommand object. When you use SQLParameter to pass a parameter to SQLCommand, SQLParameter
represents a parameter that a T-SQL statement or stored procedure can use. When you use SQLParameter to pass a
parameter to SQLDataSetCommand, SQLParameter represents a column from a result set. SQLParameter
corresponds to ADO's Parameter object.
5) SQLConnection: The SQLConnection object represents an open connection to a SQL Server data source. This
object is like ADO's standard Connection object.
6) SQLDataReader: Like ADO's fast, forward-only Recordset object, the SQLDataReader object reads a forward-
only data stream from a SQL Server database. Unlike most other ADO.NET objects, SQLDataReader works with
an open database connection.
7) SQLError: The SQLError object collects information about runtime warnings and error conditions that an
ADO.NET application encounters. SQLError corresponds to ADO's Error object.

12. Explain the following Controls with their purpose, attributes, and methods: (any two) (6)
SqlDataSource:
Represents an SQL database to data-bound controls.
The SqlDataSource can support any SQL relational database that can be connected to using an ADO.NET provider, such
as the SqlClient, OleDb, Odbc, or OracleClient provider...
Designed to work with SQL Server databases. It uses Sql Server .NET data provider internally. Sql Server .NET data
provider classes are defined in the System.Data.SqlClient namespace.
The SqlDataSource control represents a connection to a relational database such as SQL Server or Oracle database, or
data accessible through OLEDB or Open Database Connectivity (ODBC). Connection to data is made through two
important properties ConnectionString and ProviderName.
The following code snippet provides the basic syntax of the control:
<asp:SqlDataSource runat="server" ID="MySqlSource"
ProviderName='<%$ ConnectionStrings:LocalNWind.ProviderName %>'
ConnectionString='<%$ ConnectionStrings:LocalNWind %>'
SelectionCommand= "SELECT * FROM EMPLOYEES" />
<asp:GridView ID="GridView1" runat="server" DataSourceID="MySqlSource" />

Methods:
ToString() Returns a string that represents the current object.
(Inherited from Object)
DataBind() Binds a data source to the invoked server control and all its child controls.
(Inherited from Control)
Focus() Sets input focus to the control.
(Inherited from DataSourceControl)
Insert() Performs an insert operation using the InsertCommand SQL string and any parameters that are in
the InsertParameters collection.
Delete() Performs a delete operation using the DeleteCommand SQL string and any parameters that are in
the DeleteParameters collection.
Attributes:
ID Gets or sets the programmatic identifier assigned to the server control.
(Inherited from Control)
ViewState Gets a dictionary of state information that allows you to save and restore the view state of a server
control across multiple requests for the same page.
ProviderName Gets or sets the name of the .NET Framework data provider that the SqlDataSource control uses to
connect to an underlying data source.
Adapter Gets the browser-specific adapter for the control.

b) ObjectDataSource
Designed to work with objects. The ObjectDataSource Control enables user-defined classes to associate the output of
their methods to data bound controls. The programming interface of this class is almost same as the SqlDataSource
control.
Attributes:
Adapter Gets the browser-specific adapter for the control.(Inherited from Control)

ID Gets or sets the programmatic identifier assigned to the server control.

BindingContainer Gets the control that contains this control's data binding.
TypeName Gets or sets the name of the class that the ObjectDataSource object represents.
Methods:
DataBind() Binds a data source to the invoked server control and all its child controls.

Delete() Performs a delete operation by calling the method that is identified by the DeleteMethod property
with any parameters that are in the DeleteParameters collection.

Dispose() Enables a server control to perform final clean up before it is released from memory.
Focus() Sets input focus to the control.
Select() Retrieves data from the underlying data storage by calling the method that is identified by
the SelectMethod property with the parameters in the SelectParameters collection.

c) XmlDataSource: Designed to work with XML documents. XML Data Source (XmlDataSource) control is a new
control added to ADO.NET data source controls .
XmlDataSource control is a data source control that presents XML data to data-bound controls. The XmlDataSource
control can be used by data-bound controls to display both hierarchical and tabular data. The XmlDataSource control is
typically used to display hierarchical XML data in read-only scenarios.
Attributes:
Data Gets or sets a block of XML data that the data source control binds to.
ViewState Gets a dictionary of state information that allows you to save and restore the view state of a server
control across multiple requests for the same page.
Methods:
OnLoad(EventArgs) Raises the Load event.
Save() Saves the XML data currently held in memory by the XmlDataSource control to disk if
the DataFile property is set.

d) AccessDataSource
Designed to work with Microsoft Access. It uses OleDb data provider internally. OleDb data provider classes are
defined in the System.Data.OleDb namespace. The AccessDataSource control represents a connection to an Access
database. It is based on the SqlDataSource control and provides simpler programming interface.
The AccessDataSource control opens the database in read-only mode. However, it can also be used for performing
insert, update, or delete operations. This is done using the ADO.NET commands and parameter collection.
Methods:
ApplyStyleSheetSkin(Page) Applies the style properties that are defined in the page style sheet to the
control.
ClearCachedClientID() Sets the cached ClientID value to null.
Attributes:
DataFile Gets or sets the location of the Microsoft Access .mdb file.

e)Li nq DataSource : It allows binding to the results of a Linq-to-SQL query.


The LinqDataSource control enables you to use LINQ in an ASP.NET Web page by setting properties in markup text.
The LinqDataSource control uses LINQ to SQL to automatically generate the data commands. Enables the use of
Language-Integrated Query (LINQ) in an ASP.NET Web page through markup text to retrieve and modify data from a
data object.
Attribute:
AutoSort Gets or sets a value that indicates whether the LinqDataSource control supports sorting the data at run
time.
GroupBy Gets or sets a value that specifies which properties are used for grouping the retrieved data.
Methods:
Update(IDictionary, IDictionary, Performs an update operation.
IDictionary)

13. Explain the following Controls with their purpose, attributes, and methods: (any two) (6)
a) DataList: DataList is a Databound control to display and manipulate data in a web application. It is a composite
control that can combine other ASP.Net controls and it is present in the form. The DataList appearance is controlled by
its template fields.
Frequently used properties with DataList
b) GridView : DataGridView is very powerful and flexible control for displaying records in a tabular (row-column)
form. Here I am describing a different way of databinding with a DataGridView control. The GridView control is used
to display the values of a data source in a table. Each column represents a field, while each row represents a record. The
GridView control supports the following features: Binding to data source controls, such as SqlDataSource.properties
Adapter Gets the browser-specific adapter for the control.
BackColor Gets or sets the background color of the Web server control.
(Inherited from WebC
BorderColor Gets or sets the border color of the Web control.
(Inherited from WebControl)
BorderStyle Gets or sets the border style of the Web server control.
(Inherited from WebControl)
BorderWidth Gets or sets the border width of the Web server control.
Caption Gets or sets the text to render in an HTML caption element in a GridView control. This property is
provided to make the control more accessible to users of assistive technology devices.
Methods:
TrackViewState() Tracks view-state changes to the GridView control so they can be stored in the
control's StateBag object. This object is accessible through the ViewState property.

c)FormView : Displays the values of a single record from a data source using user-defined templates.
The FormView control allows you to edit, delete, and insert records.

d) DetailsView: Displays the values of a single record from a data source in a table, where each data row represents a
field of the record. The DetailsView control allows you to edit, delete, and insert records.

e)ListView : Displays the values of a data source by using user-defined templates. The ListView control enables users
to select, sort, delete, edit, and insert records.
Attributes Gets the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the
control.

f)DataPager : Provides paging functionality for data-bound controls that implement


the IPageableItemContainer interface, such as the ListView control.
UNIT3
1. What are PHP tags? List two types of PHP tags with an example for each.
PHP Tags
The symbols (<?php and ?>) are called PHP tags. They tell the web server where the PHP code starts and finishes.
Any text between the tags is interpreted as PHP. Any text outside these tags is treated as normal HTML. The PHP
tags allow you to escape from HTML.
Types of PHP tags
• Short style
<? echo ‘<p>Order processed.</p>’; ?>.It is the default tag that PHP developer use to code PHP. This tag style
is the simplest and follows the style of a Standard Generalized Markup Language (SGML) processing
instruction.
• XML style
<?php echo ‘<p>Order processed.</p>’; ?>. . This tag style can be used with Extensible Markup Language
(XML) documents. If you want to serve XML on your site, we should use this style of tag.
• Short style
<script language=’php’> echo ‘<p>Order processed.</p>’; </script>. This tag style is the longest and will be
familiar if you’ve used JavaScript or VBScript. It can be used if we are using an HTML editor that
gives problems with the other tag styles.
• ASP style
<% echo ‘<p>Order processed.</p>’; %>. This tag style is the same as used in Active Server Pages (ASP) or
ASP.NET. You can use it if you have enabled the asp tags configuration setting.
2.List any two data types used in PHP with its purpose.(any2)
• Integer—Used for whole numbers
• Float (also called double)—Used for real numbers
• String—Used for strings of characters
• Boolean—Used for true or false values
• Array—Used to store multiple data items
• Object—Used for storing instances of classes

3.How do you declare and use constants in PHP? Give an example.


We can readily change the value stored in a variable and also declare constants.
Declaring Constants
Constant stores a value just like a variable, but its value is set once and then cannot be changed elsewhere in the script.
For example, you might store the prices for each item on sale as a constant. You can define these constants using the
define function:
define (‘TIREPRICE’, 100);
define (‘OILPRICE’, 10);
define (‘SPARKPRICE’, 4);
Now add these lines of code to your script. You now have three constants that can be used to calculate the total of the
customer’s order.
Use constants
when you refer to a constant, it does not have a dollar sign in front of it. If you want to use the value of a constant, use
its name only.
For example:
echo TIREPRICE;
5.What are superglobals in PHP? List any two of them
Superglobals:
super globals or auto globals and can be seen everywhere, both inside and outside functions. They have their own scope rules.
(any 2)
■ $_GET—An array of variables passed to the script via the GET method
■ $_POST—An array of variables passed to the script via the POST method
■ $_SERVER—An array of server environment variables
■ $_COOKIE—An array of cookie variables
■ $_FILES—An array of variables related to file uploads
■ $_ENV—An array of environment variables
■ $_REQUEST—An array of all user input including the contents of input including
$_GET, $_POST, and $_COOKIE
■ $_SESSION—An array of session variables.

6.How do you suppress an error in PHP? Give an example.


We can supress an error by using the error suppression operator (@) in front of any expression. Any expression that
generates or has a value.
For example,
$a = @(57/0);
Without the @ operator, this line generates a divide-by-zero warning. With the operator included, the error is
suppressed.
If you are suppressing warnings in this way, you need to write some error handling code to check when a warning has
occurred. If you have PHP set up with the track_errors feature enabled in php.ini, the error message will be stored in the
global variable $php_errormsg.
7.What is the purpose of type operator in PHP? Give an example
The Type Operator
There is one type operator: instance of. The instance of operator allows you to check whether an object is an instance of a
particular class or not.
For example:
class sampleClass{};
$myObject = new sampleClass();
if ($myObject instanceof sampleClass)
echo “myObject is an instance of sampleClass”;
8. List any two type-setting functions of PHP with their purpose?
1. gettype()
To use gettype(), you pass it a variable. It determines the type and returns a string containing the type name:
bool, int, double (for floats), string, array, object, resource, or NULL. It returns unknown type if it is not one of the
standard types.
Syntax
string gettype(mixed var);
2.settype()
To use settype(), you pass it a variable for which you want to change the type and a string containing the
new type for that variable from the previous list.
Syntax
bool settype(mixed var, string type);

9. What are the statements used to break a control structure in PHP? Give an example.
If you want to stop executing a piece of code, you can choose from three approaches, depending on the effect you are trying
to achieve.
• If you want to stop executing a loop, you can use the break. If you use the break statement in a loop, execution of the
script will continue at the next line of the script after the loop.
• Exaple:
<?php
for($i=1;$i<=10;$i++){
echo "$i <br/>";
if($i==5){
break;
}
}
?>
Output:
1
2
3
4
5

• If you want to jump to the next loop iteration, you can instead use the continue
statement.
• Example:
<?php
$x=1;
while ($x<10){
$x++;
if ($x%2==0)
continue;
echo "x = $x" . "\n";
}
?>
Output
x=3
x=5
x=7
x=9
• If you want to finish executing the entire PHP script, you can use exit.
This approach is t ypically useful when you are performing error checking. For example,
if($totalqty == 0){
echo "You did not order anything on the previous page!<br />";exit;
}
The call to exit stops PHP from executing the remainder of the script.

10.Why do you use feof() function in PHP? Give an example.


feof stands for File End Of File- you read from the file until EOF is reached.
The while loop tests for the end of the file using the feof() function:
while (!feof($fp))
The feof() function takes a file , handle it as single parameter. It returns true if the file pointer is at the end of the file. In this
case, you read from the file until EOF is reached.
11. Write the purpose of fgets() function in PHP with an example?
We use the fgets() function to read from the file. This function reads one line at a time from a file. In this case, it
reads until it encounters a newline character (\n), encounters an EOF, or has read 998 bytes from the file. The maximum
length read is the length specified minus 1 byte.
Example: $order= fgets($fp, 999);
12. How do you initialise numerically indexed and associate arrays in PHP? Give an example.
• Initializing Numerically Indexed Arrays
PHP index is represented by number which starts from 0. We can store number, string and object in the PHP
array. All PHP array elements are assigned to an index number by default.
• Example
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
Season are: summer, winter, spring and autumn
• Initializing Associative Array
We can associate name with each array elements in PHP using => symbol.
• Example
<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>
Output:
Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000
13. List any two array operators used in PHP with their purpose.

14. What is the purpose of array_multisort() function? Give an example.


array_multisort() function
The array_multisort() is an built-in function in PHP. This function is used to sort multiple arrays at once or a multi-
dimensional array with each dimension. This function was introduced in PHP 4.0.
Example
<?php
$players = array("sachin", "ganguly", "virat", "dhoni", "yuvraj", "umesh");
array_multisort($players);
print_r($players);
?>
Output:
Array
(
[0] =>dhoni
[1] =>ganguly
[2] =>sachin
[3] =>umesh
[4] =>virat
[5] =>yuvraj
)
15. Write the purpose of shuffle() and array_reverse() functions in PHP?
• shuffle( ) function
The PHP shuffle( ) function is used to randomize the order of the elements in the array. The function assigns new
keys to the elements in an array.
• Example
<?php
$subject=array("a"=>"java","b"=>"dbms","c"=>"os","d"=>"compiler","e"=>"networking?);
shuffle($subject);
print_r($subject);
?>
• Output- Every time output is random
Array
(
[0] => networking
[1] =>dbms
[2] =>os
[3] => compiler
[4] => java
)
• Using array_reverse()
The function array_reverse() takes an array and creates a new one with the same contents in reverse order. The
array_reverse( ) function is used to reverse the order of the elements in an array.
• Example
<?php
$num= array(100,200,300,400,500);
$x = array_reverse($num,true);
$y = array_reverse($num);
print_r($x);
print_r($y);
?>
OUTPUT
Array ([4] => 500 [3] => 400 [2] => 300 [1] => 200 [0] => 100)
Array ([0] => 500 [1] => 400 [2] => 300 [3] => 200 [4] => 100)
16. What do you mean by trim() function in PHP? Give an example.
The trim() function strips whitespace from the start and end of a string and returns the resulting string.
Example
<?php
$str = "\nHello PHP\n";
echo "Without trim() function: " . $str;
echo "<br>";
echo "With trim() function:" . trim($str);
?>
Output:
Without trim() function: Hello PHP
With trim() function:Hello PHP
17. What is the purpose of htmlspecialchars() function? Give an example.
The htmlspecialchars() function converts special characters into HTML entities. It is the in-built function of PHP, which
converts all pre-defined characters to the HTML entities.
Example
<? php
//string conversion example of htmlspecialchars () function
$str = "This is <i>italic</i> text.";
echo htmlspecialchars($str, ENT_QUOTES); //Will convert both single and double
quotes.
?>

18. Write the purpose of nl2br() function with an example.


PHP string nl2br() is predefine function which is used to insert HTML line break before all newlines in a string. It returns
string with <br \> or <br> before all newlines (\r\n, \n\r, \n and \r).
Example
<?php
echo "Your string is: Hello .\ n PHP. \ n User"."<br>";
echo "By using 'nl2br()' function:".nl2br(" Hello .\nPHP.\n User");
?>
Note: Generating valid HTML markup by using 'is_xhtml' parameter.
Output:
Your string is: Hello .\ n PHP. \ n User
By using 'nl2br()' function: Hello .
PHP.
User
19. What is strlen() function? Give an example.
The strlen() function is used to find the length of string or returns the length of a string including all
the whitespaces and special character.
Example
<?php
$str = 'Oh my God';
echo "Your String is:".$str;
echo "<br>";
echo "By using 'strlen()' function:".strlen($str);
// output =9 [including whitespace]
?>
Output:
Your String is:Oh my God
By using 'strlen()' function:9

20. Write the purpose of strops() and strrpos() functions?


strops() and strrpos() a case-sensitive function of PHP, which means it treats uppercase and lowercase characters
differently.
• strops()
The strops() is in-built function of PHP. It is used to find the position of the first occurrence of a string inside
another string or substring in a string.The strpos() function has the following prototype:
int strpos(string haystack, string needle, int [offset] );
The integer returned represents the position of the first occurrence of the needle within the haystack. The first character
is in position 0 as usual.
Example
<?php
$str1="Hello php";
$str2=" Hello php user";
echo "First string is: ".$str1;
echo "<br>";
echo "First string is: ".$str2;
echo "<br>";
echo "By using 'strpos()' function:".strpos("$str1,$str2","php");
//Find the position of the first occurrence of "php" inside the string
?>
Output:
First string is: Hello php
First string is: Hello php user!
By using 'strpos()' function:6
• strrpos()
The strrpos() is an in-built function of PHP which is used to find the position of the last occurrence of a substring
inside another string.
strrpos ($string, $search, $start)
example
<?php
function Search($search, $string){
$position = strrpos($string, $search, 5);
if ($position == true){
return "Found at position " . $position;
}
else{
return "Not Found";
}
}
$string = "Welcome to GeeksforGeeks";
$search = "Geeks";
echo Search($search, $string);
?>
OUTPUT
Found at position 19

21. List any two predefined character classes with their matches used in regular expressions?
Table 4.3 Character Classes for Use in POSIX-Style Regular Expressions Class
Matches
[[:alnum:]] Alphanumeric characters [[:alpha:]]
Alphabetic characters [[:lower:]]
Lowercase letters [[:upper:]]
Uppercase letters [[:digit:]]
Decimal digits [[:xdigit:]]
Hexadecimal digits [[:punct:]]
Punctuation [[:blank:]] Tabs and
spaces [[:space:]] Whitespace characters [[:cntrl:]]
Control characters [[:print:]] All
printable characters
[[:graph:]] All printable characters except for space
22. List with their purpose, any two special characters used in regular expressions to specify multiple occurrences of a
particular string?
. The * symbol means that the pattern can be repeated zero or more times, and the + symbol means that the pattern can
be repeated one or more times. The symbol should appear directly after the part of the expression that it applies to. For
example,
[[:alnum:]]+
means “at least one alphanumeric character.”
23. List any two metacharacters used in PCRE regular expressions outside square brackets with their purpose?
Table 4.4 Summary of Special Characters Used in POSIX Regular Expressions Outside Square

brackets
Character Meaning
\ Escape character
^ Match at start of string
$ Match at end of string
. Match any character except newline (\n)
| Start of alternative branch (read as OR)
( Start subpattern
) End subpattern
* Repeat zero or more times
+ Repeat one or more times
{ Start min/max quantifier
} End min/max quantifier
? Mark a subpattern as optional
5Marks
1. How do you access Form variables in PHP? Explain with an example. (5)
Accessing Form Variables
• Within our PHP script, we can access each form field as a PHP variable whose name relates to the name of the form
field. We can recognize variable names in PHP because they all start with a dollar sign ($).
• Depending on our PHP version and setup, we can access the form data via variables in three ways. These methods
do not have official names, so we have nicknamed them as short, medium, and long style. In any case each form field
on a page submitted to a PHP script is available in the script.
• We can access the contents of the field tireqty in the following ways:
$ tireqty // short style
$_POST [‘tireqty’] // medium style
$HTTP_POST_VARS [‘tireqty’] // long style
We can use different approaches to our code
• Short style ($tireqty)
• I t is convenient but requires the register globals configuration setting be turned on. For security reasons, this
setting is turned off by default.
• When we use the short style, the names of the variables in the script are the same as the names of the form
fields in the HTML form.
• There is no need to declare the variables or take any action to create these variables in the script. They are
passed into the script, essentially as arguments are passed to a function.
• If we are using this style, we can just use a variable such as $ tireqty. The field tireqty in the form creates
the variable $ tireqty in the processing script.
• Medium style ($_POST [‘tireqty’])
• It is the recommended approach.
• Medium style involves retrieving form variables from one of the arrays $_POST, $_GET, or $_REQUEST.
$_POST is an array containing data submitted via an HTTP POST request-that is, the form method was
set to POST.
• One of the $_GET or $_POST arrays holds the details of all the form variables. Which array is used
depends on whether the method used to submit the form was GET or POST, respectively.
• If the form was submitted via the POST method, the data entered in the tireqty box will be stored
in $_POST['tireqty']. If the form was submitted via GET, the data will be in $_GET['tireqty']. In either
case, the data will also be available in $_REQUEST['tireqty'].
• Long style ($HTTP_POST_VARS[‘tireqty’]) is the most verbose. Note, however, that it is deprecated and is therefore
likely to be removed in the long term. This style used to be the most portable but can now be disabled via the
register_long_arrays configuration directive, which improves performance.
2. Write a note on scope of variables in PHP? (5)

The term scope refers to the places within a script where a particular variable is visible. The six basic scope rules
in PHP are as follows:
• Built-in super global variables are visible everywhere within a script.
• Constants, once declared, are always visible globally; that is, they can be used inside and outside functions.
• Global variables declared in a script are visible throughout that script, but not inside functions.
• Variables inside functions that are declared as global refer to the global variables of the same name.
• Variables created inside functions and declared as static are invisible from outside the function but keep their
value between one execution of the function and the next.
• Variables created inside functions are local to the function and cease to exist when the function terminates.
• Example
<?php
$x = 5;
$z=3; // global scope
function myTest() {
// using x inside this function will generate an error
echo "Global variable x inside function is: $x<br/>";
$y=2;//local scope
echo "Local variable y inside function is: $y<br/>";
global $z;
echo "Global variable z using global keyword inside function is: $z<br/>";
}
myTest();
echo "<p>Global variable x outside function is: $x</p>";
echo "<p>Local variable y outside function is: $y</p>";
echo "<p>Global variable z using global keyword outside function is: $z</p>";
?>
OUTPUT
Global variable x inside function is:
Local variable y inside function is: 2
Global variable z using global keyword inside function is: 3
Global variable x outside function is: 5
Local variable y outside function is:
Global variable z using global keyword outside function is: 3

<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?>
OUTPUT
0
1
2
3. How do you test and set variable types? Explain with an example for each. (4)
Testing and Setting Variable Types
Most of the variable functions are related to testing the type of function. The two most general are gettype()
and settype().
• gettype()
To use gettype(),pass a variable. It determines the type and returns a string containing the type name: bool, int, double
(for floats), string, array, object, resource, or NULL. It returns unknown type if it is not one of the standard types.
Syntax:
string gettype(mixed var);

• settype().
To use settype(), pass a variable for which you want to change the type and a string containing the new type for that
variable from the previous list.
Syntax:
bool settype(mixed var, string type);

• Example
$a = 56;
echo gettype(‘Before=’,$a).’<br />’;
settype($a, ‘double’);
echo gettype(‘After=’,$a).’<br />’;
• Output
Before=integer
After=double
• When gettype() is called the first time, the type of $a is integer. After the call to settype(), the type is
changed to double.

4. List and explain any six different file modes for fopen() in PHP? (6)
Summary of File Modes for fopen()

Mode Mode Name Meaning

r Read Open the file for reading, beginning from the start of the file.

r+ Read Open the file for reading and writing, beginning from the start of the file.
w Write Open the file for writing, beginning from the start of the file. If the file already
exists, delete the existing contents. If it does not exist, try to create it.

w+ Write Open the file for writing and reading, beginning from the start of the file. If the file
already exists, delete the existing contents. If it does not exist, try to create it.

x Cautious write Open the file for writing, beginning from the start of the file. If the file already
exists, it will not be opened, fopen() will return false, and PHP will generate a
warning.

x+ Cautious write Open the file for writing and reading, beginning from the start of the file. If the file
already exists, it will not be opened, fopen() will return false, and PHP will generate
a warning.

a Append Open the file for appending (writing) only, starting from the end of the existing
contents, if any. If it does not exist, try to create it.

a+ Append Open the file for appending (writing) and reading, starting from the end of the
existing contents, if any. If it does not exist, try to create it.

b Binary Used in conjunction with one of the other modes. You might want to use this
mode if your file system differentiates between binary and text files. Windows
systems differentiate; Unix systems do not. The PHP developers recommend you
always use this option for maxi- mum portability. It is the default mode.

t text Used in conjunction with one of the other modes. This mode is an option only in
Windows systems. It is not recommended except before you have ported your code
to work with the b option.
UNIT-4
2Marks
1. How do you declare a constructor in PHP? Give an example.
Constructors
A contractor is called when an object is created, and it also normally performs useful initialization tasks such as
setting attributes to sensible starting values or creating other objects needed by this object.
Declaring
A constructor is declared in the same way as other operations, but it has the same name as the class. Though we
can manually call the constructor, its main purpose is to be called automatically when an object is created.
Example: The following code declares a class with a constructor
class classname
function classname ($param)
{
echo “Constructor called with parameter”. $param.”<br/>”;
}
}
2. What are destructors in PHP? Give an example.
Destructors
The opposite of a constructor is a destructor. They allow you to have some functionality that will be executed just
before a class is destroyed, which will occur automatically when all references to a class have been unset or fallen
out of scope.
Example
<?php
class myclass{
function __construct(){
echo "object is initialized\n";
}
function __destruct(){
echo "object is destroyed\n";
}
}
$obj=new myclass();
?>
Output
object is initialized
object is destroyed
3. What are access modifiers? List three different access modifiers supported in PHP.
Access modifiers
PHP uses access modifiers. They control the visibility of attributes and methods, and are placed in front of attribute
and method declarations.
PHP supports the following three different access modifiers(Mention)
• The default option is public, meaning that if you do not specify an access modifier for an attribute or method, it
will be public. Items that are public can be accessed from inside or outside the class.
• The private access modifier means that the marked item can be accessed only from inside the class.
• The protected access modifier means that the marked item can be accessed only from inside the class. It also
exists in any subclasses.
4. What do you mean by overriding in PHP?
Overriding
We know a subclass declares new attributes and operations. It is also valid and sometimes useful to redeclare the
same attributes and operations. We might do this to give an attribute in the subclass a different default value to
the same attribute in its superclass, or to give an operation in the subclass different functionality to the same
operation in its superclass. This is called overriding.
5. Write an example to declare an interface with class definition which implements the interface?
A class uses the implements keyword to inherit from an interface and implement the methods declared in the
interface.
Example:
<?php
// class declaration
class Studytonight implements WebApp {
// methods definition
public function login($email, $password) {
echo "Login the user with email: " . $email;
}
public function register($email, $password, $username) {
echo "User registered: Email=".$email." and Username=".$username;
}
public function logout() {
echo "User logged out!";
}
}
?>
6. What are traits? How do you create them?
Traits are like interfaces in Java. But they are more powerful than the interface in Java because in the traits you
are allowed to implement the members. Traits can have methods(both abstract and non-abstract), and fields as its
members.
Traits are created using trait keywords.
Syntax:
trait Trait_Name{
// Fields..
// Methods..
}
Example:

// Scala program to illustrate how to create traits


trait MyTrait
{
def pet
def pet_color
}
// MyClass inherits trait
class MyClass extends MyTrait
{
// Implementation of methods of MyTrait
def pet()
{
println("Pet: Dog")
}
def pet_color()
{
println("Pet_color: White")
}
// Class method
def pet_name()
{
println("Pet_name: Dollar")
}
}
object Main
{
// Main method
def main(args: Array[String])
{
val obj = new MyClass();
obj.pet();
obj.pet_color();
obj.pet_name();
}
}

Output:
Pet: Dog
Pet_color: White
Pet_name: Dollar

7. What do you mean by Per-Class Constants in PHP? Give an example.


Per-Class Constants
PHP allows for per-class constants. This constant can be used without your needing to instantiate the class, as in
this example:
<?php
Class Math{
Const pi=3.14159;
}
Echo “Math::pi=”.Math::”\n”;
You can access the per-class constant by using the ::operator to specify to which class which constant belongs
to, as done in this example.
8. What are static methods in PHP? Give an example.
Static Methods
PHP allows the use of the static keyword. It is applied to methods to allow them to be called without instantiating
the class. This is the method equivalent of the per-class constant Idea. For example, consider the Mathclass created
in the preceding section. You could add a squared()function to it and invoke it without instantiating the class as
follows:
class Math
{
static function squared($input)
{
return $input*$input;
}
}
echo Math::squared(8);
Note that you cannot use the this keyword inside a static method because there may be no object instance to refer
to.
9. Write the purpose of instanceof and type hinting in PHP?
instanceof
The instanceof keyword allows you to check the type of an object. You can check whether an object is an instance
of a particular class, whether it inherits from a class, or whether it implements an interface. The instanceof keyword
is effectively a conditional operator.
e.g. If b is instance of class B
($b instanceof B) would be true.
($g instanceof B) would be false.
type hinting
Normally, when you pass a parameter to a function in PHP, you do not pass the type of that parameter.
With class type hinting, you can specify the type of class that ought to be passed in, and if that is not the type
actually passed in, an error will be triggered. The type checking is equivalent to instanceof.
For example, consider the following function:
function check_hint(B $someclass)
{
//...
}
This example suggests that $someclass needs to be an instance of class B. If you then pass in
an instance of class A as check_hint($a); you will get the following fatal error:
Fatal error: Argument 1 must be an instance of B
Note that if you had hinted A and passed in an instance of B, no error would have occurred because B inherits
from A.
10. What do you mean by clone keyword in PHP? Give an example.
Cloning Objects
The clone keyword, which allows you to copy an existing object, can also be used in PHP. If any of the properties
was a reference to another variable or object, then only the reference is copied. Objects are always passed by
reference, so if the original object has another object in its properties, the copy will point to the same object. This
behaviour can be changed by creating a __clone() method in the class.
Example:
<?php
class MyClass
{
public $color;
public $amount;
}
$obj= new MyClass();
$obj->color= "red";
$obj->amount= 5;
$copy= clone $obj;
print_r($copy);
?>
11. What are abstract classes in PHP? Give an example?
Using Abstract Classes
PHP offers abstract classes, which cannot be instantiated, as well as abstract methods, which provide the signature
for a method but no implementation.
For instance:
abstract operationX($param1, $param2);
Any class that contains abstract methods must itself be abstract, as shown in this example:
abstract class A
{
abstract function operationX($param1, $param2);
}
The main use of abstract methods and classes is in a complex class hierarchy where you want to make sure each
subclass contains and overrides some particular method; this can also be done with an interface.
12. What is the use of __autoload() function in PHP? Give an example
Using __autoload()
autoload() is a special functions in PHP. It is not a class method but a standalone function; that is, you declare
it outside any class declaration. If you implement it, it will be automatically called when you attempt to instantiate
a class that has not been declared.
The main use of autoload() is to try to include or require any files needed to instantiate the required class.
Consider this example:
Function __autoload($name)
{
include_once $name.".php";
}
This implementation tries to include a file with the same name as the class.
13. Give an example for procedural and object-oriented syntax to connect MYSQL using mysqli.
Setting Up a Connection
The PHP library for connecting to MySQL is called mysqli (the i stands for improved). When using the mysqli
library in PHP, you can use either an object-oriented or procedural syntax.
Object-oriented syntax to connect to the MySQL server:
@ $db = new mysqli('localhost', 'root', 'pass@me’, 'librarybook');
This line instantiates the mysqli class and creates a connection to host localhost with username root, and password
pass@me. The connection is set up to use the database called library. Using this object-oriented approach, we can
now invoke methods on this object to access the database.
Procedural syntax to connect to the MySQL server:
@ $db = mysqli_connect('localhost', 'root', 'pass@me', 'hotelroom');
This function returns a resource rather than an object. This resource represents the connection to the database, and
if we are using the procedural approach, we should pass this resource into
all the other mysqli functions. This is very similar to the way the file-handling functions, such as fopen(), work.

14. Write the purpose of mysqli_query() with an example.


Querying the Database
To perform the query, we can use the mysqli_query() function. Before doing this, however, it’s a good idea to set
up the query we want to run:
$query = "select * from books where ".$searchtype." like '%".$searchterm."%'";
In this case, you search for the user-input value ($searchterm) in the field the user specified ($searchtype).
We can now run the query(object-orient):
$result = $db->query($query);
We can also run the query(procedural) as:
$result = mysqli_query($db, $query);
The object-oriented version returns a result object; the procedural version returns a result resource. Either way,
we can store the result in a variable ($result) for later use. This function returns false on failure.

15. Why do you need Prepared Statements? Give an example.


Using Prepared Statements
• The mysqli library supports the use of prepared statements. They are useful for speeding up execution
when we are performing large numbers of the same query with different data. They also protect against
SQL injection-style attacks.
• The basic concept of a prepared statement is that we send a template of the query we want to execute to
MySQL and then send the data separately. We can send multiple slots of the same data to the same
prepared statement; this capability is particularly useful for bulk inserts.
• We can use prepared statements in the insert_book.php script, as follows:
$query = "insert into books(Author_name,Title,Price)values(?, ?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->bind_param("ssd", $author, $title, $price);
$stmt->execute();
echo $stmt->affected_rows.' book inserted into database.';
$stmt->close();
16. Write proper statements to disconnect from the database using PHP?
Disconnecting from the Database
• We can free up result set by calling either $result->free(); Or mysqli_free_result($result);
• We can then use $db->close(); or mysqli_close($db); to close a database connection. Using this command
isn’t strictly necessary because the connection will be closed when a script finishes execution anyway.

17. List any two directives used with PHP while uploading files with their purpose.(any 2)
Directive Description Default Value
file_uploads Controls whether HTTP file uploads are allowed. Controls On
whether HTTP file uploads are allowed
upload_tmp_dir Indicates the directory where uploaded files will temporarily be NULL
stored while they are waiting to be processed. If this value is not
set, the system default will be used.

upload_max_filesize Controls the maximum allowed size for uploaded files. If a file 2M
is larger than this value, PHP will write a 0 byte placeholder file
instead.
post_max_size Controls the maximum size of POST data that PHP will accept. 8M
This value must be greater than the value for the
upload_max_filesize directive, since it is the size for all of the
post

18. List any two directives used in session upload progress with their default values.

19. Write the purpose of dirname($path) and basename($path) functions.


dirname($path)
The dirname($path) functions return the directory part of the path
basename($path)
The basename($path)function returns filename part of the path.
This information could be useful for the directory browser, particularly if we want to begin to build up a
complex directory structure of content based on meaningful directory names and filenames.

20. How do you create and delete directories in PHP?


Creating and Deleting Directories
We can use the PHP functions mkdir() and rmdir() to create and delete directories. We can create or delete
directories only in that paths where the user script has the access.
Using mkdir() is more complicated than we think. It takes two parameters: the path to the desired directory
(including the new directory name) and the permissions that we would like to have the directory.
Here’s an example:
mkdir(“/tmp/testing”, 0777);

The rmdir() function deletes a directory, as follows:


rmdir(“/tmp/testing”); or rmdir(“c:\\tmp\\testing”);
The directory you are trying to delete must be empty.

5marks.
1. How do you access the attributes and operations of a class in PHP? Explain an example. (5)
Class Attributes : the classes need attributes and operations. You create attributes by declaring variables within
a class definition using keywords that match their visibility: public, pri vate, or protected. The following code
creates a class called classname with two public attributes, $attribute1 and $attribute2:
class classname{
public $attribute1; public $attribute2;
}
Within a class, you have access to a special pointer called $this. If an attribute of your current class is called
$attribute, you refer to it as $this->attribute when either set- ting or accessing the variable from an operation within
the class.
The following code demonstrates setting and accessing an attribute within a class:
class classname {
public $attribute; function operation($param) {
$this->attribute = $param echo $this->attribute;
}}
This example does not restrict access to the attributes, so you can access them from outside the class as follows:
class classname
{
public $attribute;
}
$a = new classname();
$a->attribute = "value";
echo $a->attribute;
It is not generally a good idea to directly access attributes from outside a class. If, instead of accessing the
attributes of a class directly, you write accessor functions, you can make all your accesses through a single section
of code. When you initially write your accessor functions, they might look as follows:
class classname {
public $attribute;
function get($name) {
return $this->$name;
}
function set ($name, $value)
{
$this->$name = $value;
}
You create operations by declaring functions within the class definition. The following code creates a
class named classname with two operations that do nothing. The operation operation1() takes no
parameters, and operation2() takes two parameters:
class classname {
function operation1()
{}
function operation2($param1, $param2) {
You can call class operations in much the same way that you call class attributes. Say you have the class
class classname {
function operation1()
{}
function operation2($param1, $param2)
{}
} and create an object of type classname called $a as follows: $a = new classname();
You then call operations the same way that you call other functions: by using their name and placing any
parameters that they need in brackets. Because these operations belong to an object rather than normal
functions, you need to specify to which object they belong. The object name is used in the same way as an
object’s attributes, as follows:
$a->operation1();
$a->operation2(12, "test");
If the operations return something, you can capture that return data as follows:
$x = $a->operation1();
$y = $a->operation2(12, "test");

2. How do you implement inheritance in PHP? Explain with an example. (5)


Implementing Inheritance in PHP: Inheritance allows you to create a hierarchical relationship between classes
using subclasses. A subclass inherits attributes and operations from its superclass
If the class is to be a subclass of another, you can use the extends keyword to specify this use. The following
code creates a class named B that inherits from some previously defined class named A:
class B extends A
{
public $attribute2; function operation2()
{}}
If the class A was declared as
class A
{
public $attribute1; function operation1()
{}}
all the following accesses to operations and attributes of an object of type B would be valid:
$b = new B();
$b->operation1();
$b->attribute1 = 10;
$b->operation2();
$b->attribute2 = 10;
Note that because class B extends class A, you can refer to operation1() and $attribute1, although they
were declared in class A. As a subclass of A, B has all the same functionality and data. In addition, B
has declared an attribute and an operation of its own.
It is important to note that inheritance works in only one direction. The subclass or child inherits
features from its parent or superclass, but the parent does not take on features of the child. This means
that the last two lines in this code are wrong:
$a = new A();
$a->operation1();
$a->attribute1 = 10;
$a->operation2();
$a->attribute2 = 10;
The class A does not have an operation2() or an attribute2.

3. Explain the concept of Overriding in PHP with an example? (6)


Overriding : We have shown a subclass declaring new attributes and operations. It is also valid and sometimes
useful to redeclare the same attributes and operations. You might do this to give an attribute in the subclass a
different default value to the same attribute in its superclass or to give an operation in the subclass different
functionality to the same operation in its superclass. This action is called overriding.
For instance, say you have a class A:

class A
{
public $attribute = "default value"; function operation()
{
echo "Something<br />"; echo "The value of \$attribute is ".
$this->attribute."<br />";
}
}
If you want to alter the default value of $attribute and provide new functionality for operation(), you can
create the following class B, which overrides $attribute and operation():
class B extends A
{
public $attribute = "different value"; function operation()
{
echo "Something else<br />"; echo "The value of \$attribute is
". $this->attribute."<br />";
}
}
Declaring B does not affect the original definition of A. Now consider the following two lines of code:
$a = new A();
$a -> operation();
These lines create an object of type A and call its operation() function. This produces Something
The value of $attribute is default value proving that creating B has not altered A. If you create an object
of type B, you will get different output. This code
$b = new B(); $b -> operation(); produces
Something else

4. How do you create traits? Explain with an example. (5)


PHP only supports single inheritance: a child class can inherit only from one single parent. So, what if a class
needs to inherit multiple behaviors? OOP traits solve this problem.
Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract
methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or
protected).
Traits are declared with the trait keyword:
Syntax
<?php
trait TraitName {
// some code...
}
?>
To use a trait in a class, use the use keyword:
Syntax
<?php
class MyClass {
use TraitName;
}
?>
Example
<?php
trait message1 {
public function msg1() {
echo "OOP is fun! ";
}
}
class Welcome {
use message1;
}
$obj = new Welcome();
$obj->msg1();
?>

5. What is late static binding? Explain with an example? (4)


Late Static Bindings: Late static bindings allow references to the called class within the context of a static
inheritance; parent classes can use static methods overridden by child classes. The following basic example from
the PHP Manual shows a late static binding in action:
<?php
class A {
public static function who() { echo CLASS ;
}
public static function test() {
static::who(); // Here comes Late Static Bindings
}
}
class B extends A {
public static function who() { echo CLASS ;
}}
B::test(); ?>
The above example will output:
B
Allowing references to classes called at runtime, regardless if they have been overridden, brings additional
object functionality to your classes.

6. How do you implement method overloading in PHP? Explain with an example. (5)
Overloading Methods with call() : We previously looked at a number of class methods with special meanings
whose names begin with a double underscore ( ), such as get(), set(), construct(), and destruct(). Another
example is the method call(), which is used in PHP to implement method overloading.
Method overloading is common in many object-oriented languages but is not as useful in PHP because you tend to
use flexible types and the (easy-to-implement) optional function parameters instead.
To use it, you implement a call() method, as in this example:
public function _call($method, $p)
{
if ($method == "display") { if (is_object($p[0])) {
$this->displayObject($p[0]);
} else if (is_array($p[0])) {
$this->displayArray($p[0]);
} else {
$this->displayScalar($p[0]);
}}}
The call() method should take two parameters. The first contains the name of the method being
invoked, and the second contains an array of the parameters passed to that method. You can then
decide for yourself which underlying method to call. In this case, if an object is passed to method
display(), you call the underlying displayObject() method; if an array is passed, you call
displayArray(); and if something else is passed, you call displayScalar().
To invoke this code, you would first instantiate the class containing this call() method (name it overload) and
then invoke the display() method, as in this example:

$ov = new overload;


$ov->display(array(1, 2, 3)); $ov->display('cat');
The first call to display() invokes displayArray(), and the second invokes displayScalar().
Note that you do not need any underlying implementation of the display() method for this code to work.

7. How do you implement iterators and iterations in PHP? Explain with an example? (7)
Implementing Iterators and Iteration: One clever feature of the object-oriented engine in PHP is that you can
use a foreach() loop to iterate through the attributes of an object as you would an array. Here’s an example:
class myClass
{
public $a = "5"; public $b = "7"; public $c = "9";
}
$x = new myClass; foreach ($x as $attribute)
{
echo $attribute."<br />";
}
If you need more sophisticated behavior than this, you can implement an iterator. To do this, you make the
class that you want to iterate over implement the Iterator Aggregate interface and give it a method called get
Iterator that returns an instance of the iterator class. That class must implement the Iterator interface, which has
a series of methods that must be implemented. An example of a class and iterator is shown in Listing 6.4.
Listing 6.4 iterator.php— A Sample Base Class and Iterator Class
<?php
class ObjectIterator implements Iterator {
private $obj; private
$count; private $currentIndex;
function___construct($obj)
{
$this->obj = $obj;
$this->count = count($this->obj->data);
}
function rewind()
{
$this->currentIndex = 0;
}
function valid()
{
return $this->currentIndex < $this->count;
}
function key()
{
return $this->currentIndex;
} function current()
{
return $this->obj->data[$this->currentIndex];
}
function next()
{
$this->currentIndex++;
}}
class Object implements IteratorAggregate
{
public $data = array();
function construct($in)
{
$this->data = $in;
} function getIterator()
{
return new ObjectIterator($this);
}
}
$myObject = new Object(array(2, 4, 6, 8, 10));

$myIterator = $myObject->getIterator(); for($myIterator->rewind(); $myIterator->valid(); $myIterator-


>next())
{
$key = $myIterator->key();
$value = $myIterator->current(); echo $key."
=> ".$value."<br />";}
?>

The ObjectIterator class has a set of functions as required by the Iterator interface:
■ The constructor is not required but is obviously a good place to set up values for the number of
items you plan to iterate over and a link to the current data item.
■ The rewind() function should set the internal data pointer back to the beginning of the data.
■ The valid() function should tell you whether more data still exists at the current location of the
data pointer.
■ The key() function should return the value of the data pointer.
■ The value() function should return the value stored at the current data pointer.
■ The next() function should move the data pointer along in the data.

The reason for using an iterator class like this is that the interface to the data will not change even if the
underlying implementation changes. In this example, the Iterator Aggregate class is a simple array. If you
decide to change it to a hash table or linked list, you could still use a standard Iterator to traverse it, although
the Iterator code would change.

8. Explain the steps involved in working of web database architecture? (6)


How Web Database Architectures Work
“Designing Your Web Database,” we outlined how web database architectures work. Just to remind you, here are
the steps:
1. A user’s web browser issues an HTTP request for a particular web page. For example, the user might
have requested a search for all the books written by Michael Morgan at Book-O-Rama, using an
HTML form. The search results page is called results.php.
2. The web server receives the request for results.php, retrieves the file, and passes it to the PHP engine
for processing.
3. The PHP engine begins parsing the script. Inside the script is a command to connect to the
database and execute a query (perform the search for books). PHP opens a connection to the MySQL
server and sends on the appropriate query.
4. The MySQL server receives the database query, processes it, and sends the results— a list of
books—back to the PHP engine.
5. The PHP engine finishes running the script. This usually involves formatting the query results nicely
in HTML. It then returns the resulting HTML to the web server.
6. The web server passes the HTML back to the browser, where the user can see the list of books she
requested.
Now you have an existing MySQL database, so you can write the PHP code to perform the preceding steps.

9. Explain the basic steps involved to access (query) a database from the web with necessary example.(8)
Querying a Database from the Web
In any script used to access a database from the Web, you follow some basic steps:
1. Check and filter data coming from the user.
2. Checking and Filtering Input Data
You begin the script by stripping any whitespace that the user might have inadvertently entered at the
beginning or end of his search term. You do this by applying the function trim() to the value of
$_POST['searchterm'] when giving it a shorter name: $searchterm=trim($_POST['searchterm']);
The next step is to verify that the user has entered a search term and selected a search type. Note that
you check whether the user entered a search term after trimming white- space from the ends of
$searchterm. If you arrange these lines in the opposite order, you could encounter situations in which
a user’s search term is not empty and therefore does not create an error message; instead, it is all
whitespace, so it is deleted by trim(): if (!$searchtype || !$searchterm) {
echo "You have not entered search details. Please go back and try again."; exit;
}
3. Set up a connection to the appropriate database.
Setting Up a Connection
The PHP library for connecting to MySQL is called mysqli (the i stands for improved). When using
the mysqli library in PHP, you can use either an object-oriented or procedural syntax.
You use the following line in the script to connect to the MySQL server:
@ $db = new mysqli('localhost', 'bookorama', 'bookorama123', 'books');
This line instantiates the mysqli class and creates a connection to host localhost with username
bookorama, and password bookorama123.The connection is set up to use the database called books.
Using this object-oriented approach, you can now invoke methods on this object to access the
database. connect in a procedural fashion, you use @ $db = mysqli_connect('localhost', 'bookorama',
'bookorama123', 'books');
4. Query the database: To actually perform the query, you can use the mysqli_query() function. Before
doing this, however, it’s a good idea to set up the query you want to run:
$query = "select * from books where ".$searchtype." like '%".$searchterm."%'";
In this case, you search for the user-input value ($searchterm) in the field the user specified
($searchtype).
Notice the use of like for matching rather than equal: it’s usually a good idea to be more tolerant in a
database search.
You can now run the query: $result = $db->query($query);
5. Retrieve the results: A large variety of functions is available to break the results out of the result
object or identifier in different ways. The result object or identifier is the key to accessing the rows
returned by the query. In this example, you counted the number of rows returned and also used the
mysqli_fetch_assoc() function.
When you use the object-oriented approach, the number of rows returned is stored in the num_rows
member of the result object, and you can access it as follows: $num_results = $result->num_rows;
When you use a procedural approach, the function mysqli_num_rows() gives you the number of rows
returned by the query. You should pass it the result identifier, like this: $num_results =
mysqli_num_rows($result);
6.Present the results back to the user:
Disconnecting from the Database
You can free up your resultset by calling either
$result->free(); or mysqli_free_result($result);
You can then use $db->close(); or mysqli_close($db)
These are the steps we followed in the script results.php

10. Create a web page to store Book information such as ISBN, Author, Title and Price accepted by the user to a table
‘Books ‘. (8)
This interface for putting new books into the database could be used by Book-O-Rama’s staff.
newbook.html— HTML for the Book Entry Page
<html>
<head>
<title>Book-O-Rama - New Book Entry</title>
</head>
<body>
<h1>Book-O-Rama - New Book Entry</h1>
<form action="insert_book.php" method="post">
<table border="0">
<tr>
<td>ISBN</td>
<td><input type="text" name="isbn" maxlength="13" size="13"></td>
</tr>
<tr>
<td>Author</td>
<td> <input type="text" name="author" maxlength="30" size="30"></td>
</tr>
<tr>
<td>Title</td>
<td> <input type="text" name="title" maxlength="60" size="30"></td>
</tr>
<tr>
<td>Price $</td>
<td><input type="text" name="price" maxlength="7" size="7"></td>
</tr> <tr>
<td colspan="2"><input type="submit" value="Register"></td> </tr>
</table>
</form>
</body>
</html>
The results of this form are passed along to insert_book.php, a script that takes the details, performs some
minor validations, and attempts to write the data into the database.
insert_book.php— This Script Writes New Books into the Database
<html>
<head>
<title>Book-O-Rama Book Entry Results</title>
</head>
<body>
<h1>Book-O-Rama Book Entry Results</h1>
<?php
// create short variable names
$isbn=$_POST['isbn'];
$author=$_POST['author'];
$title=$_POST['title'];
$price=$_POST['price'];

if (!$isbn || !$author || !$title || !$price) { echo "You have not entered all the required details.<br />"
."Please go back and try again."; exit;
}

if (!get_magic_quotes_gpc()) {
$isbn = addslashes($isbn);
$author = addslashes($author);
$title = addslashes($title);
$price = doubleval($price);
}
@ $db = new mysqli('localhost', 'bookorama', 'bookorama123', 'books'); if
(mysqli_connect_errno()) { echo "Error: Could not connect to database. Please try again later."; exit;
}
$query = "insert into books values
('".$isbn."', '".$author."', '".$title."', '".$price."')";
$result = $db->query($query);
if ($result) {
echo $db->affected_rows." book inserted into database.";
} else { echo "An error has occurred. The item was not added.";
}
$db->close();
?>
</body>
</html>

11. How do you implement a file upload using HTML? Explain with an example. (6)
Ans: HTML for File Upload
To implement file upload, you need to use some HTML syntax that exists specially for this purpose. The
HTML for this form is shown in Listing 19.1.
Listing 19.1 upload.html—HTML Form for File Upload

<html>
<head>
<title>Administration - upload new files</title>
</head>
<body>
<h1>Upload new news files</h1>
<form action="upload.php" method="post" enctype="multipart/form-data"/>
<div>
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<label for="userfile">Upload a file:</label>
<input type="file" name="userfile" id="userfile"/>
<input type="submit" value="Send File"/>
</div>
</form>
</body>
</html>

• this form uses POST.


• File uploads also work with the PUT method supported by Netscape Composer although we would need to
make significant changes to the code. They do not work with GET.
• The extra features in this form are as follows:
.In the <form> tag, you must set the attribute enctype=”multipart/form-data” to let the server
know that a file is coming along with the regular information.
■ You must have a form field that sets the maximum size file that can be uploaded. This is a hidden
field and is shown here as
<input type=”hidden” name=”MAX_FILE_SIZE” value=” 1000000”>

Note that the MAX_FILE_SIZE form field is optional, as this value can also be set server-side.
However, if used in the form, the name of this form field must be MAX_FILE_SIZE. The value is
the maximum size (in bytes) of files you will allow people to upload. Here, we set this field to
1,000,000 bytes (roughly one megabyte).You may like to make it bigger or smaller for your
application.
■ You need an input of type file, shown here as
<input type="file" name="userfile" id="userfile"/>
You can choose whatever name you like for the file, but you should keep it in mind because you will
use this name to access your file from the receiving PHP script.

12. Explain the data stored in superglobal array $_FILES handled by PHP script while uploading the file? (5)
When the file is uploaded, it briefly goes into the temporary directory that is specified in your php.ini
upload_tmp_dir directive., if this directive is not set, it will default to the web server’s main temporary
directory. If you do not move, copy, or rename the file before your script finishes execution, it will be
deleted when the script ends.
The data you need to handle in your PHP script is stored in the superglobal array $_FILES. If you have
register_globals turned on, you can also access the information through direct variable names. However, this is
probably the area in which it is most important to have register_globals turned off, or at least to act as though it
is and use the superglobal array and ignore the globals.
The entries in $_FILES will be stored with the name of the <file> tag from your HTML form. Your form
element is named userfile, so the array will have the following contents:
■ The value stored in $_FILES[‘userfile’][‘tmp_name’] is the place where the file has been
temporarily stored on the web server.
■ The value stored in $_FILES[‘userfile’][‘name’] is the file’s name on the user’s system.
■ The value stored in $_FILES[‘userfile’][‘size’] is the size of the file in bytes.
■ The value stored in $_FILES[‘userfile’][‘type’] is the MIME type of the file—for example,
text/plain or image/gif.
■ The value stored in $_FILES[‘userfile’][‘error’] will give you any error codes associated with
the file upload. This functionality was added at PHP 4.2.0.
Given that you know where the file is and what it’s called, you can now copy it to somewhere useful. At the end
of your script’s execution, the temporary file will be deleted. Hence, you must move or rename the file if you
want to keep it.

13. Explain directives used in session upload progress with their descriptions. (5)

14. Explain any five common upload problems to be avoided?


Avoiding Common Upload Problems
Keep the following points in mind when performing file uploads:
■ The previous example assumes that users have been authenticated elsewhere. You shouldn’t allow just
anybody to upload files to your site.
■ If you are allowing untrusted or unauthenticated users to upload files, it’s a good idea to be paranoid
about the contents of the files. The last thing you want is a malicious script being uploaded and run. You
should be careful, not just of the type and contents of the file as we are here, but of the filename itself. It’s
a good idea to rename uploaded files to something you know to be “safe.”
■ To mitigate the risk of users “directory surfing” on your server, you can use the basename() function to
modify the names of incoming files. This function will strip off any directory paths that are passed in as part
of the filename, which is a common attack that is used to place a file in a different directory on your server.
An example of this function is as follows:
<?php
$path = "/home/httpd/html/index.php";
$file1 = basename($path);
$file2 = basename($path, ".php");
print $file1 . "<br/>"; // the value of $file1 is "index.php" print $file2 .
"<br/>"; // the value of $file2 is "index"

■ If you are using a Windows-based machine, be sure to use \\ or / instead of \ in file paths as per usual.
■ Using the user-provided filename as we did in this script can cause a variety of problems. The
most obvious one is that you run the risk of accidentally over writing existing files if somebody uploads a file
with a name that has already been used. A less obvious risk is that different operating systems and even
different local language settings allow different sets of legal characters in filenames. A file being uploaded
may have a filename that has illegal characters for your system.
■ If you are having problems getting your file upload to work, check out your php.ini file.
You may need to have the upload_tmp_dir directive set to point to some directory that you have access to.
You might also need to adjust the memory_limit directive if you want to upload large files; this determines
the maximum file size in bytes that you can upload. Apache also has some configurable timeouts and
transaction size limits that might need attention if you are having difficulties with large uploads.

15. Explain opendir(), readdir(), rewinddir(), and scandir() with an example. (any two) (6)
i. Opendir — Open directory handle
Description: opendir(string $directory, ?resource $context = null): resource|false
Opens up a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls.
<?php
$dir = "/etc/php5/";

// Open a known directory, and proceed to read its contents


if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
?>
ii. Readdir — Read entry from directory handle
Description: readdir(?resource $dir_handle = null): string|false
Returns the name of the next entry in the directory. The entries are returned in the order in which they are
stored by the filesystem.
<?php
if ($handle = opendir('/path/to/files')) {
echo "Directory handle: $handle\n";
echo "Entries:\n";
/* This is the correct way to loop over the directory. */
while (false !== ($entry = readdir($handle))) {
echo "$entry\n";
}
/* This is the WRONG way to loop over the directory. */
while ($entry = readdir($handle)) {
echo "$entry\n";
}
closedir($handle);
}
?>
iii. Rewinddir— Rewind directory handle
Description: rewinddir(?resource $dir_handle = null): void
Resets the directory stream indicated by dir_handle to the beginning of the directory.
<?php
$dir = "/images/";
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
// List files in images directory
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
}
rewinddir();
// List once again files in images directory
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
}
closedir($dh);
}
}
?>
iv. scandir— List files and directories inside the specified path
Description:scandir(string $directory, int $sorting_order = SCANDIR_SORT_ASCENDING, ?resource $
context = null): array|false.
Returns an array of files and directories from the directory.
<?php
$dir = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);
print_r($files1);
print_r($files2);
?>
16. Explain any three file status functions with an example. (5)

17. List and explain the functions used by web server to change the file system properties with their syntax). (5).
Changing File Properties : In addition to viewing file properties, you can alter them. Each of the chgrp(file,
group), chmod(file, permissions), and chown(file, user) functions behaves similarly to its Unix equivalent. None
of these functions will work in Windows-based systems, although chown() will execute and always return true. The
chgrp() function changes the group of a file. It can be used to change the group only to groups of which the user is
a member unless the user is root.
The chmod() function changes the permissions on a file. The permissions you pass to it are in the usual Unix
chmod form. You should prefix them with a 0 (a zero) to show that they are in octal, as in this example:
chmod(‘somefile.txt’, 0777);
The chown() function changes the owner of a file. It can be used only if the script is running as root, which should
never happen, unless you are specifically running the script from the command line to perform an administrative
task.

18. How does the web server user can create, delete and move files, explain? (6)
Creating, Deleting, and Moving Files : You can use the file system functions to create, move, and delete files.
First, and most simply, you can create a file, or change the time it was last modified, using the touch() function.
This function works similarly to the Unix command touch. The function has the following prototype: bool touch
(string file, [int time [, int atime]])
If the file already exists, its modification time will be changed either to the current time or the time given in the
second parameter if it is specified. If you want to specify this time, you should give it in timestamp format. If the
file doesn’t exist, it will be created. The access time of the file will also change: by default to the current system
time or alternatively to the timestamp you specify in the optional atime parameter.
You can delete files using the unlink() function. (Note that this function is not called delete—there is no delete.)
You use it like this:
unlink($filename);
You can copy and move files with the copy() and rename() functions, as follows: copy($source_path,
$destination_path);
rename($oldfile, $newfile);
You might have noticed that we used copy() in Listing 19.2.
The rename() function does double duty as a function to move files from place to place because PHP doesn’t have a
move function. Whether you can move files from file system to file system and whether files are overwritten when
rename() is used are operating system dependent, so check the effects on your server. Also, be careful about the path
you use to the filename. If relative, this will be relative to the location of the script, not the original file.

19. Explain the four main techniques to execute a command on the web server with their syntax? (6)

***

You might also like