ASP

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

(2½ Hours) [Total Marks: 75]

N. B.: (1) All questions are compulsory.


(2) Make suitable assumptions wherever necessary and state the assumptions made.
(3) Answers to the same question must be written together.
(4) Numbers to the right indicate marks.
(5) Draw neat labeled diagrams wherever necessary.

I. Answer any two of the following: 10


a. Define each of the following terms:
i. Derived class
The functionality of an existing class can be extended by creating a new class
from it. The new class is then called a child class or derived class. The derived
class inherits the properties of the base class.
ii. Abstract class
An Abstract class is a non-instantiable class which is either partially
implemented, or not at all implemented. It can have abstract methods as well
as non-abstract methods. Abstract classes require subclasses to provide
implementations for the abstract methods. It provides default
functionality to its sub classes.
iii. Static class
A static class is class whose objects cannot be created and must contain
only static members.
iv. Sealed class
A sealed class is a class which cannot be inherited. In C#, the sealed
modifier is used to define a class as sealed.
v. Partial class
It is possible to split the definition of a class over two or more source files.
Each source file contains a section of the type or method definition, and all
parts are combined when the application is compiled.
b. Explain reference parameter with example.
A parameter declared with a ref modifier is a reference parameter. The reference
parameter does not create a new storage location. Instead both the actual and formal
parameters refer to the same memory location. The changes that take place inside the
method will be reflected on the original values of the actual parameters. So this type
of parameter passing is well suited to methods that need to change multiple values
and which are required to be accessed from the caller method.
Example:-
In the following example the variable x is passed by reference to the method triple.
using System;
class byref_example
{
public void triple(ref int x) // The parameter x is passed by reference.
{
x = x*3;
Console.WriteLine("The value inside the method: {0}", x);
}
public static void Main()
{
int x = 10;
byref_example o=new byref_example();
Console.WriteLine("The value before calling the method: {0}",x);
o.triple(ref x); // Passing x by reference.
Console.WriteLine("The value after calling the method: {0}",x);
}
}
Output
The value before calling the method: 10
The value inside the method: 30
The value after calling the method: 30
c. Explain jagged array with example.
In a jagged array, each row may have different number of columns. It is equivalent
to an array of variable sized one-dimensional arrays. The Length property is used to
get the length of each one-dimensional array.

1
Here the first row is a one-dimensional array of
one column, second row is a one-dimensional
array of two columns and third row is a one-
dimensional array of four columns.

A jagged array can be declared and initialized as follows:


datatype[][] arrayname=new datatype[rowsize][];
arrayname[0]=new datatype[]{val1,val2,val3, …};
arrayname[1]=new datatype[]{val1,val2,val3, …};
arrayname[2]=new datatype[]{val1,val2,val3, …};
.
.
.
arrayname[rowsize-1]=new datatype[]{val1,val2,val3, …};

Example:- Write a program to create the following jagged array.

program:-
using System;
class numadd{
public static void Main(){
int[][] x=new int[4][];
x[0]=new int[2]{5,13};
x[1]=new int[3]{7,8,11};
x[2]=new int[4]{2,3,4,5};
x[3]=new int[1]{9};
for(int i=0;i<4;i++){
for(int j=0;j<x[i].Length;j++){
Console.Write(x[i][j]+"\t"); }
Console.Write("\n");}}}
d. Explain method hiding with example.
In a C# program a derived class can have methods with the same signature as that of
its base class methods. This hides the base class methods by its derived class
counterparts and gives a warning. This warning can be suppressed by using the new
keyword with the derive class methods. This means that the members of the base
class are made intentionally hidden by the members having the same signature in the
derived class. The new function will never be invoked by a base class pointer.
Example:-
class demo{
public void disp(){
System.Console.WriteLine("From disp method of base class");
}}
class test:demo{
new public void disp() //This method hides the disp() method of demo class
{
System.Console.WriteLine("From disp method of derived class");
}
public static void Main(){
test t=new test();
t.disp();
}}
Output
From disp method of derived class

II. Answer any two of the following: 10


a. Explain foreach loop with proper syntax and example.
The foreach statement is used to iterate through the elements of an array or another
collection. The syntax of foreach loop is:
foreach(type identifier in expr) { statements; }
where foreach and in are keywords.
2
type represents the data type of the loop variable.
identifier represents loop variable.
expr represents a Collection data type.
statements represents body of the loop.
Example:-
int[] x={10,11,6,23,1,133};
foreach(int i in x)
{
System.Console.WriteLine(i);
}
b. What are the various stages in ASP.NET page lifecycle? Arrange the following page
lifecycle events in correct sequence in which they are raised.
i. Unload
ii. PreRender
iii. Init
iv. Load
v. SaveStateComplete
vi. InitComplete

Following are the various stages in ASP.NET page lifecycle


1. Page request
2. Start
3. Initialization
4. Load
5. Postback event handling
6. Rendering
7. Unload

Following is the correct sequence of the given life cycle events


i. Init
ii. InitComplete
iii. Load
iv. PreRender
v. SaveStateComplete
vi. Unload
c. What is delegate? Explain delegate declaration and delegate instantiation with
example.
A delegate in C# is similar to a function pointer in C or C++. It is a reference type
object that allows the programmer to encapsulate a reference to a method in it. It
defines the return type and signature for a method and can refer to any methods that
are of the same format in the signature.

Delegate declaration
A delegate is declared with the delegate keyword, followed by return type and the
signature of the method that can be delegated to it. The declaration takes the
following form:
modifier delegate return-type delegate-name (formal-parameters);
where modifier specifies the accessibility of the delegate,
delegate is a keyword,
delegate-name is any valid C# identifier,
formal-parameter defines the parameter list.
Delegate instantiation
Creation of a delegate instance takes the form:
new typename ( invocation-target-expression )
The invocation target instance can refers to either:
 a static method
 an instance method
Example:-
In the following program delegate instantiation statements are highlighted.
delegate string mydelegate(); //delegate declaration statement
class myclass{
public static string mydelegatemethod1() //delegate method 1
{
System.Console.WriteLine(“from mydelegatemethod1”); //delegate method 2
}
public string mydelegatemethod2()
{
3
System.Console.WriteLine(“from mydelegatemethod1”);
}
}
class Demo
{
public static void Main(){
mydelegate d1 = new mydelegate (myclass.mydelegatemethod1); // static
// method
myclass m=new myclass();
mydelegate d2 = new mydelegate (m.mydelegatemethod2); // instance method
}
}
d. Explain about external style sheet and its advantages. How would you link an HTML
page to an external style sheet?
External style sheets consist of a list of rules that can be applied to one or more web
pages. It helps you to separate the style information from the HTML file. The styles
are external to, or outside of, the web page. It can be linked to any number of web
pages and thereby providing maximum reusability. The external style sheet files
have extension .css.
An external style sheet can be linked to a web page using link tag as follows:
<link rel=“stylesheet” href=“Styles/Sstl.css” type=“text/css” >

III. Answer any two of the following: 10


a. Explain any five common properties of web server controls.
Property Description

AccessKey Enables you to set a key with which a control can be accessed at
the client by pressing the associated letter.
BackColor, Enables you to change background color and text color of a
ForeColor control.
BorderColor This property is used to change the border color of a control.
BorderStyle Using this property border Style can be set to none, dotted,
dashed, solid double, groove etc.
BorderWidth Enables you to change border width of a control.
CssClass Enables you to set the style sheet class for this control.
Enabled Determines whether the control is enabled or not. If the control is
disabled user cannot interact with it.
Font Enables you to change the Font settings.
Height Enables you to set the height of the control.
Width Enables you to set the width of the control.
ToolTip This property enables you to set a tooltip for the control in the
browser and is rendered as a title attribute in the HTML, is shown
when the user hovers the mouse over the control.
Visible Determines whether the control is visible or not.
b. What is the scope of protected data members of a class? Explain method overloading with
example.
Protected Data Members
The protected data members of a class are similar to private data members in many
respects except the fact that they can be accessed also from it’s child classes.
Method Overloading
An operation may have more than one method defined for it. Some of these methods
might represent proposals from various vendors on how an operation should be
specified. Some of these methods could represent staged approaches to implement a
method over a period of time. The choice of a method could be based on what
performs best for a given situation.
The Multiple methods with the same name (for the same operation) are
achieved by varying the number or type of arguments of these methods. This
phenomenon is known as method overloading in C#.
Example:-
using System;
class demo{
public int add(int a,int b){ return a+b; }
public int add(int a,int b,int c){ return a+b+c; }
double add(double a,int b){ return a+b; }
double add(int a,double b){ return a+b; }
4
double add(double a,double b){ return a+b; }
public static void Main(){
demo n=new demo();
Console.WriteLine(n.add(1,2,3)); Console.WriteLine(n.add(2,3));
Console.WriteLine(n.add(4.5,2)); Console.WriteLine(n.add(2,3.2));
Console.WriteLine(n.add(1.2,3.7));
}}
The output of the above program would be:
6
5
6.5
5.2
c. When is CheckedChanged event of a Check Box fired?
Describe the following properties:
i. GroupName property of a Radio Button
ii. Text property of a Label
iii. TextMode property of a Text Box
iv. Checked property of a Radio Button

The CheckedChanged event of a Check Box occurs when the value of


the Checked property changes between posts to the server.

i. GroupName property of a Radio Button


Use the GroupName property to specify a grouping of radio buttons to create
a mutually exclusive set of controls. You can use the GroupName property
when only one selection is possible from a list of available options. It gets or
sets the name of the group that the radio button belongs to. To set
group to a radio button following code can be used.
RB1.GroupName = "osg"; where RB1 is the ID of a radio button.
ii. Text property of a Label
Use the Text property to specify or determine the text content of
the Label control.
Example:-
Label1.Text= "Enter a Number"
iii. TextMode property of a Text Box
TextMode : Get or set the behavior mode of a text box.
a. Single – Single line text box
b. Multiple – Multiline text box
c. Password – Password text box
A password TextBox:
<asp:TextBox id="t1" TextMode="password" runat="server" />
A multiline TextBox:
<asp:TextBox id="t2" TextMode="multiline" runat="server" />
iv. Checked property of a Radio Button
Specifies whether the radio button is checked or not
<asp:RadioButton id="r1" Checked="True" runat="server"/>
This property can be used to determine which button is selected in a group.
d. Explain the similarities and differences between List Box and Drop-Down List.
At least 5 proper points expected.

IV. Answer any two of the following: 10


a. Write short descriptions for the following:
i. Session state variables
Session state identifies requests from the same browser during a limited time
window as a session, and provides a way to persist variable values for the
duration of that session. ASP.NET session state enables you to store and
retrieve values for a user as the user navigates ASP.NET pages in a Web
application. It is a server-side state management technique.
Following is the syntax for adding/updating Session Variables
Session[" session_variable_name"]=value;
Example:-
Session["FirstName"] = t1.Text;
Session["LastName"] = t2.Text;
Retrieving Session Variables
String variable=Session[“session_variable_name”].ToString();
Example:-
string x = Session["itm1"].ToString();
5
ii. SiteMapPath control
The SiteMapPath control is a series of links that lead the user to find his or
her way back to home page. These links are also known as bread
crumbs. The SiteMapPath control directly gets data from the web.sitemap
file and does not need a SiteMapDataSource control.
b. What are the advantages of a master page? Explain about ContentPlaceHolder’s in
master pages.
The master page provides a framework (common content as well as the layout) within
which the content from other pages can be displayed. It provides elements such as
headers, footers, style definitions, or navigation bars that are common to all pages in
your web site. The major advantage of master page is that the content pages need not
have to duplicate code for shared elements within your web site. It gives a consistent
look and feel for all pages in your application. The master page layout consists of
regions where the content from each content page should be displayed. These regions
can be set using ContentPlaceHolder server controls. These are the regions where
you are going to have dynamic content in your page. A derived page also known as
a content page is simply a collection of blocks the runtime will use to fill the regions
in the master.
c. What is RangeValidator? Describe any four properties of it.
The RangeValidator control is used to check whether the user enters an input value that is
within a specified range. It can be used to check ranges within numbers, dates, and
characters.
Property Description
ControlToValidate The id of the control to validate
Display • None (the control is not displayed and error message is shown
in the ValidationSummary control)
• Static (in case of failure error message is shown in the space
reserved).
• Dynamic (In case of failure error message is shown. Space is not
reserved.)
ErrorMessage The text to display in the ValidationSummary control when validation
fails.
Note: This text will also be displayed in the validation control if the Text
property is not set
MaximumValue Specifies the maximum value of the input control
MinimumValue Specifies the minimum value of the input control
Type Specifies the data type of the value to check.
The valid types are:
Currency, Date, Double, Integer, String
Text The message to display when validation fails
d. What are the advantages and drawbacks of using cookies? Explain how server sets a
cookie and retrieve it.
Advantages
• Cookies are very easy to create and manipulate.
• Cookies do not require any server resources since they are stored on the client.
Drawbacks
• Users can edit or delete cookie files.
• Cookies stores data in text files and hence not reliable in storing sensitive data.
• Can store only small amount of data.
Syntax for Creating a Cookie:
Response.Cookies[“cookie name”].Value=“specify value”;
Example:-
Response.Cookies["uname"].Value = TextBox1.Text;
Syntax for Reading a Cookie:
String str=Request.Cookies[“cookie name”].Value;
Example:-
string str= Request.Cookies["uname"].Value;

V. Answer any two of the following: 10


a. Explain about sqlConnection and sqlCommand classes.
sqlConnection
It is an object that provides physical connection to the database. It connects to the
database and then opens a connection between the application and the Data Source.
Then the SQL Commands is executed with the help of the Command Object either
for retrieving data from the Data Source or for manipulating data in the Data Source.
Once the Database activity is over, Connection should be closed and releases the
6
Data Source resources. The connectionstring property of this object provides the
information that is needed to connect to the database.
sqlCommand
An sqlCommand object contains an SQL statement. It requires a Connection Object
for executing the SQL statements. It executes SQL statements and Stored
Procedures against the data source specified in the Connection Object.
Example:-
string connectionString =
ConfigurationManager.ConnectionStrings["testConnectionString"].ToString();
SqlConnection connection = new SqlConnection(connectionString);
string sql = "select ename from EMP";
SqlCommand command = new SqlCommand(sql, connection);
b. What is a GridView control? Explain how to enable row selection, paging and
sorting features of GridView.
The GridView server control displays data provided by a data source in a tabular
format. It renders its data as an HTML table. The GridView control supports
automatic paging, sorting, editing, deleting, and selecting. To enable row selection
AutoGenerateSelectButton property of GridView can be set to True.
The GridView data can be sorted based on any or all of its columns. To sort GridView
data, following are the steps
– Set AllowSorting attribute of GridView to True
– Also set SortExpression property of columns to respective field
from database to sort.
Paging refers to the ability of GridView control to display bound data one page at a
time. Users can arbitrarily select pages from a GridView. To enable paging feature
of a GridView
– Set AllowPaging property of GridView control to true.
– Set PageSize property to no of records you want in each page.
Example:-
<asp:gridview AllowSorting="true" AllowPaging="true" PageSize="5"
ID="Gridview1" runat="server" DataKeyNames="pid" DataSourceID="SqlDS" >
<Columns>
<asp:BoundField DataField="pname" HeaderText="PRODUCT NAME"
SortExpression="pname"> </asp:BoundField>
</Columns>
</asp:gridview>
c. Briefly explain FormView control. How is it different from DetailsView.
Like DetailsView, FormView also displays a single record from the data source at a
time. Both controls can be used to display, edit, insert and delete database records
but one at a time. Both have paging feature and hence support backward and forward
traversal. The FormView control provides more formatting and layout options than
DetailsView. The DetailsView control uses <BoundField> elements or
<TemplateField> elements to display bound data whereas FormView can use only
templates to display bound data. The FormView control renders all fields in a single
table row whereas the DetailsView control displays each field as a table row.
When compare to DetailsView, the FormView control provides more control over
the layout.
d. Write short notes on Data Reader and Data Adapter.
An object of sqlDataReader class can be used to read the rows in a result set returned
by a database query. Even data adapter uses a data reader to read through the rows
in the result set and store them in a data set. The DataReader cannot be created
directly from code; they can be created only by calling the ExecuteReader method of
a Command Object.
SqlDataReader reader = command.ExecuteReader();
The data that is used by an application is stored in a DataSet. A DataSet is a container
for one or more DataTable objects that contain the data you retrieve from the
database. DataSet is completely independent from the Data Source. DataAdapter
Object allows us to load data into the DataTables. To retrieve data from a database
and store it in a data table, DataAdapter object issues a select statement stored in a
Command object. Similarly to modify data, DataAdapter object issues insert, update
or delete statement stored in a database.

7
VI. Answer any two of the following: 10
a. What are the benefits using Ajax? Explain about UpdatePanel and ScriptManager.
The major benefit of Ajax is partial page rendering. The partial update of a page does
not necessitate full reload of the page and hence leads to flicker-free page rendering.
UpdatePanel
• It is a container control.
• A page can have multiple update panels.
• The UpdatePanel control enables you to create a flicker free page by providing
partial-page update support to it.
• It identifies a set of server controls to be updated using an asynchronous post back.
• If a control within the UpdatePanel causes a post back to the server, only the
content within that UpdatePanel is refreshed.
ScriptManager
• The ScriptManager control manages client script for AJAX-enabled ASP.NET
Web pages.
• Although this control is not visible at runtime, it is one of the most important
control for an Ajax enabled web page.
• This control work with UpdatePanel control to facilitate partial page rendering in
Ajax enabled web pages.
• There can be only one ScriptManager in an Ajax enabled web page.
b. Write jQuery program that changes the background colour of a paragraph to red and
font colour to yellow when mouse enters over it. Also set the background colour to
white and font colour to black when mouse leaves the paragraph.
c. Explain LINQ to Objects with an example.
• It is used to query collections.
• The LINQ can be used to query any IEnumerable or IEnumerable<T> collection.
• Any enumerable collections such as List<T>, Array, ArrayList, Dictionary<TKey,
TValue> etc. can be queried using LINQ.
Example:-
Label1.Text = "";
string[] hollywood = { "The Darkest Hour", "Heartbreaker",
"Contraband", "Haywire", "The Descendants"};
var query = from x in hollywood
select x;
foreach (string s in query)
{
Label1.Text += s+"<br>";
}
d. Explain the query operators SELECT, FROM, ORDERBY and WHERE in LINQ.
• The select clause is used to retrieve data from the source you are querying.
• It specifies the format of the data returned.
• It can have a set of columns based on the query expression results.
• select adds the result to the return type.
• The from clause defines the collection or data source that the query must act upon.
• var query = from x in nwdb.Customers
select x;
• Where clause is used to filter elements from the data source.
• It selects only those elements for which the ‘where’ clause expression is true.
• Example:-
var query = from x in nwdb.Customers
where x.Country = = "Germany"

8
select x;
• Order by clause is used to arrange the items in the result collection in ascending
or descending order.
var query = from x in nwdb.Products
orderby x.UnitsInStock ascending
select x;

VII Answer any three of the following: 15


a. What are the rules in defining a constructor? Explain static constructor with
example.
A constructor should have the same name as that of its class.
Constructors can take any number of arguments.
Constructor cannot return any value.
A static constructor is used to initialize static variables of a class. It is declared using
the static keyword. A class can have only one static constructor. The general syntax
of a static constructor is shown below.
static classname()
{
static member initializations;
}
Also note that a static constructor is parameter less and no access modifiers are
allowed with its declaration. The exact timing of static constructor execution is
implementation-dependent, but is subject to the following rules:
The static constructor for a class executes before any instance of the class is created.
The static constructor for a class executes before any of the static members for the
class are referenced.
The static constructor for a class executes after the static fields initializes for the
class.
The static constructor for a class executes at most one time during a single program
execution.
Example:-
class A{
static A() // A static constructor is parameter_less and no access modifier is
{ // allowed with its declaration.

Console.WriteLine("static constructor A is invoked");


}
public static void Main() { }
}
Output:
static constructor A is invoked
b. What is a CSS selector? Explain class selector and grouped selector with example.

A CSS selector is the part of a CSS rule set that actually selects the content you want
to style. Following are the common type of selectors.
• HTML Tag Selectors
• Class Selector
• ID Selector
• Grouped Selector
• Context Selector
Class Selector
• It styles all elements with the specified class.
• It starts with a period (.) symbol.
Syntax:-
.classname { property:value; }
• Example:-
.test { font-family: ARIAL; font-size: 1em; color: aqua; }
• A class can be applied to selected HTML elements as follows.
h1.test{ color:silver;font-size:2em; }
Here the style ‘test’ is applicable only to h1 tag.
so <p class= "test">STYLE NOT APPLIED</p>
<H1 class="test"> STYLE APPLIED </H1>
Grouped Selector
• If there are multiple elements with the same style then these elements can be
grouped and a common style definition can be made for the group.
• Separate each element in the group with a comma.
• Example:-
9
h1,h2,h3,p{
color:lime;
}
This is equivalent to:
h1{color:lime}
h2{color:lime}
h3{color:lime}
p {color:lime}
c. What is code-behind model in ASP.NET? How is it different from single file model?
The ASP.Net Framework provides a new style of coding to develop web pages. This is called
Code-Behind. In Code Behind Model server maintains two types of files.
• The HTML code page with .aspx extension maintains the code for User Interface
design.
• The .aspx.cs file maintains the program logic.
The file that contains the programming logic (.aspx.cs file) is known as the code behind file.
Only server controls can interact with the code behind the page; not the HTML controls.
Code Behind Vs. Single File
Code Behind Single File
The code is in <script> blocks in the
The HTML and controls are in the .aspx file,
same .aspx file that contains the HTML and
and the code is in a separate . aspx.cs file.
controls.
The code for the page is compiled into a
separate class from which the .aspx file The .aspx file derives from the Page class.
derives.
The program logic is separated from user Both program logic and user interface
interface design code. design code are placed in the same .aspx
So it is easy to understand. file, which makes it cumbersome.

d. Explain URL encoding in detail.


e. What is a Data source? Explain various types of data sources in ASP.NET.
The Data source control connects to and retrieves data from a data source and makes it
available for other controls to bind to, without requiring code. ASP.NET allows a variety of
data sources such as a database, an XML file, or a middle-tier business object. The common
data source controls are:
• AccessDataSource – Enables you to work with a Microsoft Access database.
• XmlDataSource – Enables you to work with an XML file.
• SqlDataSource – Enables you to work with Microsoft SQL Server, OLE DB, ODBC,
or Oracle databases.
• ObjectDataSource – Enables you to work with a business object or other class
• SiteMapDataSource – Used for ASP.NET site navigation.
• EntityDataSource - Enables you to bind to data that is based on the Entity Data Model.
• LinqDataSource – Enables you to use Language-Integrated Query (LINQ) in an
ASP.NET Web page.
f. Explain LINQ to SQL with the help of a query that performs equijoin.
LINQ to SQL allows developers to generate .NET classes that represent data. These
generated classes map directly to database tables. When the application runs, LINQ
to SQL translates the language-integrated queries in the object model into SQL and
sends them to the database for execution. When the database returns the results,
LINQ to SQL translates them back to objects that you can work with in Visual Basic
or C#. LINQ to SQL needs a Data Context object. The Data Context object is the
bridge between LINQ and the database. The Data Context is created using the LINQ
to SQL designer. The LINQ to SQL designer creates a .dbml file which contains
auto-generate Visual Basic or C# source code that represents data. The Data Context
is named after .dbml file. If the name of the .dbml file is DataClasses1 then Data
Context class name would be DataClasses1DataContext. The name of the data
context in the following example is DataClasses1DataContext and has mapped
objects Orders and Order_Details. These objects are mapped to relational tables
Order and Order_Detail respectively.
var nwdb = new DataClasses1DataContext();
var query = from o in nwdb.Orders
join od in nwdb.Order_Details
on o.OrderID equals od.OrderID orderby o.OrderID
select new { o.CustomerID, od.OrderID }

10

You might also like