vidyalankarvidyalankar.org/upload/asp._soln.pdf · 2015-07-24 · vidyalankar : t.y. b.sc. (it) –...

41
BSc/IT/TY/Pre_Pap/2015/ASP_Soln 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 mark] 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 mark] Switch (m) { case 1: x = y; case 2: x = y + m; Vidyalankar

Upload: dangkhue

Post on 07-Jul-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

BSc/IT/TY/Pre_Pap/2015/ASP_Soln 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 mark] 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 mark] Switch (m) {

case 1: x = y; case 2: x = y + m;

Vidyala

nkar

Page 2: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET

2

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: 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) What are sealed classes and sealed methods? Why are they used? [5](A) Sealed classes are the classes which can not be inherited. [1 mark]

The sealed classes are defined as follows sealed class class1

{ } class class2 : class1 //not allowed { }

Vidyala

nkar

Page 3: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Prelim Paper Solution

3

class Program { static void Main(string[] args) { } } } The line ‘class class2 : class1’ shows the following error 'class2': cannot derive from sealed type

Sealed classes may be ‘public’ or ‘internal’. Sealed Methods [1 mark]

Sealed methods are the methods which cannot be overridden. ‘sealed’ keyword is always used with ‘override’ keyword.

Example [3 mark] class A

{ public virtual void Fun() { Console.WriteLine("A"); } } class B : A { public sealed override void Fun() { Console.WriteLine("B"); } } class C : B { // public override void Fun() // { // Console.WriteLine("C"); //} } class Program { static void Main(string[] args) { // C abc = new C();

Vidyala

nkar

Page 4: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET

4

B ab = new B(); //abc.Fun(); ab.Fun(); Console.ReadLine(); } }

If these comments are removed, then compiler gives the error ‘Cannot ovverride inherited member ‘Fun’ , as it is sealed.

Q.1(c) Explain how multiple inheritance is achieved using interfaces. [5](A) When a class inherits multiple base classes, then this technique is called

as Multiple inheritance. A class cannot inherit multiple classes in C#. [1 Marks] Interface [1 Marks] So to achieve multiple inheritance, interfaces are used. Interfaces are declared in the same way to classes, but having the ‘interface’ keyword, rather than ‘class’.

interface IMyInterface [3 mark] { //interface members }

Example interface Addition { int Add(); } interface Multiplication { int Mul(); } class Computation : Addition, Multiplication { int x, y; public Computation(int x, int y) { this.x = x; this.y = y; } public int Add() {

Vidyala

nkar

Page 5: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Prelim Paper Solution

5

return (x + y); } public int Mul() { return (x * y); } }

class Program { static void Main(string[] args) { Computation com = new Computation(10, 20); Console.WriteLine("Sum = " + com.Add()); Console.WriteLine("Multiplication = " + com.Mul()); Console.ReadLine();

//OR //Computation object is cast to interface type Addition a = (Addition)com; Console.WriteLine("Sum = " + a.Add()); //Computation object is cast to interface type Multiplication m = (Multiplication)com; Console.WriteLine("Multiplication = " + m.Mul()); Console.ReadLine();

} }

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]

Vidyala

nkar

Page 6: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET

6

// Field used by property. private int myInt; // Property. public int MyIntProp { get { 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 mark] class Number {

private int myInt; // Property.

public int MyIntProp { get { return myInt; } set { // Property set code. myInt = Value; } } }

Vidyala

nkar

Page 7: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Prelim Paper Solution

7

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

Vidyala

nkar

Page 8: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET

8

[3 mark]

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) How does garbage collector work? [5](A) Garbage collector [3 mark]

The garbage collector can be considered as the heart of the .Net framework.

It manages the allocation and release of memory for any .NET application.

Garbage collector is a background thread that continuously run in the background, and at specific intervals it checks whether there are any unused objects of which memory can be reclaimed.

Every time your application instantiates a reference-type object, the CLR allocates space on the managed heap for that object.

However, you never need to clear this memory manually. As soon as your reference to an object goes out of scope (or your application ends), the object becomes available for garbage collection. The garbage collector runs periodically inside the CLR, automatically reclaiming unused memory for inaccessible objects.

Vidyala

nkar

Page 9: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Prelim Paper Solution

9

The .NET Framework provides automatic memory management called garbage collection.

A .NET program that runs in a managed environment is provided with this facility by .NET CLR(common language runtime). The purpose of using Garbage Collector is to clean up memory.

In .NET all dynamically requested memory is allocated in the heap which is maintained by CLR. The garbage collector continuously looks for heap objects that have references in order to identify which ones are accessible from the code. Any objects without reference will be removed at the time of garbage collection.

The Garbage collection is not deterministic. It is called only when the CLR decides that it is most needed. It happens in a situation such as the heap for the given process is becoming full and requires a cleanup.

Q.2(c) Delegates in C# are used for Event Handling. Justify this

statement with a relevant example program. [5]

(A) An event is a mechanism via which a class can notify its clients when something happens. Events are variables of type delegates. For example when you click a button, a button-click-event notification is sent to the window hosting the button. Events are declared using delegates. A Button is a class, when you click on it, the click event fires. A Timer is a class, every millisecond a tick event fires. Events are variables of type delegates. If you want to declare an event, you just declare a variable of type delegate and put ‘event‘ keyword before declaration, like this: public event MyDelegate1 SomeEvent;

[1 Marks]

Vidyala

nkar

Page 10: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET

10

where MyDelegate1 is the delegate name. Some event is the event name. [4 Marks]

Example : [1 mark] using System; namespace events { public delegate void EventHandler(); class Program { public static event EventHandler _click1; static void CSharp() { Console.WriteLine("C#"); } static void Java() { Console.WriteLine("Java"); } static void Linux() { Console.WriteLine("Linux"); } static void Main() { // Add event handlers to Show event. _click1 += new EventHandler(CSharp); _click1 += new EventHandler(Java); _click1 += new EventHandler(Linux);

// Invoke the event. _click1.Invoke(); Console.ReadKey(); } } } All the three delegate methods would be executed proving that the event has triggered.

Vidyala

nkar

Page 11: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Prelim Paper Solution

11

Q.2(d) Create a Console Application in C# to handle an event using Timer object.

[5]

(A) using System; [5 mark] using System.Timers; namespace aaa { class Program { static int counter = 0; static string displayString = “This string will appear one letter at a time.”; static void Main(string[] args) { Timer myTimer = new Timer(100); myTimer.Elapsed += new ElapsedEventHandler(WriteChar); myTimer.Start(); Console.ReadKey(); }

static void WriteChar(object source, ElapsedEventArgs e) { Console.Write(displayString[counter++ % displayString.Length]);

} } }

Q.3 Attempt the following (any TWO) [10]Q.3(a) Explain CheckBox and RadioButton control with their properties and

methods RadioButton [5]

(A) The RadioButton control is used to display a radio button. Radiobuttons are used to Select single option from multiple options.

[1 mark]

Property Description

AutoPostBack A Boolean value that specifies whether the form should be posted immediately after the Checked property has changed or not. Default is false

Checked A Boolean value that specifies whether the radio button is checked or not Vidyala

nkar

Page 12: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET

12

Id A unique id for the control

GroupName The name of the group to which this radio button belongs

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 (right or left)

Cleanup() Enables a server to perform final cleanup

Focus() Focuses the control.

[3 Marks]

Checkbox control [1 Marks] 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

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"

Vidyala

nkar

Page 13: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Prelim Paper Solution

13

Text The text next to the check box

TextAlign On which side of the check box the text should appear (right or left)

ValidationGroup Group of controls for which the Checkbox control causes validation when it posts back to the server

OnCheckedChanged The name of the function to be executed when the Checked property has changed

Cleanup() Enables a server to perform final cleanup

Focus() Focuses the control.

Q.3(b) Explain Button Control. [5](A) The Button Control The Button control is used to display a push button. The push button may be a

submit button or a command button. By default, this control is a submit button. A submit button does not have a command name and it posts the page back

to the server when it is clicked. It is possible to write an event handler to control the actions performed when the submit button is clicked.

A command button has a command name and allows you to create multiple

Button controls on a page. It is possible to write an event handler to control the actions performed when the command button is clicked.

The example below demonstrates a simple Button control : < html > < body > < form runat = “server” > < asp : Button id = “b1” Text = “Submit” runat = ‘server’ /> < / form > Q.3(c) Explain the importance of web.config file. [5](A) Web.config file [2 mark]

Configuration file is used to manage various settings that define a website.

Vidyala

nkar

Page 14: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET

14

The settings are stored in XML files that are separate from your application code. In this way one can configure settings independently from your code. Generally a website contains a single Web.config file stored inside the application root directory. However there can be many configuration files that manage settings at various levels within an application. Usage of configuration file: ASP.NET Configuration system is used to describe the properties and behaviors of various aspects of ASP.NET applications. Configuration files help you to manage the many settings related to your website. Each file is an XML file (with the extension .config) that contains a set of configuration elements. Configuration information is stored in XML-based text files.

Structure of Web.config : [1 mark] <configuration> <configSections> <sectionGroup> </sectionGroup> </configSections> <system.web> </system.web> <connectionStrings> </connectionStrings> <appSettings> </appSettings> .… .... </configuration> Example [2 mark] <configuration> <appSettings> <add key="appISBN" value="0-273-68726-3" /> <add key="appBook" value="Corporate Finance" /> </appSettings> <connectionStrings> <add name="booksConnectionString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\ \databinding\App_Data\books.mdb"

Vidyala

nkar

Page 15: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Prelim Paper Solution

15

providerName="System.Data.OleDb" /> </connectionStrings> <system.web> <authentication mode="[Windows|Forms|Passport|None]"> </authentication> <authorization> <allow roles = “Users” /> <deny users = “*” /> </authorization> <customErrors mode="On" defaultRedirect="session.aspx"> <error statusCode="404" redirect="Cookies.aspx" /> </customErrors> <caching> <cache>.....</cache> <outputCache>...</outputCache> <outputCacheSettings>...</outputCacheSettings> <sqlCacheDependency>...</sqlCacheDependency> </caching> <pages enableSessionState= “true”> <controls> <add tagPrefix="asp" namespace="System.Web.UI"/> </controls> </pages> </system.web> </configuration> The <appSettings> section is used to store key-value pairs of data. Authentication mode for the application can also be set in this file under <Authentication> section. <CustomeErrors> section is used to specify the application-wide error information. <pages> section allows to enable or disable the SessionState. <add> tag under <pages> section under <controls> subsection allows to

add the tagPrefix for the user defined Controls.

Vidyala

nkar

Page 16: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET

16

Q.3(d) What are the different types of events in global.asax file? [5](A) The Global.asax contains following events : [5 mark]

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. 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) CompareValidator

[5]Vidyala

nkar

Page 17: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Prelim Paper Solution

17

(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

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"

Vidyala

nkar

Page 18: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET

18

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

Page 19: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Prelim Paper Solution

19

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 mark] 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) Write a note on cookies. Explain how to create and read cookies? [5](A) Cookies are used as client side state management technique.

It is a text file stored on the client side that the browser uses to store the textual information.

Vidyala

nkar

Page 20: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET

20

Thses files store data as a name-value pairs. There are two types of cookies in ASP.NET. temporary cookies and

permanenet cookies. A temporary cookie is alive in main memory for as long as the user’s

session is alive. It expires as soon as the session terminates or the web beowser is closed.

A permanent cookie is stored uptill the expiration date and time set. It gets deleted automaticalluy when the expiration date and time is

reaached. HttpCookie class is used to work with Cookies. Request.Cookies collection is used to read the cookies. Response.Cookies collection is used to write thje cookies. [3 Marks]

Creting cookie using the response object [2 Marks] //write cookies protected void btnWrite_Click(object sender, EventArgs e) { HttpCookie cookie1 = Request.Cookies["UserInfo1"]; if (cookie1 == null) // checking whether the cookie exists or not, if not then create { userCookie1 = new HttpCookie("UserInfo1"); userCookie1["username"] = TextBox1.Text; userCookie1["password"] = TextBox2.Text; userCookie1.Expires=DateTime.Now.AddDays(3); Response.Cookies.Add(userCookie1); Label1.Text = "Cookie creation successful!<br><br/>"; } } //read cookies protected void btnRead_Click(object sender, EventArgs e) { HttpCookie cookie1 = Request.Cookies["UserInfo1"]; if (cookie1 != null) { string username = cookie1["username"]; string password = cookie1["password"]; TextBox1.Text = username; TextBox2.Text = password; } }

}

Vidyala

nkar

Page 21: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Prelim Paper Solution

21

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

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]

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 Marks] 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.

Vidyala

nkar

Page 22: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET

22

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 Description

Connection The SqlConnection object used to connect to database.

Command Text The text of the SQL statement Method Description

ExecuteReader 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 Marks]

Property Description SelectCommand 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.

Vidyala

nkar

Page 23: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Prelim Paper Solution

23

Method Description Fill 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.

Q.5(b) List all the steps in order to access a database through ADO.NET. [5](A) Import the namespace using System.Data.SqlClient ;

2. Create the SQLConnection class’s object SqlConnection conn = new SqlConnection(); 3. In the Button_Click or Page_Load event set the ConnectionString

property of connection object in the following way. conn.ConnectionString = ("Data Source=ACER-PC;Initial Catalog=master;Integrated SQLDataAdapt 4. Write the SQL query and store in a string variable. statmnt = "Select * from Product1"; 5. Instantiate the SQLDataAdapter class and set the Selectcommand

property. SqlDataAdapter adapter = new SqlDataAdapter();

adapter.SelectCommand = new SqlCommand(statmnt, conn); 6. Instantiate the DataSet class Dataset ds = new DataSet 7. In the button_click event or Page_Laod event , write the following code

and design the DataGridView control in the design view. using System.Data.SqlClient ; //using System.Data; public partial class _Default : System.Web.UI.Page { string statmnt = " "; SqlDataAdapter adapter = new SqlDataAdapter(); SqlConnection conn = new SqlConnection(); DataSet ds = new DataSet();

protected void Button1_Click(object sender, EventArgs e) { conn.ConnectionString = ("Data Source=ACER-PC;Initial Catalog=master;Integrated Security=True"); statmnt = "Select * from Product1";

Vidyala

nkar

Page 24: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET

24

adapter.SelectCommand = new SqlCommand(statmnt, conn); conn.Open(); adapter.Fill(ds, "Prd"); conn.Close(); GridView3.DataSource = ds; GridView3.DataBind(); } }

Q.5(c) List and explain various templates provided by ListView control. [5](A) [Listing 1 Marks, Explanation 4 marks] LayoutTemplate

Identifies the root template that defines the main layout of the control. It contains a placeholder object, such as a table row (tr), div, or span element. This element will be replaced with the content that is defined in the ItemTemplate template or in the GroupTemplate template. It might also contain a DataPager object.

ItemTemplate Identifies the data-bound content to display for single items. ItemSeparatorTemplate

Identifies the content to render between single items.

GroupTemplate Identifies the content for the group layout. It contains a placeholder object, such as a table cell (td), div, or span that will be replaced with the content defined in the other templates, such as the ItemTemplate and EmptyItemTemplate templates.

GroupSeparatorTemplate Identifies the content to render between groups of items.

EmptyItemTemplate Identifies the content to render for an empty item when a GroupTemplate template is used. For example, if the GroupItemCount property is set to 5, and the total number of items returned from the data source is 8, the last row of data displayed by the ListView control will contain three items as specified by the ItemTemplate template, and two items as specified by the EmptyItemTemplate template.

Vidyala

nkar

Page 25: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Prelim Paper Solution

25

SelectedItemTemplate Identifies the content to render for the selected data item to differentiate the selected item from the other displayed items.

AlternatingItemTemplate Identifies the content to render for alternating items to make it easier to distinguish between consecutive items.

Q.5(d) Write the steps with sample code to use windows authentication [5](A) To configure the ASP.NET application to recognize authenticated users, you

must change the Web.config file. In the Web.config file, locate the <authentication> tag, and then set the mode attribute to Windows, as in the following example: [1 Marks] <authentication mode="Windows" /> .config file is used to apply the authentication and authorization mechanics in applications. The <authentication> Node [4 mark] The <authentication> node is used in the application's web.config file to set the type of authentication your ASP.NET application requires: <system.web> <authentication mode="Windows|Forms|Passport|None"> </authentication> </system.web> Authenticating and Authorizing a User Now create an application that enables the user to enter it. You work with the application's web.config file to control which users are allowed to access the site and which users are not allowed. Add the section presented in Listing 1 to your web.config file. Listing 1: Denying all users through the web.config file <system.web> <authentication mode="Windows" /> <authorization> <deny users="*" /> </authorization> </system.web>

Vidyala

nkar

Page 26: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET

26

Any end user — authenticated or not — who tries to access the site sees a large "Access is denied" statement in his browser window, which is just for those not allowed to access the application! In most instances,if at least some users is allowed to access your application. Use the <allow> element in the web.config file to allow a specific user. Here is the syntax: <allow users="Domain\Username" /> Example : Allowing a single user through the web.config file <system.web> <authentication mode="Windows" /> <authorization> <allow users="REUTERS-EVJEN\Bubbles" /> <deny users="*" /> </authorization> </system.web>

Q.6 Answer any two of the following. [10]Q.6(a) Write short notes on (i) LINQ to Objects (ii) Linq to XML

explanation of Linq to Obejcts 1mk [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)

Vidyala

nkar

Page 27: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Prelim Paper Solution

27

{ 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> <Customer> <id> 1</id> <name> Lakshmi </name> <age> 20 </age> <address> Sion </address> <phone> 4035468</phone> </Customer>

Vidyala

nkar

Page 28: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET

28

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

} }

Vidyala

nkar

Page 29: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Prelim Paper Solution

29

Q.6(b) Explain the terms Take, Skip, TakeWhile, SkipWhile, First,FirstOrDefault, Last, LastOrDefault, Single, singleOrDefault withrespect to LINQ.

[5]

(A)

Skip The Skip operator skips a given number of elements from a sequence and then yields the remainder of the sequence.

SkipWhile The SkipWhile operator skips elements from a sequence while a test is true and then yields the remainder of the sequence.

Take The Take operator yields a given number of elements from a sequence and then skips the remainder of the sequence.

TakeWhile The TakeWhile operator yields elements from a sequence while a test is true and then skips the remainder of the sequence.

First The First operator returns the first element of a sequence.

FirstOrDefault The FirstOrDefault operator returns the first element of a sequence, or a default value if no element is found.

Last The Last operator returns the last element of a sequence.

LastOrDefault The LastOrDefault operator returns the last element of a sequence, or a default value if no element is found.

Single The Single operator returns the single element of a sequence.

SingleOrDefault The SingleOrDefault operator returns the single element of a sequence, or a default value if no element is found.

Q.6(c) Explain the use of UpdateProgress 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.

Vidyala

nkar

Page 30: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET

30

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

Page 31: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Prelim Paper Solution

31

<asp:UpdateProgress ID="UpdateProgress1" AssociatedUpdatePanelID="UpdatePanel1" runat="server"> <ProgressTemplate> UpdatePanel1 updating... </ProgressTemplate> </asp:UpdateProgress> </ContentTemplate> </asp:UpdatePanel> </div> </form> </body> </html>

Timer Control [2 mark]

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.

Vidyala

nkar

Page 32: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET

32

Q.6(d) Explain the purpose of ScriptManager Control and Update Panel control. Explain with the help of an example.

[5]

(A) The ScriptManager control [2 mark] 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 Description EnablePartialRendering This property determines whether the

Scriptmanager supports the partial page rendering using updatePanel control. It should be true.

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 youy client-side pages.

The UpdatePanel control [2 mark] 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 >

Vidyala

nkar

Page 33: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Prelim Paper Solution

33

<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

Page 34: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET

34

Q.7 Attempt the following (any THREE) [10]Q.7(a) Draw and explain .NET framework architecture. [5](A)    .NET framework architecture                           [4 mark]

net Framework is a platform for development, deployment and execution of the application.

A programming infrastructure created by Microsoft for building, deploying, and running applications and services that use .NET technologies, such as desktop applications and Web services.

.NET Framework is a software framework developed by Microsoft that runs primarily on Microsoft Windows.

.net Framework has multiple components CLS – Common Language specification CLR – common language runtime FCL – Framework class library At the base of the diagram is the operating system, which technically can be any platform but typically Microsoft windows. CLS – Common Language Specification The CLS is a common platform that integrates code and components

from multiple .NET programming languages. a .net application can be written in multiple programming languages with

no extra work by the developer. CLS ensures complete interoperability among applications, regardless of

the language used to create the application. These applications written in different programming languages get

compiled to common intermediate language and can work together in the same application.

FCL Is a collection of over 7000 classes and data types that enable .NET

applications to read and write files, access databases, process XML, display a graphical user interface, draw graphics, use web services, etc.

TheFCL wraps much of the massive, Windows API(application programming interface) into more simple .NET objects that can be used by C# and other .NET programming languages.

CLR The Common Language Runtime (CLR) is the common Execution (Runtime)

Environment. It works as a layer between Operating Systems and the applications

written in .Net compliant languages.

Vidyala

nkar

Page 35: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Prelim Paper Solution

35

The main function of Common Language Runtime (CLR) is to convert the Managed Code into native code and then execute the Program. CLR provides many services like

Code management Memory management Verification of type safety Conversion of MSIL to native code Loading and execution of managed code Insertion and execution of security checks Handling cross-language exceptions

.Net languages .Net includes new object oriented programming languages such as C#,

vb.net, J# and managed C++. These languages all compile to MSIL and work together in a single

application.                                                                 

[1 Marks]

Vidyala

nkar

Page 36: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET

36

Q.7(b) Explain asp.net Page life Cycle. [5](A) Different phases and the events triggered in that phase [5 mark]

Between the time a request is sent to the web server and the time the response is sent back to the web browser, a lot of events are executed one after the other. These events are associated with their respective event handlers.

Phase Description

Page request

A request to aspx page starts the life cycle of the page.

Start In this phase, the page gets access to properties like request and response that are used to interact with the page’s environment. During this phse, the PreInit event is raised to signal that the page is about to go into the initialization phase.

Page initialization

Dusing this phase , the controls those are set up in the page become available. The Page class fires three events at this stage – Init, InitComplete, PreLoad. Also during this phase, the control properties are loaded form the viewstate again during a pagepostback. So for example, when the selected element from the dropdownlikst is changed, then the postback is caused by clicking any button, and this is the moment the correct element gets preselected in the dropdownlist again.

Load During this phase, the page raises the Load event. Validation In this phase, the validation controls used to validate user

inputs are processed. Post back event handling

The controls in the page may raise their own events. When all event processing is done, the page raises the Page_LoadComplete event. During this phase, the Prerender event is raised to signal that the page is about to render to the browser. Shortly after that, PrerenderComplete event SaveStateComplete event is raised to indicate that the page is done storing all relevent data for the control in Viewstate.

Rendering It is the phase where the controls (and the page itself) output their HTML to the browser.

Unload It is the cleanup phase.. page and controls release their resourses like database connections. During this phase, the Unload event is raised.

Vidyala

nkar

Page 37: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Prelim Paper Solution

37

Q.7(c) What is the difference between .aspx file and .cs file? Explain withan 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.............."; } }

Vidyala

nkar

Page 38: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET

38

Q.7(d) Explain Menu and Treeview site navigation controls. [5](A) Menu Control [2 mark] 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

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 mark] A TreeView is capable of displaying a hierarchical list of items, similar

to how the tree in Windows Explorer looks.

Vidyala

nkar

Page 39: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Prelim Paper Solution

39

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 Description CssClass 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) Explain the terms authentication, authorization and impersonation

with respect to ASP.NET security. [5]

(A) [Explanation Marks] Authentication is the process of obtaining identification credentials such as name and password from a user and validating those credentials against some authority. If the credentials are valid, the entity that submitted the credentials is considered an authenticated identity.

There are three ways of doing authentication and authorization in ASP.NET: Windows authentication:

In this methodology ASP.NET web pages will use local windows users and groups to authenticate and authorize resources.

Forms Authentication: This is a cookie based authentication where username and password are stored on client machines as cookie files or they are sent through URL for every request. Form-based authentication presents the user with an HTML-based Web page that prompts the user for credentials.

Vidyala

nkar

Page 40: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET

40

Passport authentication: Passport authentication is based on the passport website provided by the Microsoft .So when user logins with credentials it will be reached to the passport website (i.e. hotmail, devhood, windows live etc) where uthentication will happen. If Authentication is successful it will return a token to your website.

Anonymous access: If you do not want any kind of authentication then you will go for Anonymous access.

Authorization To enable a specified authentication provider for an ASP.NET application, you must create an entry in the application's configuration file as follows: // web.config file <authentication mode = "[Windows/Forms/Passport/None]"> </authentication> Authorization determines whether an identity should be granted access to a specific resource. Web.config [2 mark] <configuration> <system.web> <authorization> <allow users = “*” /> </authorization> </system.web> </configuration> Impersonation By default ASP.NET executes in the security context of a restricted user account on the local machine. Sometimes one needs to access network resources such as a file on a shared drive, which requires additional permissions. One way to overcome this restriction is to use impersonation. With impersonation, ASP.NET can execute the request using the identity of the client who is making the request or ASP.NET can impersonate a specific account you specify in web.config. Web.config <configuration> <system.web> <identity impersonate=”true”> </system.web> </configuration>

Vidyala

nkar

Page 41: Vidyalankarvidyalankar.org/upload/ASP._Soln.pdf · 2015-07-24 · Vidyalankar : T.Y. B.Sc. (IT) – ASP.NET 8 [3 mark] Manifest It describes the assembly. The manifest file contains

Prelim Paper Solution

41

Q.7(f) What is the difference between SQL and LINQ? List the advantages of using LINQ.

[5]

(A) [3 mark] LINQ SQL

LINQ stands for Language Integrated Query

SQL stands for Structured Query Language

LINQ statements are verified during compile time.

SQL statements used in the application gets verified only at the runtime.

To use LINQ, one can depend upon .net language syntaxes and also can consume base class library functionalities.

To use SQL, one needs to be familier with SQL syntaxes and also the predefined functions of SQL like MAX, MIN. LEN etc.

LINQ statements can be debugged as they execute under framework environment.

As SQL statement executes on the database server, debugging of the code is not possible.

Advantages of LINQ [2 mark] LINQ provides unified model for accessing data in various data sources. Because LINQ queries are integrated into the C# language, it is possible

for you to write code much faster than writing old style queries. In some cases, developers have seen their development time cut in half.

The integration of queries into the C# language also makes it easy to step through the queries with the integrated debugger.

LINQ queries are compiled at compile time and hence there is reduction in complexity.

Because LINQ is extensible, one can use the knowledge of LINQ to make new types of data sources queriable.

Because LINQ is composable, one can easily join multiple data sources in a single query, or in a series of related queries.

The composable feature of LINQ also makes it easy to break complex problems into a series of short, comprehensible queries that are easy to debug.

 

Vidy

alank

ar