1
T.Y. B.Sc. (IT) : Sem. V
ASP.NET with C# Time : 2½ Hrs.] Prelim Question Paper Solution [Marks : 75
Q.1 Attempt the following (any TWO) [10]Q.1(a) What is fall through in switch with respect to switch in C#? Explain. [5](A) The switch statement is similar to the if statement in that it executes code conditionally
based on the value of a test. [1 Marks] The basic structure of a switch statement is as follows: switch (<testVar>) {
case<comparisonVal1>: <code to execute if <testVar> == <comparisonVal1>> break; case<comparisonVal2>: <code to execute if <testVar> == <comparisonVal2>> break; . . . case<comparisonValN>: <code to execute if <testVar> == <comparisonValN>> break; default: <code to execute if <testVar> != comparisonVals> break;
}
Fallthrough in switch statement [2 marks] In the absence of break statement in a case block, if the control moves to the next
case block without any problem, it is known as ‘fallthrough’. Fallthrough is permitted in C++ and Java but C# does not permit automatic fallthrough,
if the case block contains executable code. However it is allowed if the case block is empty. Example: [2 marks] Switch (m) {
case 1: x = y; case 2: x = y + m; default: x = y – m;
}
is an error in C#, if one wants two consecutive case blocks to be executed continuously, one has to force the process by using the goto statement. Example: switch (m) { case 1: x = y; goto case 2; case 2:
Vidyala
nkar
Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET
2
x = y + m; goto default; default: x = y – m; break; } _______________ switch (m) { case 1: case 2: case 3: code to execute; default: code to execute; break; } Is allowed as case 1 and 2 do not contain any executable code.
Q.1(b) Explain Exception Handling. [5](A) Exception Handling [1 mark]
It is a mechanism to handle runtime problems generated in the program. In C/C++ The runtime problem causes abnormal termination of program however in Java / C++. The runtime problem causes abnormal termination of program however in java/C#. There is a mechanism to take corrective action. In case of exception. Exception handing is implemented using following keywords. i) try It contains code that needs to be monitored for occurrence of exception. It exception is generated in try block there is chance of it being handled. When
exception is generated outside the try block, it cannot be handled and causes abnormal program termination. [1 mark]
ii) catch block It contains exception handling code. [1 mark] iii) throw It is used to manually throw an exception normally used for throwing user-defined
exception. [1 mark] iv) finally
It contains code that must be executed whether exception is generated or not or generated exception is handled or not it is executed before method returns to its caller. [1 mark]
Q.1(c) Explain CLR. [5](A) CLR (COMMON LANGUAGE RUNTIME) [2 marks]
CLR is one of the most essential components of .net framework. CLR is the environment where all programs using .net technologies over executed. CLR allows the execution of code across different platform by transmitting code into IL
(Intermediate Language).
Vidyala
nkar
Prelim Question Paper Solution
3
IL is converted into machine language during execution by JIT compiler (Just-In-Time). During JIT compilation the code is also check for type safety. Type safety ensure that object are always accessed in compatible way. If value of 8
byte given to 4 byte then error will occur by CLR and error will attempt to trap. CLR consist of common rules that must be followed by all language using .net framework
these set of rules are called as Common Language Specification (CLS). The CLS enables an object or application to interact with the bjects or application of
other language. The classes that follows the rules specified by CLS are termed as CLS compliant
classes. One of the specification defined in CLS is Common Typed System (CTS). CTS provides a type system that is common across all languages. CTS defines rules that ensure that the data object written in various languages are able
to interact with each other. During execution CLR performs following steps : (a) Loading assemblies & identifies name spaces [1 mark]
assemblies are loaded into memory after loading assemblies the CLR will identifies namespace for the code in assemblies.
namespaces are collections of classes (similar package in java) namespaces are used to organised the classes in hierarchy.
The namespaces have public access & this can not be change. (b) JIT Compilation (Just-in-time) [1 mark] Before execution the IL is converted into machine language using JIT complier. The IL code is examined for following points : The memory location that code needs to access are available. methods are called only through properly define types IL has been correctly generated. (c) Garbage Collection [1 mark] The garbage collection process begins after the JIT compilation. It manages the allocation & de-allocation of memory for an application.
When you create an object the CLR allocates memory for the object from managed heap.
Q.1(d) Demonstrate with the help of an example, the significance of properties in C#. [5](A) Properties are members that provide a flexible mechanism to read, write and compute
the values of private fields. Properties can be used as though they are public data members, but they are actually
special methods called accessors. This enables data to be accessed easily while still providing safety and flexibility of
methods. Their processing involves two function-like blocks: one for getting the value of the
property and one for setting the value of the property. These blocks, also known as accessors, are defined using get and set keywords
respectively, and may be used to control the access level of the property. [1 marks]
// Field used by property. private int myInt; // Property. public int MyIntProp { get
Vidyala
nkar
Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET
4
{ return myInt; } set { // Property set code. myInt = Value; }
} [2 marks]
Code external to the class cannot access this myInt field directly due to its accessibility level (it is private).
Instead, external code must use the property to access the field. The set function assigns a value to the field similarly. Here, you can use the keyword value to refer to the value received from the user of the property:
Complete example [2 marks] class Number {
private int myInt; // Property.
public int MyIntProp { get { return myInt; } set { // Property set code. myInt = Value; } } } class PropTest {
public static void Main() {
Number n = newNumber(); //n.no = 10; // not allowed , as ‘no’ is a private field.
n.Ano = 10; Console.WriteLine("The value of variable no is {0}", n.Ano);
Console.ReadKey(); }
}
Q.2 Attempt the following (any TWO) [10]Q.2(a) What is an assembly? Explain its different components. [5](A) Assembly is a compiled code library for deployment, versioning and security purpose.
Assemblies are the building blocks of .NET framework applications; they form the fundamental unit of deployment.
When an application is compiled, the MSIL code created is stored in an assembly. With the MSIL code, metadata (information about the information contained in the
assembly) is also created after the first compilation.
Vidyala
nkar
Prelim Question Paper Solution
5
That means an assembly contains the MSIL code, which the common language runtime executes(JIT), and the type metadata.
The metadata enables the assemblies to be fully descriptive. One does not need any other information to use an assembly. This means that deploying applications is often as simple as copying the files into
directory on a remote computer. Assemblies are the smallest units to which the .NET Framework grants permissions.
They provide security boundaries within the .NET Framework. Assembly Structure (Components of Assembly) [1 mark]
An assembly consists of assembly metadata(assembly manifest) describing the complete assembly, type metadata describing the exported types and methods,
MSIL code resources. All these parts can be inside of one file or spread across several files.
[3 marks]
Manifest It describes the assembly. The manifest file contains all the metadata needed to specify the assembly's version requirements, security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes. Type Metadata It contains metadata, which describes each and every type (class, structure, enumeration, and so forth). MSIL It contains Intermediate language code. Resources
It contains bitmaps, icons, audios and other types of resources. Q.2(b) Explain ASP.NET life cycle. [5](A) ASP.NET Page LifeCycle [1 mark]
Sequence of events that are fixed in life cycle of ASP.NET web page are as follows : a) Page_Init b) Load ViewState c) Load Post Back Data d) Page_Load e) Raise PostDataChangedEvent f) Raise PostBackEvent g) Page_PreRender h) SaveViewsState i) Page_Render j) Page_Unload
Page_Init [1 mark] It contains initialization code for example the server controls are initialized to their default values.
LoadViewState [1 mark] It restores the pages view state information from its last saved state.
Vidyala
nkar
Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET
6
Load Post Back Data [1 mark] It populates the server control in your web with the posted data.
PageLoad [1 mark] It restores the control the values of the web page i.e. the data will be binded to the data controls.
Page-PreRender [1 mark] It is called prior to the rendering of page event here we can add code to make changes in the rendered output.
Save View State [1 mark] It is responsible for saving view state information of web page.
PageRender [½ mark] It render the content of web page in the webbrowser you can make changes to the rendered output here.
Page Unload [½ mark] It is the last event in life cycle of ASP.NET page. It is called after the page has been rendered and is responsible for releasing the resource and discarding the web page from memory.
Q.2(c) Explain CSS & its types. [5](A) CSS offers with set of options to change every aspects of web sites. [½ mark]
CSS is understood by all the browsers and so it is used for visual presentation of web pages.
It separates presentation from data. It decrease the bandwidth and direct change with every request.
Types: [1½ marks] InclineCss It uses style distribute of a very element on which we want to apply style >It cannot be nemed Example [1½ marks] <html> <body> <hl style = “backgroundcolor:block; fontstyle: Italic>Hello</h1> </body> <html> Embedded CSS [1½ marks] Here the style rule for the element or the clam all id us specified in the head element of the page. Style rule specified will be applied to every html elements on the page. Example: <html> <head> <style type = “text/CSS”> hl { background_color:green; Font face: Arial } </style> </head> </html>
Vidyala
nkar
Prelim Question Paper Solution
7
External CSS: Here external stylesheet CSS rule is created and only contains style rules. The style rules are applied on every apperance of the elements wherever oppear on the web page. [1½ mark] To link external CSS page on the web page <html> <head> <such fref= “stylesheet.CSS” vel = “Stylesheet” type “text/CSS”/> </head> </html>
Q.2(d) Explain delegate with example. [5](A) DELEGATE [3 marks]
class program { delegate int MyDelegate (int x, int y); // delegate static int add (intx, int y) { return (x + y); } static int mul(int x, int y) { return (x * y); } static void main (string [ ] args) { MyDelegate md; // Reference of delegate md = new MyDelegate (add); // function name variable. int P = md(10, 20); // function call Console.WriteLine ("Sum" + P); MyDeletage md1; md1 = new MyDelegate (mul); P = md1(20, 40); Console.WriteLine ("multiplication " + p); } }
Note : [2 marks] Delegate is a type that enables you to store references to the function. Delegates are much like function but with no function body. It is declared using delegate keyword. The delegate declaration specifies the return type and parameter list. After defining a delegate you can define a variable of delegate type & can initialize the
variable as reference to function. We can call the function using delegate variable by passing arguments to it.
Q.3 Attempt the following (any TWO) [10]Q.3(a) Explain RadioButton and CheckBox control. [5](A) RadioButton [½ mark]
The RadioButton control is used to display a radio button. Radiobuttons are used to Select single option from multiple options.
Property DescriptionAutoPostBack A Boolean value that specifies whether the form should be
posted immediately after the Checked property has changed or not. Default is false
Vidyala
nkar
Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET
8
Checked A Boolean value that specifies whether the radio button is checked or not.
Id A unique id for the control GroupName The name of the group to which this radio button belongs. [2 marks]OnCheckedChanged The name of the function to be executed when the
Checked property has changed.
Runat Specifies that the control is a server control. Must be set to “server”
Text The text next to the radio button TextAlign On which side of the radio button the text should appear
(rightor left)
Checkbox control [½ mark] The CheckBox control is used to display a check box. Check box control is used to select multiple choices. AutoPostBack Specifies whether the form should be posted immediately
after the Checked property has changed or not. Default is false
CausesValidation Specifies if a page is validated when a Button control is clicked
Checked Specifies whether the check box is checked or not InputAttributes Attribute names and values used for the Input element for
the CheckBox control [2 mark]
LabelAttributes Attribute names and values used for the Label element for the CheckBox control
Runat Specifies that the control is a server control. Must be set to "server"
Q.3(b) Explain Web.Config file. [5](A) WEB.CONFIG [2 marks]
The web.config file is an XML based file configuration that contains application wide settings. It is present in applications root directory. We can have more than web.config file for the application but we can have only machine.config file.
General form < Configuration > < System.web > < !_Specify compilation, CustomError_Authentication, Authorization . /> < /System .web > < appsettings > < !_Specify file path, connection string, Servername, CustomSettings /> </ appsettings > < /Configuration >
We can use web .configuration for following : i) Uses < pages > section to specify whether session or view state is enabled or disabled.
[1 mark] Example < Configuration > < System .web > < pages enableSessionState = “true”/ > </System.web > </Configuration >
Vidyala
nkar
Prelim Question Paper Solution
9
ii) We can use < Custom Errors > to specify Application wide Error information. [1 mark] < Custom Errors mode = “On” > < error Status code = “You” redirect = “FileUnavailable .aspx”/ > < /custom errors > iii) Can specify key-value-pair [1 mark] < appsetttings > < add key = “Key” value = “Value”/ >
< /appsettings > Q.3(c) Explain the text box web server control. List and explain any four text box
attributes. [5]
(A) The TextBox control is used to create a text box where the user can input text. [1 mark]
Textbox attributes (properties) [4 marks] Properties Description
TextMode The type of text box. SingleLine creates a standard text box, MultiLine creates a textbox that accepts more than one line of text and Password causes the charaacters 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 Determines whether or not text wraps automatically when it reaches the
end of a multiline text box. The default is true. ReadOnly Determines whether the user can change the text in the textbox. The
default is False which means text can be changed. Columns The width of the text box in characters. The actual width is determined
based on the font that’s used for the text entry. Rows The height of a multi-line text box in lines. The default value is 0 which
sets the height to a single line. Q.3(d) What are the different types of events in global.asax file? [5](A) The Global.asax contains following events : [5 marks]
Application_BeginRequest() – This event raised at the start of every request for the web application. Application_AuthenticateRequest – This event rose just before the user credentials are authenticated. We can specify our own authentication logic here to provide custom authentication. Application_AuthorizeRequest() – This event raised after successful completion of authentication with user’s credentials. This event is used to determine user permissions. You can use this method to give authorization rights to user. Application_EndRequest() – This event raised at the end of each request right before the objects released. Application_Start() – This event raised when the application starts up and application domain is created. Session_Start() – This event raised for each time a new session begins, This is a good place to put code that is session-specific.
Vidyala
nkar
Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET
10
Session_End The closing event of “Session_Start” event. Whenever a user’s session in the application expires this event gets fired. So anything you want to do when the user’s session expires you can write codes here. The session expiration time can be set in web.config file. By default session time out is set to 20 mins. Application_End The same as “Application_Start”, “Application_End” is executed only once, when the application is unloaded. This event is the end event of “Application_Start”. This event is normally fired when the application is taken offline or when the server is stopped.
Application_Error Now we come to the last event mentioned in this blog and that is “Application_Error”. This event gets fired when any unhandled exception/error occurs anywhere in the application. Any unhandled here means exception which are not caught using try catch block. Also if you have custom errors enabled in your application i.e. in web.config file then the configuration in web.config takes precedence and all errors will be directed to the file mentioned in the tag.
Q.4 Answer any two of the following. [10]Q.4(a) Explain the following validation controls with example.
(i) Compare Validator (ii) CustomValidator (iii) RangeValidator (iv) RegularExpressionValidator (v) RequriedFieldValidator
[5]
(A) <asp:CompareValidator> Checks if the value is acceptable compared to a given value or compared to the content of another control. In other words, it checks that the value in the validated control matches the value in another control or a specific value. The data type and comparison operation can be specified. If the validated control is empty, no validation takes place. The most important properties in the CompareValidator are ValueToCompare, ControlToCompare,Operator, and type. <asp:CompareValidator id="comvR" runat="server" display="static" controlToValidate="txtR" errorMessage="Data not matching" type="Double" operator="DataTypeCheck"></asp:CompareValidator> Additional property of this control ValueToCompare – the value to compare with. ControlToCompare - The control to compare with.
RangeValidator: <asp:RangeValidator> Checks if the input control’s value is within a specified range. In other words, it checks that the value in the validated control is within the specified text or numeric range. If the validated control is empty, no validation takes place. The most important properties in the RangeValidator are MaximumValue, MinimumValue, and type. <asp:RangeValidator id="ranvDependents" runat="server" display="static" controlToValidate="txtDependents" errorMessage="Must be from 0 to 10" type="Integer" minimumValue=0 maximumValue=10> </asp:RangeValidator> Additional property of this control MinimumValue MaximumValue
Vidyala
nkar
Prelim Question Paper Solution
11
RegularExpressionValidator: <asp:RegularExpressionValidator> Checks the value against a regular expression (pattern).Checks that the value in the control matches a specified regular expression. If the validated control is empty, no validation takes place. The most important property in theRegularExpressionValidator is ValidationExpression. <asp:RegularExpressionValidator id="regvH" runat="server" display="static" controlToValidate="txtH" errorMessage="Hours must be 1-3 digits only" validationExpression="\d{1,3}"></asp:RegularExpressionValidator> CustomValidator: <asp:CustomValidator> Allows you to develop custom validation.Performs user-defined validation on an input control using a specified function (client-side, server-side, or both). If the validated control is empty, no validation takes place. The most important property in the CustomValidator is ClientValidationFunction. <asp:CustomValidator id="cusvDeptNum" runat="server" display="static" controlToValidate="txtDeptNum" ClientValidateFunction="validateLength" errorMessage="Length must be greater than or equal to 4" > </asp:CustomValidator> Examples In JavaScript function validateLength(oSrc, args) {
args.IsValid = (args.Value.length >= 4); RequriedFieldValidator General form < asp : RequiredFieldValidator ID = “RequiredFieldValidator” runnat = “Server” ErrorMessage = “RequiredFieldValidator”>
</asp : RequiredFieldValidator > It validates the content of the control by ensuring that the control should not be empty.
Q.4(b) What is state management? Explain ViewState and URL Encoding. [5](A) State management [1 mark] Asp.net is based on the stateless HTTP protocol. So each request from the client browser to the web server is understood as an
independent request. State management is a technique used to maintain the state information for asp.net
web pages across multiple requests. Asp.net comes with built in support for state management, both at the server and
client ends. ViewState [2 marks] View state is an ASP.NET feature that provides for retaining the values of page and
control properties that change from one execution of a page to another. ViewState does not hold the page’s controls, it holds the control IDs and the corresponding
values that would otherwise have been lost due to a postback to the web server. Viewstate represents the state of a page when it was last processed on web server.
Vidyala
nkar
Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET
12
Viewstate is a property of all server controls and is stored as a key-value pair using the System.Web.UI.StateBag object.
Before ASP.NET sends a page back to the client, it determines what changes the program has made to the properties of the page and its controls. Changes are encoded into a string that is assigned to the value of a hidden input field named _VIEWSTATE.
When the page is posted back to the server, the _VIEWSTATE field is sent back to the server along with the HTTP request. Then ASP.NET retrieves the property values from the _VIEWSTATE field and uses them to restore the page and control properties.
Enabling viewstate at a page level <%@ Page EnableViewstate= “False/true” %> Enabling viewstate at Control level <asp:Label is= “label1” runnat= “server” EnableViewState= “false”> Enabling viewstate at an Application level – in web.config <pages enableViewState= “false/true”> URL encoding / Query Strings [2 marks] It is a string appended at the end of the URL. It can be used to pass the data from one page to another, thus maintain the state
information. It cannot exceed more than 255 characters. Data passed through a querystring is not secure. When security is not an issue, this type of state management can be used. Is typically used to store nonsensitive and nonconfidential data like page numbers,
search data etc. Is composed of a series of filed-value pairs like
<a href=”emp.aspx?Id=1&firstname=Joy&lastname=Mehta&address=vashi> Click</a> To retrieve the querystring information String empid = Request.QueryString[“id”] String empname = Request. QueryString [“name”]
Q.4(c) Explain MasterPage and steps to create MasterPage. [5](A) Master Page [2 marks]
The master page serves as a template for the other content pages on the site. The master page has some code-behind methods, and it could auto-generate the page
titles for the pages and the other tags which are mentioned in it for each content page. Master page stores global page elements that occur on every content page. Extension: ".Master" Content page Stores page-specific elements that are put into the master.
Extension: ".aspx" Master page code behind can change master page after it acquires content.
Extension: ".aspx.cs"
Creating Master Pages [1 mark] Open the application and add new Item and select “Master Page”. Write any code between the <form>tag of the master page. It has two <ContentPlaceHolder>tags , one in the <head> and other in the <body> part of
the page.
Vidyala
nkar
Prelim Question Paper Solution
13
The code looks like this <%@MasterLanguage="C#"AutoEventWireup="true"CodeFile="MasterPage.master.cs"Inherits="MasterPage"%> <html> <head runat="server"> <title></title> <asp:ContentPlaceHolder id="head" runat="server"> </asp:ContentPlaceHolder> </head> <body> <formid="form1"runat="server"> <div> <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder> </div> </form> </body> </html> Any element added to the master page outside the contentplaceholder will appear on every content page that uses the master page.
Q.4(d) Explain the significance of Web.sitemap file with an example. [5](A) To make it easy to show relevant pages in your site using a Menu, a TreeView, or a
SiteMapPath, ASP.NET uses an XML-based file that describes the logical structure of your web site.
By default, this file is called Web.sitemap. This file is then used by the navigation controls in your site to present relevant links in an organized way. [2 marks] Web.sitemap File [2 marks] <?xml version=”1.0” encoding=”utf-8” ?> <siteMap xmlns=”http://schemas.microsoft.com/AspNet/SiteMap-File-1.0”> <siteMapNode url=”~/Home.aspx” title=”Home” description=”Go to the homepage”> <siteMapNode url=”~/Reviews” title=”Reviews” description=”Reviews published on this site” /> <siteMapNode url=”~/About” title=”About” description=”About this site” /> </siteMapNode> </siteMap>
The site map file contains siteMapNode elements that together form the logical
structure of your site. In this example, there is a single root node called “Home,” which in turn contains two child elements, “Reviews” and “About.”
Each siteMapNode can have many child nodes (but there can only be one siteMapNode directly under the siteMap element).
The siteMapNode elements three attributes set: url, title, and description. The url attribute should point to a valid page in your web site. The title attribute is used in the navigation controls to display the name of the page. The description attribute is used as a tooltip for the navigation elements.
[1 marks]
[2 marks]
Vidyala
nkar
Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET
14
Q.5 Attempt the following (any TWO) [10]Q.5(a) Explain Command class and Data Adapter class with properties and methods. [5](A) The Sql Command class [1 mark]
The Sql Command object class is represented by two corresponding classes: Sql Command and Ole Db Command.
Command objects are used to execute SQL commands against a SQL server database. Command objects provide three methods that are used to execute commands on the
database: Execute Non Query: Executes commands that have no return values such as INSERT, UPDATE or DELETE Execute Scalar: Returns a single value from a database query Execute Reader: Returns a result set by way of a Data Reader object
Common members of the SqlCommand Class
Property DescriptionConnection The SqlConnection object used to connect to database. Command Text The text of the SQL statement
Method DescriptionExecuteReader Executes the query and returns the result as s SqldataReader object. ExecuteNonQuery Executes the command and returns an integer representing the
number of rows affected. ExecuteScaler Executes a query and returns the first column of the first row
returned by the query. The Sql Data Adapter class [3 marks]
The Data Adapter is the class at the core of ADO .NET's disconnected data access. It is the bridge facilitating all communication between the database and a Data Set. The Data Adapter is used either to fill a Data Set with data from the database with
it's Fill method. After the memory-resident data has been manipulated, the Data Adapter can commit
the changes to the database by calling the Update method. Common members of the SqlDataAdapter Class [1 mark]
Property DescriptionSelectCommand A SqlCommand object representing the Select statement used to
query the database. DeleteCommand A SqlCommand object representing the Delete statement used to
query the database. InsertCommand A SqlCommand object representing the Insert statement used to
query the database. UpdateCommand A SqlCommand object representing the Update statement used to
query the database. Method DescriptionFill Executes the command identified by the Selectcommand property and
loads the result into a database object. Update Executes the commands identified by the DeleteCommand,
InsertCommand and the UpdateCommand properties for each row in the dataset that was deleted, added or updated.
Vidyala
nkar
Prelim Question Paper Solution
15
Q.5(b) Explain ADO.NET architecture. [5](A) ADO.NET ARCHITECTURES [2 marks]
1) DataSet : ADO.Net can work in connected as well as in disconnected mode. DataSet is
core component of disconnected architecture. It is in memory representation of db it can be used to cache data locally & can track
changes to the data. [½ mark] e.g. : DataSet ds = new DataSet (“customers”); 2) DataTable : A DataTable is use to represent a table in a database. It consist of
collection of rows & columns. [½ mark] 3) DataView : It provide customized view of the data Table. It can be used as sort of
filters for rows of DataSet. e.g.: DataView dv = cust.Tables[“Reliance”] DefaultView; dv.RowFilter = “Address like ‘Hyderabad’”
4) DataProvider : DataProvider provides access to the db. We can use Oracle, SQL server, OLEDB as data proviers. [2 marks]
The DataProvider classes includes : (a) Connection (b) Command (c) Data reader (d) Data Adapter
(a) Connection Object : It is use to establish connection to the db we can use OleDB connection, odbc connection, OracleConnection, SQLConnection.
(b) Command Object : It is use to send SQL Query to the db. we can use OracleCommand, SqlCommand, etc.
The CommandObject makes use of : 1) ExecuteScalar : Returns a single value from query. 2) ExecuteReader : Returns collection of rows & columns as resultSet. 3) ExecuteNonQuery : Rerform insert, delete, update and returns integer
representing number of rows affected by operation. 4) Execute XMLReader : Returns xmlReader Obj as result of query.
(c) DataReader : It is connected, forward, read-only, stream of Data i.e. use to read sequential collection of record from db.
It is faster than DataSet but requires open connection. The DataReader we can use are : OracleDataReader, SqlDataReader, etc.
(d) DataAdapter : It is use in disconnected mode of DataAccess. It acts as a bridge between Db & DataSet & it populates the data with the data from db.
The DataAdapter provides 2 methods : (i) Fill (ii) Update
Fill : The fill method will populate dataset with value from db. Update : Update method is use to commit changes back to the db.
Vidyala
nkar
Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET
16
Q.5(c) Explain security concepts in ASP.NET. [5](A) ASP.NET SECURITY
(a) Authentication (b) Authorization. (c) Impersonation.
(a) Authentication [2 marks] (i) Window mode : (Default) done by IIS. (ii) Form mode : The data is obtained using HTML form & the Authentication rule is
specified by user itself. (iii) Passport Mode : Microsoft provides passport based authentication when user sign up
for the passport then the authentication it is stored at Microsoft server. (b) Authorization [2 marks] (i) File Based : Here the access specification is provided in a file called ACL (access
control list) the privilege of user is identified by the list. (ii) URL Based : Here the authorization specification is done in web.config file. <authorization> <[allow/deny] user role> </authorization> (c) Impersonation [1 mark] Here the process identifies itself as a legitimate user and the access the Resource.
specified in <identify> section of web.config file <configuration> <configuration> <identity impersonate = false> </configuration>
Here impersonate = false means impersonation is not supported. Q.5(d) Explain the various Data Source controls in ASP.NET. [5](A) DATA SOURCE CONTROLS IN ASP.NET
DataSource provide efficient, flexible & extensible storage for data in ASP.Net The various DataSourceControls are : 1) Access DataSource Control : [1 mark] It is used to connect to Access DB created using MS-office. Syntax : <asp : Access DataSecure id = “AccessDataSource1” runat = “server”> </asp> 2) SQLDataSource control : [1 mark] It is used to connect to sql db supported by ADO.Net. Syntax : <asp:SqlDataSource id = “SqlDataSource1” runat = “server”> </asp>
3) LinqDataSource Control : [1 mark] It is used to connect to collections of object from the application.
4) EntityDataSource contend : [1 mark] It is used to connect to dataSource in EntityDataModel supported by .Net framework.
5) XMLDataSource Control : [½ mark] It is used to connect to XML.
6) ObjectDataSource Control : [½ mark] It is used to bind data from Generic object to data controls.
Vidyala
nkar
Prelim Question Paper Solution
17
Q.6 Answer any two of the following. [10]Q.6(a) Write short notes on (i) LIN Q to Objects (ii) Linq to XML [5](A) LINQ to objects [1 mark]
The term "LINQ to Objects" refers to the use of LINQ queries with any IEnumerable or IEnumerable<T> collection directly, without the use of an intermediate LINQ provider. LINQ to Objects is used to query in-memory objects or collections of objects. LINQ to Objects is the purest form of language integration. With LINQ to Objects,
you can query collections in your .NET applications. You’re not limited to arrays because LINQ enables you to query almost any kind of
collection that exists in the .NET Framework. LINQ to Objects allows you to replace iteration logic (such as a foreach block) with a
declarative LINQ expression
public class Employee [½ mark] { //Properties
public int EmployeeID { get; set; } public string Name { get; set; } public int Age { get; set; }
public Employee(int employeeID,string name,int age) { EmployeeID = employeeID; Name = name; Age = age; }
public static List<Employee> GetEmp() {
List<Employee> employees = new List<Employee>(); employees.Add(new Employee(1, "Poonam", 35)); employees.Add(new Employee(2, "Arati", 45)); employees.Add(new Employee(3, "Deepa", 55)); employees.Add(new Employee(4, "Lakshmi", 59)); employees.Add(new Employee(5, "Raji", 67)); employees.Add(new Employee(6, "Shruti", 30)); return employees;
} } protected void Page_Load(object sender, EventArgs e) {
List<Employee> emp = Employee.GetEmp(); //Filtering var employee = from e1 in emp select e1.Name; foreach (var em in employee) Output1.Text += String.Format("<br/> {0}",em);
} LinqtoXML [1 mark] Here data soruce is an XML File. XDocument class is used to load an XML file.
<?xml version="1.0" encoding="utf-8" ?> [½ mark] <Customers>
Vidyala
nkar
Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET
18
<Customer> <id> 1</id> <name> Lakshmi </name> <age> 20 </age> <address> Sion </address> <phone> 4035468</phone> </Customer> <Customer> <id> 2 </id> <name> Poonam </name> <age> 22 </age> <address> Bhandup </address> <phone> 5213456 </phone> </Customer> <Customer> <id> 3 </id> <name> Geeta </name> <age> 35 </age> <address> Mulund </address> <phone> 5234981 </phone> </Customer> <Customer> <id> 4 </id> <name> Deepa </name> <age> 27 </age> <address> Bandra </address> <phone> 4098721 </phone> </Customer>
</Customers> public partial class LinqToXml : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string url = "XMLFile.xml";
XDocument doc=XDocument.Load(url); var names = from c in doc.Root.Elements("Customer") select c.Element("name").Value;
Output.Text = "Names of all the customers from XML files are <br/><br/>"; foreach (var v in names) Output.Text += v.ToString() + "<br/>";
} }
Q.6(b) Explain any five methods of Jquery. [5](A) JQUERY EFFECT METHOD [Any Ten - Five mark]
These methods improves look and feel of website, at client side. These are easy to use and are
1) animate( ) : It performs the specified animation for the element. 2) ClearQueue( ) : To remove all queued function for the element. 3) delay( ) : To set delay for all queued function for the element. 4) fade In( ) : It changes the opacity of the element from hidden to visible. 5) fade Out( ) : It changes the opacity of the element from visible to hidden. 6) hide( ) : It hides the specified element. 7) fade To( ) : It changes the opacity of the element to specified value. 8) show( ) : It displays the hidden elements.
Vidyala
nkar
Prelim Question Paper Solution
19
9) slide Up( ) : It slowly changes the hide of the element from visible to hidden. 10) slide Down( ) : It slowly changes the hide of the element from hidden to visible. 11) slide Toggle( ) : This method toggles between SlideUp and SlideDown of the
element. 12) stop( ) : Stop the animation of selected element. 13) Toggle : This method toggles between hide and show method for the element.
Q.6(c) Explain the use of Update Progress control and Timer Control in AJAX. [5](A) UpdateProgress [2 marks]
The UpdateProgress control provides status information about partial-page updates in UpdatePanel controls.
One can customize the default content and the layout of the UpdateProgress control. To prevent flashing when a partial-page update is very fast, one can specify a delay
before the UpdateProgress control is displayed. The UpdateProgress control helps in designing a more intuitive UI when a Web page
contains one or more UpdatePanel controls for partial-page rendering. If a partial-page update is slow, you can use the UpdateProgress control to provide
visual feedback about the status of the update. One can put multiple UpdateProgress controls on a page, each associated with a
different UpdatePanel control. Alternatively, one can use one UpdateProgress control and associate it with
all UpdatePanel controls on the page. <asp:UpdateProgress ID="UpdateProgress1" runat="server"> [1 mark] <ProgressTemplate> An update is in progress... </ProgressTemplate> </asp:UpdateProgress> Example <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void Button_Click(object sender, EventArgs e) { System.Threading.Thread.Sleep(3000); } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>UpdateProgress Example</title> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server" /> <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server"> <ContentTemplate> <%=DateTime.Now.ToString() %> <br /> <asp:Button ID="Button1" runat="server" Text="Refresh Panel" OnClick="Button_Click" />
Vidyala
nkar
Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET
20
<asp:UpdateProgress ID="UpdateProgress1" AssociatedUpdatePanelID="UpdatePanel1" runat="server"> <ProgressTemplate> UpdatePanel1 updating... </ProgressTemplate> </asp:UpdateProgress> </ContentTemplate> </asp:UpdatePanel> </div> </form> </body> </html>
Timer Control [2 marks]
The Timer control is great for executing server-side code on a repetitive basis. For ex. It can be used to update the contents of an UpdatePanel every 5
seconds. The Timer Control fires its Tick event at a specified time interval. Inside an event handler for this event, an executable code is written.
Example
<asp:UpdatePanel ID=”UpdatePanel1” runat=”server”> <ContentTemplate> <asp:Label ID=”Label1” runat=”server”></asp:Label> <asp:Timer ID=”Timer1” runat=”server” Interval=”5000” OnTick=”Timer1_Tick” /> </ContentTemplate> </asp:UpdatePanel> When the timer “ticks” it raises its Tick event, which can be handled with the following code. Protected void Timer1_Tick() { Label1.text = System.DateTime.Now.ToString(); } When this code is executed, the label will be updated with the current date and time every 5 seconds.
Q.6(d) Explain the purpose of Script Manager Control and Update Panel control. Explain
with the help of an example. [5]
(A) The Script Manager control [2 marks] It serves as a bridge between the client page and the server. It manages script resources (the javascript files used at the client), takes care of
partial page updates and handles interaction with the web site for things like web services.
This control is used directly in the content page. The ScriptManager class has multiple properties.
Properties and methods of ScriptManager
Properties DescriptionEnablePartialRendering This property determines whether the Scriptmanager
supports the partial page rendering using updatePanel control. It should be true.
Vidyala
nkar
Prelim Question Paper Solution
21
AsyncPostBackErrorMessage When an unhandled server exception occurs during postback, gets or sets the error message that is sent to the client.
AllowCustomErrorsRedirect This property determines whether errors that occur during an Aljax operation cause the customized error page to be loaded, the default is True.
Scripts The <Scripts> child elements of the ScriptManager control enables you to add additional JavaScript files that must be downloaded by the client at runtime.
Services The <Services> element enables you to define services that are accessible by you client-side pages.
The UpdatePanel control [2 marks] Is a key component in creating flicker-free pages. Just the contents have to wrapped in UpdatePanel and ScriptManager control is to be
added. Whenever one of the controls within the UpdatePanel causes a postback to the server,
only the contents within that UpdatePanel is refreshed. Ex.<asp:ScriptManager ID="ScriptManager1" runat="server"> [1mark] </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate > <asp:Label ID="Label1" runat="server"></asp:Label> <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /> </ContentTemplate> </asp:UpdatePanel> Code behind protected void Page_Load(object sender, EventArgs e) { Label1.Text = DateTime.Now.ToString(); }
Properties and methods of UpdatePanel Property Description
ChildrenAsTriggers Determines whether controls located within the UpdatePanel can cause a refresh of the UpdatePanel. The default value is true. When set as false, UpdateMode has to be set to Conditional.
Triggers The triggers collection contains PostBackTrigger and AsyncPostBacktrigger elements. The first is useful if you want to force a complete page refresh, whereas the latter is useful if you want to update an UpdatePanel with a control that is defined outside the panel.
RenderMode Can be set to Block or Inline to indicate whether UpdatePanel renders itself as a <div> or <span> element.
UpdateMode Determines whether the control, is always refreshed (the UpdateMode is always set to Always) or only under certain conditions, for ex. when one of the controls defined in the <Triggers> element is causing a postback(the UpdateMode is set to conditional)
ContentTemplate Although not visible in the Properties Grid for the UpdatePanel, the <Contenttemplate> is an important property of the UpdatgePanel. It is the container in which you place your controls as children of the UpdatePanel. If one forgets this, he gets the warning.
Vidyala
nkar
Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET
22
Q.7 Attempt the following (any THREE) [10]Q.7(a) What is method overloading? [5](A) Method overloading provides the programmer with the capability to create multiple methods
with the same name, but each working with different parameters. [2 marks]
Example: [3 marks] class abc
{ public void Disp(int a)
{ Console.WriteLine(a);
} public void Disp(int a, int b)
{ Console.WriteLine("{0}{1}", a,b);
} }
class Program {
staticvoid Main(string[] args) {
abc a1 = newabc(); a1.Disp (10);
a1.Disp (10,20); }
} Q.7(b) What are the uses of AutoPostBack and runat properties? [5](A) The AutoPostBack property is used to set or return whether or not an automatic post back
occurs when the user selects an item in a list control. If this property is set to TRUE the automatic post back is enabled, otherwise FALSE.
Default is FALSE. Syntax
<asp:SomeListControl AutoPostBack="TRUE|FALSE" runat="server"/> [2 marks]
Example: [3 marks] The following example sets the AutoPostBack property to "True" for a RadioButtonList control: <script runat="server"> Sub Change(obj As Object, e As EventArgs) Response.Write("You selected " & rb1.SelectedItem.Text) End Sub </script>
<form runat=server> <asp:RadioButtonList id="rb1" AutoPostBack="True" runat="server" OnSelectedIndexChanged="Change"> <asp:ListItem Text="Item 1" /> <asp:ListItem Text="Item 2" /> </asp:RadioButtonList> </form>
Runat: Runat='Server' Indicates the accessibility of the control at Serverside. If runat="server" is placed inside any of the control then that control cab be used at the server side. e.g : <asp:TextBox id="txt" Runat="Server"></asp:TextBox>
Vidyala
nkar
Prelim Question Paper Solution
23
Q.7(c) What is the difference between .aspx file and .cs file? Explain with an example for each.
[5]
(A) .aspx file .cs file
It is a page model where server side code is stored in the same file as markup.
A page model where server side code is stored in a separate code file.
ASPX files usually will have the User Interface and which has usually HTML tags, some ASP.NET server control embed code (which ultimately produce some HTML markups).
ASPX.CS file (usually called the code behind) will have sever side coding in C#.
In this, the .aspx file derives from the Page class.
In Code Behind, the code for the page is compiled into a separate class from which the .aspx file derives.
In this, When the page is deployed, the source code is deployed along with the Web Forms page, because it is physically in the .aspx file. However, one does not see the code, only the results are rendered when the page runs.
In Code Behind, all project class files (without the .aspx file itself) are compiled into a .dll file, which is deployed to the server without any source code. When a request for the page is received, then an instance of the project .dll file is created and executed.
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> </div> </form> </body> </html>
public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Label1.Text = "Hello.............."; } }
Q.7(d) Explain Menu and Tree view site navigation controls. [5](A) Menu Control [2 marks] The Menu control displays site navigation information in a menu. Submenus automatically
appear when the user hovers the mousse over a menu item that has a submenu. To display an application’s navigation structure, the Menu control must be bound to a
SiteMapDataSource control. The menu control can be autoformatted by clicking the Smarttag icon for the menu control.
Property Description CssClass Enables you to set a CSS class attribute that applies
to the entire control. StaticEnableDefaultPopOutImage A Boolean that determines whether images are used
to indicate submenus on the top-level menu items. DisappearAfter Determines the time in milliseconds that menu items
will remain visible after you move your mouse away from them.
DataSourceID The ID of a SiteMapDataSource control that supplies the data for the menu from the Web.sitemap file
Vidyala
nkar
Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET
24
Orientation Determines whether to use a horizontal menu with dropout submenus, or a vertical menu with fold-out submenus.
RenderingMode New in ASP.NET 4, this property determines whether the control presents itself using tables and inline styles or unordered lists and CSS styles.
Aspx code for Menu control [1 mark] <asp:Menu ID=”Menu1” Orientation=”Horizontal” runat =”Server” DataSourceID= “SiteMapDataSource1”> /asp:/Menu> TreeView Control [2 marks] A TreeView is capable of displaying a hierarchical list of items, similar to how the tree
in Windows Explorer looks. Items can be expanded and collapsed with the small plus and minus icons in front of
items that contain child elements. The data used by the TreeView control is not limited to the Web.sitemap file, however.
You can also bind it to regular XML files and even create a TreeView or its items (called nodes) programmatically.
Common properties of the TreeView
Property DescriptionCssClass Enables you to set a CSS class attribute that applies to the
entire control. CollapseImageUrl The image that collapses a part of the tree when clicked. The
default is an icon with a minus symbol on it. ExpandImageUrl The image that expands a part of the tree when clicked. The
default is an icon with a plus symbol on it. CollapseImageToolTip The tooltip that is shown when a user hovers over a collapsible
menu item. ExpandImageToolTip The tooltip that is shown when a user hovers over an
expandable menu item. Q.7(e) List the different places in the web application where ViewState field can be
disabled? [5]
(A) Viewstate can be disabled at the following places in the web application. 1. Page 2. Control 3. Application 4. Machine [2 marks]
Page <% @Page.EnableViewState=”false”/>
Control <asp : TextBox id=”Name” runat=”server” EnableViewState=”false”/>
For Application < Page enableViewState = “false” /?
For Machine <Page enableViewState=”false” enableViewStateMac=”false” />
Q.7(f) What is the use of document Ready Event and explain with example. [5](A) Document.Ready(): [3 marks]
It is used to prevent any JQuery code from running before the document is finished loading because there are few functions which can fail if they run before the document is loaded.
[3 marks] Vidyala
nkar
Prelim Question Paper Solution
25
General form- $(document).ready(function( )
{ } ); Example : [2 marks] <html> <head runat=”server”> <script type=’text/JavaScript” src=”jquery.js”> $(document).ready(function() { $(“button”).click (function() {
$( “table”).hide(); }); }); </script> </head> <body runat=”server”> <table border=1>
<tr> <td> 1</td> <td> 2</td> <td> 3</td> <td> 4</td> </tr>
</table> <input type=”button” value=”Hide”/> </body> </html>
Vidyala
nkar