page 1 38 maharashtra state board of...
TRANSCRIPT
Page 1 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
Q1.A)
(i) (Correct diagram – 2Marks, two component explanation 1 mark each)
The .NET Framework consists of
i. the CLR, ii. the .NET Framework Class Library, iii. the Common Language Specification (CLS), iv. a number of .NET languages, and v. Visual Studio.NET
Common Language Runtime
A runtime provides services to executing programs. Traditionally, different
programming environments have different runtimes. Examples of runtimes include the
standard C library, MFC, the Visual Basic runtime, and the Java Virtual Machine (JVM).
The runtime environment provided by .NET, the CLR, manages the execution of code
and provides useful services. The services of the CLR are exposed through programming
languages. The syntax for these services varies from language to language, but the
underlying execution engine providing the services is the same.
Not all languages expose all the features of the CLR. The language with the best
mapping to the CLR is the new language C#. VB.NET, however, does an admirable job of
exposing the functionality.
.NET Framework Class Library
The .NET Framework class library is huge, comprising more than 2,500 classes. All this
functionality is available to all the .NET languages. The library consists of four main parts:
1. Base class library (which includes networking, security, diagnostics, I/O, and
other types of operating system services)
2. Data and XML classes
3. Windows UI
4. Web services and Web UI
Page 2 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
Common Language Specification
An important goal of the .NET Framework is to support multiple languages. But all
languages are not created equal, so it is important to agree upon a common subset that all
languages will support. The CLS is an agreement among language designers and class
library designers about those features and usage conventions that can be relied upon.
CLS rules apply to public features that are visible outside the assembly where they are
defined. (An assembly can be thought of as a logical EXE or DLL and will be discussed later
in this chapter.) For example, the CLS requires that public names do not rely on case for
uniqueness, because some languages are not case sensitive.
Languages in .NET
A language is a CLS-compliant consumer if it can use any CLS-compliant type—that
is, if it can call methods, create instances of types, and so on. (A type is basically a class in
most object-oriented languages, providing an abstraction of data and behavior, grouped
together.) A language is a CLS-compliant extender if it is a consumer and can also extend
any CLS-compliant base class, implement any CLS-compliant interface, and so on.
Microsoft itself is providing four CLS-compliant languages. VB.NET, C#, and C++
with Managed Extensions are extenders. JScript.NET is a consumer. Third parties are
providing additional languages (more than a dozen so far). Active-State is implementing Perl
and Python. Fujitsu is implementing COBOL. It should be noted that at present some of
these languages are not .NET languages in the strict sense. For example, ActiveState
provides a tool called PerlNET that will create a .NET component from a Perl class. This
facility enables .NET applications to call the wealth of Perl modules, but it does not make
Perl into either a consumer or an extender. For more information on
PerlNET, see the book Programming Perl in the .NET Environment (Saltzman, Oberg), another
book in The Integrated .NET Series.
Note: Any Two descriptions can be considered
(ii)Difference between VB and VB.Net
VB.NET is what it got transformed into under the Microsoft .NET framework and VB is an obsolete language.
VB6 used ASP to build web applications where as VB.NET uses ASP.NET to build
web applications. However, VB.NET,C++.NET and C# all compile into the same .NET code – in a
certain sense it is almost like they are the same language. The greatest change in VB.NET and VB6 is of runtime environment. VB6 used the
VB-Runtime while running the program but VB.NET uses the .Net Common Language Runtime (.Net CLR).In comparison to VB-Runtime, the CLR is much better designed and implemented.VB-Runtime interprets the code while the CLR uses better code translation through Just in Time compiler. In comparison to VB6,the CLR Garbage Collector is also more efficient one as it may detect cyclic references too.
VB6 was interpreter based language while VB.NET is a compiled language and the VB6 was not a type-safe language while VB.NET is a type safe language. There is no magical type conversions in VB.NET and variant type happen in VB.NET
Page 3 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
VB6 used ‗On Error Goto‘ syntax to handle exceptions at runtime. VB.NET uses the Try….Catch. At runtime, finally syntax is used to handle exceptions.
In VB6, a lot of code (like user interface code) was hidden from developer. In VB.NET no code is hidden from developer and you can access and control each part of your application
VB.NET has much enhanced object oriented support than VB6. VB6 does not allow developing the multithreaded applications but in VB.NET you can
create multi threaded applications. VB6 was only considered good for desktop windows application but in VB.NET you
can also develop web applications, distributed applications, create .NET windows and web controls and components, write windows and web services.
In VB.NET, to read the meta-data of types, reflections is used and using reflection emit you can also generate code to invoke and define types at runtime.
VB.NET uses .NET framework class library along with specialized VB library (System.VisualBasic) as a standard library and so that the standard library for VB.NET is much enhanced and useful compared to VB6 standard library
VB.NET is platform independent because of .Net framework and programs written in VB.NET can run on any platform where .Net framework is present. The platform includes both software (operating system) and hardware platforms.
VB.NET also supports language interoperability with various .NET compliant languages and this means that you can use and enhance the code written in other .NET compliant languages. Similarly the code written in VB.NET can also be used and enhanced by other .NET compliant languages. Although VB6 also provided this functionality through COM but it was limited and difficult to use and manage. VB.Net makes it easier because of the presence of Intermediate Language (IL) and Common Language Specification (CLS) of the .NET architecture.
VB6 uses COM (Component Object Model) as component architecture where as VB.NET uses assemblies as its component architecture and the Assemblies architecture has removed a lot of problems with COM including DLL-Hell and versioning problem.
Components created in VB6 (COM) need to update and make registry entries. VB.NET does not require any registry entry which makes the deployment easier
VB6 used record-sets and ADODB to implement data access applications where as VB.NET uses ADO.NET and datasets to build data access applications. And also the ADO.NET also supports the disconnected data access.
(½ marks per correct point)
Note: Any 8 point can be considered
(iii) (Correct Diagram – 1 mark, Data Provider Explanation – 1 Marks, Data Set
Explanation – 1Marks and XML –ado,net Explanation – 1Mark)
The architecture of ADO.net in which data retrieved from database can be accessed even
when connection to database was closed is called as disconnected architecture.
ADO.NET Components There are two components of ADO.NET that you can use to access and manipulate
data: .NET Framework data providers The DataSet
.NET Framework Data Providers The .NET Framework Data Providers are components that have been explicitly
designed for data manipulation and fast, forward-only, read-only access to data. The
Page 4 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
Connection object provides connectivity to a data source. The Command object enables access to database commands to return data, modify data, run stored procedures, and send or retrieve parameter information. The DataReader provides a
high-performance stream of data from the data source. Finally, the DataAdapter provides the bridge between the DataSet object and the data source. The
DataAdapter uses Command objects to execute SQL commands at the data source to both load the DataSet with data, and reconcile changes made to the data in the DataSet back to the data source.
The DataSet
The ADO.NET DataSet is explicitly designed for data access independent of any data source. As a result, it can be used with multiple and differing data sources, used with XML data, or used to manage data local to the application. The
DataSet contains a collection of one or more DataTable objects made up of rows and columns of data, as well as primary key, foreign key, constraint, and relation information about the data in the DataTable objects.
The following diagram illustrates the relationship between a .NET Framework data provider and a DataSet.
ADO.NET architecture
Choosing a DataReader or a DataSet When deciding whether your application should use a DataReader or a DataSet,
you should consider the type of functionality that your application requires. Use a
DataSet to do the following: Cache data locally in your application so that you can manipulate it. If you
only need to read the results of a query, the DataReader is the better choice. Remote data between tiers or from an XML Web service. Interact with data dynamically such as binding to a Windows Forms control
or combining and relating data from multiple sources.
Page 5 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
Perform extensive processing on data without requiring an open connection to the data source, which frees the connection to be used by other clients.
If you do not require the functionality provided by the DataSet, you can improve the
performance of your application by using the DataReader to return your data in a forward-only, read-only fashion. Although the DataAdapter uses the DataReader to
fill the contents of a DataSet, by using the DataReader you can boost performance because you will save memory that would be consumed by the DataSet, as well as avoid the processing required to create and fill the contents of the DataSet.
XML and ADO.NET
ADO.NET leverages the power of XML to provide disconnected access to data. ADO.NET was designed hand-in-hand with the XML classes in the .NET Framework; both are components of a single architecture.
ADO.NET and the XML classes in the .NET Framework converge in the DataSet object. The DataSet can be populated with data from an XML source, whether it is a file or an XML stream. The DataSet can be written as World-Wide
Web Consortium (W3C) compliant XML, including its schema as XML Schema definition language (XSD) schema, regardless of the source of the data in the
DataSet. Because of the native serialization format of the DataSet is XML, it is an excellent medium for moving data between tiers, making the DataSet an optimal choice for remoting data and schema context to and from an XML Web service.
(iv) Difference between ASp and ASP.Net
(1/2 marks per correct point)
ASP:
1) ASP is Interpreted language based on scripting languages like Jscript or VBScript.
2) ASP has Mixed HTML and coding logic.
3) Limited development and debugging tools available.
4) Limited OOPS support.
5) Limited Session and Application state management.
6) Poor Error-Handling Mechanism.
7) No in-built support for XML.
8) No fully distributed data source support.
ASP.Net:
1) ASP.Net is supported by compiler and has compiled language support.
2) Separate code and design logic possible.
3) Variety of compilers and tools available including the Visual studio.Net.
4) Completely Object Oriented Support.
5) Complete Session and Application state management.
6) Full proof Error-Handling Mechanism.
7) Full XML Support for easy data exchange.
8) Fully distributed data source support
Page 6 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
b)
(i)
(If then else syntax – 1marks, Explanation – 1Marks, Code -1 Marks)
(Select case syntax – 1marks, Explanation – 1Marks, Code -1 Marks)
Syntax of If-Then-Else
If condition Then
[statements] [ElseIf condition-n Then
[elseifstatements] …] [Else [elsestatements]]
End If
You use comparison operators in the condition here to generate a logical result that's true or false; for example, if condition is intVariable > 5, then condition
will be true if the value in intVariable is greater than 5.
If condition is True, the statements immediately following the Then keyword in the body of the If statement will be executed, and the If statement will terminate
before the code in any ElseIf or Else statement is executed. If condition is False, the following ElseIf statements are evaluated, if there are any; this statement lets you
test additional conditions, and if any are True, the corresponding code (elseifstatements above) is executed and the If statement terminates. If there are no ElseIf statements, or if none of their conditions are True, the code in the Else
statement (elsestatements above), if there is one, is executed automatically. Example of case select
Module Module1 Sub Main() Dim intInput As Integer
System.Console.WriteLine("Enter an integer…") intInput = Val(System.Console.ReadLine())
If intInput = 1 Then System.Console.WriteLine("Thank you.") ElseIf intInput = 2 Then
System.Console.WriteLine("That's fine.") ElseIf intInput = 3 Then
System.Console.WriteLine("Too big.") Else System.Console.WriteLine("Not a number I know.")
End If End Sub End Module
Note: Related example can be considered
Page 7 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
Syntax of Select case statement
select Case testexpression
[Case expressionlist-n [statements-n]]…
[Case Else [elsestatements]]
End Select
Use multiple Case statements in a Select statement, each specifying a different value to test against textexpression, and the code in the Case statement
that matches is executed.
The Select Is keyword, which you can use like this: Case Is condition, allowing you to test testexpression against some condition (such as Case Is > 7). You can also test testexpression against a range of values with the To keyword (such as Case 4
To 7). And Case Else can handle values we don't explicitly provide code for-it's just like the Else statement in an If…Then statement, because the code in it is executed
if no other case matches. Here's the code: Example of Select case
Module Module1 Sub Main()
Dim intInput As Integer System.Console.WriteLine("Enter an integer…") intInput = Val(System.Console.ReadLine())
Select Case intInput Case 1 System.Console.WriteLine("Thank you.")
Case 2 System.Console.WriteLine("That's fine.")
Case 3 System.Console.WriteLine("OK.") Case 4 To 7
System.Console.WriteLine("In the range 4 to 7.") Case Is > 7
System.Console.WriteLine("Definitely too big.") Case Else System.Console.WriteLine("Not a number I know.")
End Select End Sub End Module
Note: Related example can be considered
Page 8 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
(ii)
(Correct code and any three properties – 6marks)
Class rumtimelabelcreation
Private sub form1_load(byval sender as system.object, byval e as system.eventargs)
Dim labeL1 as new Label() Label1.text = ―MyLabelRuntime‖ Label1.Location = new Point(175,100)
Label1.size = new Size(50,150); Me.controls.add(Label1)
End sub
End class Note: Related example can be considered. Any three properties can be cosndiered.
Q.2
a) (AdRotator – description with properties – 2Marks)
ADrotator
Use the AdRotator control to display a randomly or sequentially selected advertisement banner on the Web page. The displayed advertisement changes whenever the page refreshes.
Advertisement information is stored in a separate XML file. The XML file allows you to maintain a list of advertisements and their associated attributes. Attributes included are as follows
Element Description
<ImageUrl> The path to the image file or image to be displayed
<NavigateUrl> The URL to link to if the user clicks the ad
<AlternateText> An alternate text to display when the image is not available
<Keyword> A category for the ad
<Impressions> The display rates in percent of the hits
(Correct description of any four parameter – 2 Marks)
Following are the properties of the adrotator
Property Description
Advertisement File Specifies the path to the XML file that contains ad
information
AlternateTextField Specifies a data field to be used instead of the Alt text for an
ad
ImageUrlField Specifies a data field to be used instead of the ImageURL
Page 9 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
attribute for an ad
KeywordFilter Specifies a filter to limit ads after categories
NavigateUrlField Specifies a data field to be used instead of the NavigateUrl
attribute for an ad
runat Specifies that the control is a server control. Must be set to
"server"
Target Specifies where to open the URL
Example of Ad rotator : Asp.Net Code for Adrotator
(Correct code – 1 Marks) <%@ Page Language="VB" AutoEventWireup="True" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>AdRotator Example</title> </head>
<body> <form id="form1" runat="server">
<h3>AdRotator Example</h3>
<asp:AdRotator id="AdRotator1" runat="server" Target="_self AdvertisementFile="~/App_Data/Ads.xml"/>
</form> </body>
</html>
Note: Related example can be considered
XML: file for the above ad rotator code(Ads.XML)
(Correct XML file – 1mark)
The following code example demonstrates the file format for an XML file that contains advertisement information for the previous example. For more information
on the file format, see the Advertisement File member. <Advertisements> <Ad>
<ImageUrl>~/Images/image1.jpg</ImageUrl> <height>60</height>
Page 10 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
<width>190</width> <NavigateUrl>http://www.microsoft.com</NavigateUrl> <AlternateText>Microsoft Main Site</AlternateText>
<Impressions>80</Impressions> <Keyword>Topic1</Keyword>
</Ad> <Ad> <ImageUrl>~/Images/image2.jpg</ImageUrl>
<height>90</height> <width>90</width>
<NavigateUrl>http://www.wingtiptoys.com</NavigateUrl> <AlternateText>Wingtip Toys</AlternateText> <Impressions>80</Impressions>
<Keyword>Topic2</Keyword> </Ad> </Advertisements>
Browser Capabilities
(Explanation with 4 properties and Code related to 4 properties - 2 marks)
ASP.NET determines the capabilities of the browser with which a user is browsing your site using a feature called ‗browser capabilities‘. Following are the properties of the Browser capabilities
There are two ways to implement browser capabilities
1. Using sever object (used in ASP and ASP.net both)
2. Using request object (Used in ASP.NET)
When a client requests a page from the server, the HTTP header includes a user agent ASCII string that specifies the browser software name and version. Browser capabilities component search for this string in the Browser capabilities component
and the server adopts the properties of the browser.
Property/Method Type Purpose
ActiveXControls Bool Support for ActiveX controls
AOL Bool America Online browser
BackgroundSounds Bool Support for background sounds
Beta Bool Beta version
Browser String Name of the browser
ClrVersion Version Version number of the latest .NET Framework installed on the
client
Cookies Bool Support for cookies (though not whether cookies are disabled)
Crawler Bool Client is a search engine Web crawler
Page 11 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
Frames Bool Support for frames
JavaApplets Bool Support for Java applets
JavaScript Bool Support for JavaScript blocks
MajorVersion Integer Major version of the browser
MinorVersion Integer Minor version of the browser
MSDomVersion Version Version of the Microsoft HTML (MSHTML) Document Object
Model (DOM) is supported by the client
Platform String Operating system running the browser
Tables Bool Support for tables
Type String Browser name and major version number
VBScript Bool Support for VBScript
Version String Full version number of the browser
Note: Any four properties can be considered in description and example
Example of Browser Capabilities
<%@ Page Language="vb" %>
<%@ Import Namespace="System.Web" %>
<html><head>
<title>Determining Browser Capabilities in ASP.NET: Demo</title></head>
<body>
<%
Dim objBrowser As HTTPBrowserCapabilities
objBrowser = Request.Browser
%>
<p align = center>
<b>Determining Browser Capabilities in ASP.NET: Demo</b></p>
<TABLE>
<% With objBrowser %>
<tr>
<td><b>Browser type:</b></td><td><%=.Type %>
</td></tr>
<tr>
<td><b>Browser version:</b></TD><td> <%=.Version%>
</td>
</tr>
<tr>
<td><b>Major version:</b></TD><td> <%=.MajorVersion%>
</td>
</tr>
<tr>
Page 12 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
<td><b>Minor version:</b></TD><td> <%=.MajorVersion%></td></tr>
<tr>
<td><b>Platform:</b></TD><td> <%=.Platform%></td>
</tr>
<tr>
<td><b>This is a Win16 Platform:</b></TD><td> <%=iif(.Win16, "Yes", "No")%></td>
</tr>
<tr>
<td><b>This is a Win32 Platform:</b></TD><td> <%=iif(.Win32, "Yes", "No")%></td>
</tr>
<tr>
<td><b>Tables Supported:</b></TD><td> <%=iif(.Tables, "Yes", "No")%></td>
</tr>
<tr>
<td><b>Frames Supported:</b></TD><td> <%=iif(.Frames, "Yes", "No")%></td>
</tr>
<tr>
<td><b>Background Sounds Supported:</b></TD><td> <%=iif(.BackgroundSounds, "Yes",
"No")%></td>
</tr>
<tr>
<td><b>Cookies Supported:</b></TD><td> <%=iif(.Cookies, "Yes", "No")%></td>
</tr>
<tr>
<td><b>Java Script Supported:</b></TD><td> <%=iif(.JavaScript, "Yes", "No")%></td>
</tr>
<tr>
<td><b>Java Applets Supported:</b></TD><td> <%=iif(.JavaApplets, "Yes", "No")%></td>
</tr>
<tr>
<td><b>VB Script Supported:</b></TD><td> <%=iif(.VBScript, "Yes", "No")%></td>
</tr>
<tr>
<td><b>Active X Controls Supported:</b></TD><td> <%=iif(.ActiveXControls, "Yes",
"No")%></td>
</tr>
<tr>
<td><b>AOL Client:</b></TD><td> <%=iif(.AOL, "Yes", "No")%></td>
</tr>
<tr>
<td><b>Browser is a Search-Engine Crawler:</b></TD><td> <%=iif(.Crawler, "Yes",
"No")%></td>
</tr>
<tr>
<td><b>Browser is a Beta Version:</b></TD><td> <%=iif(.Beta, "Yes", "No")%></td>
Page 13 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
</tr>
<tr>
<td><b>Channel Definition Format Supported:</b></TD><td> <%=iif(.CDF, "Yes",
"No")%></td>
</tr>
<%End With %>
</table>
</body>
</html>
Note: Any four properties can be considered in description and example
b) (Correct description 1 marks each) The SqlConnection Object is Handling the part of physical communication between
the application and the SQL Server Database. An instance of the SqlConnection class in .NET Framework is supported the Data Provider for SQL Server Database
The four Objects from the .Net Framework provide the functionality of Data Providers in ADO.NET. They are Connection Object, Command Object , DataReader Object and DataAdapter Object.
Connection Object
The Connection Object provides physical connection to the Data Source.
Connection Object connect to the specified Database and open a connection between the application and the Database . When the connection is established ,
SQL Commands may be executed, with the help of the Connection Object, to retrieve or manipulate data in the Database
Command Object The Command Object uses to perform SQL statement or stored procedure to
be executed at the Data Source.
The Command Object required an instance of a Connection Object for executing the SQL statements. That is, for retrieving data or execute an SQL
statement against a Data Source , you have to create a Connection Object and open a connection to the Data Source, and assign the open connection to the connection property of the Command Object. When the Command Object return result set , a
Data Reader is used to retrieve the result set.
Data Reader The DataReader Object is a stream-based , forward-only, read-only retrieval of query
results from the Data Source, which do not update the data. DataReader Object in ADO.NET is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not update the data. The
DataReader cannot be created directly from code, they created only by calling the ExecuteReader method of a Command Object.
Page 14 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
DataReader = Command.ExecuteReader()
DataReader Object provides a connection oriented data access to the data Sources. A Connection Object can contain only one DataReader at a time and the connection
in the DataReader remains open and cannot be used for any other purpose while data is being accessed. When started to read from a DataReader it should always be open and positioned prior to the first record. The Read() method in the DataReader
is used to read the rows from DataReader and it always moves forward to a new valid row, if any row exist .
DataReader.Read()
There are two types of DataReader in ADO.NET. They are SqlDataReader and the
OleDbDataReader. The System.Data.SqlClient and System.Data.OleDb are containing these DataReaders respectively Data Adapter
The DataAdapter Object , which populate a Dataset Object with results from a Data Source .
DataAdapter provides the communication between the Dataset and the Datasource. We can use the DataAdapter in combination with the DataSet Object. That is these
two objects combine to enable both data access and data manipulation capabilities. The DataAdapter can perform Select , Insert , Update and Delete SQL operations in the Data Source. The Insert , Update and Delete SQL operations , we are using the
continuation of the Select command perform by the DataAdapter. That is the DataAdapter uses the Select statements to fill a DataSet and use the other three SQL commands (Insert, Update, delete) to transmit changes back to the Database.
Once the Database activities over , Connection should be closed and release the
database resources . The Close() method in SqlConnection class is used to close the Database
Connection. The Close method rolls back any pending transactions and releases the
Connection from the SQL Server Database.
Note: Above code is common for all objects whereas individual sample code for each object can be considered
Example to achieve database connectivity in SQL
(Correct code 2 Marks) Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click Dim connetionString As String
Dim cnn As SqlConnection
Page 15 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" cnn = New SqlConnection(connetionString)
Try cnn.Open()
MsgBox("Connection Open ! ") cnn.Close() Catch ex As Exception
MsgBox("Can not open connection ! ") End Try
End Sub End Class
Note : Related program code can be considered (Correct code – 2 Marks) Example Console Application using Data reader Import System.Data.Sqlclient
Import System.console Module module1
Dim myconnection as sqlconnection Dim mycommand as sqlcommand Dim dr as sqldataReader
Sub main() Myconnection = New
sqlconnection(―Server=.;UserID=sa;Passsword=sa;database=mydatabase‖) Mycommand= New sqlcommand(―Select * from Employee‖,
myconnection) Dr = mycommand.Executereader Do
While dr.read() Console,.writeline(―Employee Name = ― & dr(0))
Console,.writeline(―Employee Age = ― & dr(1)) Console,.writeline(―Employee Mobile = ― & dr(2)) Console,.writeline(―Employee Desgination = ― & dr(3))
Console,.writeline(―Employee Salary = ― & dr(4)) Console,.writeline(―Employee Email = ― & dr(5))
End while Loop while dr.nextresult() Dr.close
Myconnection.close Console.Read() End sub
End module
Page 16 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
c) (Multithreading Explanation with code – 4Marks, Explanation 2 Marks and Code – 2Marks)
Multithreading is a feature provided by the operating system that enables your
application to have more than one execution path at the same time. We are all used to Windows' multitasking abilities, which allow us to execute more than one application at the same time. While writing in Microsoft Word, listening to favorite
songs in WinAmp and downloading a new song using the Internet Download Manager and document is sent for printing. In a similar manner, we may use multithreading to run different methods of our program at the same time.
The .NET Framework, and thus VB.NET provides full support for multiple execution threads in a program. You can add threading functionality to your application by using the System.Threading namespace. A thread in .NET is represented by the
System.Threading.Thread class. We can create multiple threads in our program by creating multiple instances (objects) of this class. A thread starts its execution by calling the specified method and terminates when the execution of that method gets
completed. We can specify the method name that the thread will call when it starts by passing a delegate of the ThreadStart type in the Thread class constructor. The
delegate System.Threading.ThreadStart may reference any method which has the void return type and which takes no arguments.
Example of Multithreading
Note: Related program code can be considered Imports SystemImports System.ThreadingModule Test
Public Sub Main() Dim firstThread As New Thread(New ThreadStart(AddressOf Fun1))
Dim secondThread As New Thread(New ThreadStart(AddressOf Fun2)) firstThread.Start() secondThread.Start()
Console.WriteLine("End of Main()") End Sub Public Sub Fun1()
Dim i As Integer For i = 1 To 5
Console.WriteLine("Fun1() writes: {0}", i) Next End Sub
Public Sub Fun2() Dim i As Integer
For i = 10 To 6 Step -1 Console.WriteLine("Fun2() writes: {0}", i) Next
End Sub End Module
Page 17 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
One possible output of the program is: End of Main()
Fun1() writes: 1 Fun1() writes: 2
Fun1() writes: 3 Fun1() writes: 4 Fun1() writes: 5
Fun2() writes: 10 Fun2() writes: 9
Fun2() writes: 8 Fun2() writes: 7 Fun2() writes: 6
Press any key to continue
Thread Priorities
(Multithreading Priorities Explanation with code – 4Marks, Explanation 2
Marks and Code – 2Marks)
Threads can also be assigned priority for execution. Thread priority can be set by the
thread's Priority property and assigning a value from predefined Thread Priority
enumeration.
Values for Thread Priority:
Above Normal -> Gives thread higher priority
Below Normal ->Gives thread lower priority
Normal -> Gives thread normal priority
Lowest -> Gives thread lowest priority
Highest -> Gives thread highest priority
Working with the above example, add a new button Button6 to the main form. When
this button is clicked the thread is assigned Highest priority .The code for that looks like
this:
Private Sub Button6_Click(ByVal sender as System.Object, ByVal e as
System.EventArgs)_
Handles Button6.Click
Thread1.Priority=System.Threading.ThreadPriority.Highest
'setting Highest priority for the thread
End Sub
Example For thread Priorities
Imports System Imports System.Threading Imports System.Text
Page 18 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
Imports System.Windows.Forms Public Class MainClass Public Shared Sub Main() Dim bThreadStart As New ThreadStart(AddressOf SubtractFromCounter) Dim bThread As New Thread(bThreadStart) bThread.Priority = ThreadPriority.Highest bThread.Start() Dim i As Integer Do While True Console.WriteLine("In main thread and count is " & i) i += 1 Loop End Sub Shared Public Sub SubtractFromCounter() Dim count As Integer Do While True count -= 1 Console.WriteLine("Am in another thread and counter =" & count) Loop End Sub End Class
Output
Page 19 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
Note: related code can be considered Q3. a)
(Response Object – Explanation – 1Marks 4 Methods and 4 properties – 2marks )
Response Object
The ASP Response object is used to send output to the user from the server. Its collections, properties, and methods are described below:
Collections
Collection Description
Cookies Sets a cookie value. If the cookie does not exist, it will be created,
and take the value that is specified
Properties
Property Description
Buffer Specifies whether to buffer the page output or not
CacheControl Sets whether a proxy server can cache the output generated by ASP
or not
Charset Appends the name of a character-set to the content-type header in
the Response object
ContentType Sets the HTTP content type for the Response object
Expires Sets how long (in minutes) a page will be cached on a browser before
it expires
ExpiresAbsolute Sets a date and time when a page cached on a browser will expire
IsClientConnected Indicates if the client has disconnected from the server
Pics Appends a value to the PICS label response header
Status Specifies the value of the status line returned by the server
Methods
Method Description
AddHeader Adds a new HTTP header and a value to the HTTP response
AppendToLog Adds a string to the end of the server log entry
BinaryWrite Writes data directly to the output without any character conversion
Clear Clears any buffered HTML output
End Stops processing a script, and returns the current result
Flush Sends buffered HTML output immediately
Redirect Redirects the user to a different URL
Write Writes a specified string to the output
Page 20 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
Note: Any four propertied and Methods can be considered
Request Object
(Request Object – Explanation – 1Marks
4 Methods and 4 properties – 2marks )
When a browser asks for a page from a server, it is called a request. The Request object is used to get information from a visitor. Its collections, properties, and methods are described below: Collections
Collection Description
ClientCertificate Contains all the field values stored in the client certificate
Cookies Contains all the cookie values sent in a HTTP request
Form Contains all the form (input) values from a form that uses the post
method
QueryString Contains all the variable values in a HTTP query string
ServerVariables Contains all the server variable values
Properties
Property Description
TotalBytes Returns the total number of bytes the client sent in the body of the
request
Methods
Method Description
BinaryRead Retrieves the data sent to the server from the client as part of a post
request and stores it in a safe array
Note: Any four propertied and Methods can be considered
Example to create and Display Cookie using Request and Response Object
(Correct code – 2 marks ie, 1-MArks to create/save, 1-Marks to read/Display)
Create/Write Cookie HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now; ‗Set the cookie value.
myCookie.Value = now.ToString(); ‗ Set the cookie expiration date.
myCookie.Expires = now.AddMinutes(1);
Page 21 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
‗Add the cookie. Response.Cookies.Add(myCookie);
Response.Write("<p> The cookie has been written.");
Display Cookie HttpCookie myCookie = new HttpCookie("MyTestCookie")
myCookie = Request.Cookies["MyTestCookie"] ‗ Read the cookie information and display it.
if (myCookie != null) Response.Write("<p>"& myCookie.Name & "<p>"& myCookie.Value)
else Response.Write("not found");
Note: Related code can be considered
b) (Composite Data Bound Object Explanation and Example – 2 Marks)
Data Bound controls are controls that are bound to data sources. Traditionally the DataGrid is the principal data bound control in ASP.NET 1.x. Though DataGrid is still supported, ASP.NET 2.0 introduces three new controls—
GridView, FormView and DetailsView. All Data bound controls can be classified into Simple, composite and
hierarchical controls. In composite data bound controls two new base classes have
been added to enhance the Composite Data bound controls. The new CompositeControl and CompositeDataBoundControl are separate classes with a
similar blueprint. The CompositeControl class addresses the UI-based needs and CompositeDataBoundControl defines the common foundation for all composite data bound controls.
Grid View Control
(Explanation – 1 - marks, Feature – 1-marks, Code – 1-Mark) The GridView control is the official successor to the DataGrid control of
yesteryears. It is no longer listed in the toolbox, even though it is supported by
ASP.NET 2.0. All new projects would automatically use the GridView control. Though both these controls have a similar look and feel they are implemented differently. The GridView control is associated with the DataSource control through
its DataSourceID property.
Features of grid View Control
Binding the data source control such as sqldatasource
Built-in sorting , updating deleting paging capabilities
Multiple key fields
Multiple data field for hyperlink column
Customizable appearance through theme and style
Page 22 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
GridView totally supports 6 field types, they are:
1. BoundField,
2. CheckBoxField, 3. ButtonField,
4. CommandField, 5. HyperlinkField, 6. ImageField and
7. TemplateField Example of Grid View control
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"> <title>Grid View Control Demo</title>
</head> <body> <form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" DataSource=‖SQLdatasource1‖ /> <asp: SQLdatasource ID=‖ SQLdatasource1‖ runat=‖Server‖
ConnectionString=‖Data Source=.;Initial catalog=Northwind;UID=sa;Password=sa;‖ selectcommand=‖Select * from employee‖ providerName=System.data.sqlclient‖/>
</form></body></html>
Note: Related code can be considered
DetialView Control (Explantion – 1 - marks, Feature – 1-marks, Code – 1-Mark)
The DetailsView is a control that is complementary to the GridView control. It
has been introduced in ASP.NET 2.0 to provide an ability to work with a single
record or row from an associated data source. The default view of this control is vertical with each column of the record displayed on a line of its own. It is used for updating and inserting new records and used often in the Master-details scenario
where the details of the record selected in the master is displayed in detail. The DetailsView, like the GridView rides on the data source capabilities to
update, insert or delete rows. It renders a single data item at a time even when the data source exposes more items. If the data object represents the ICollection interface or the underlying data source exposes the paging operation, the
DetailsView can page over the data, provided the AllowPaging property is set to true. Users can also navigate between rows of data using this control.
The process of binding the DetailsView control to a data source is very simple. The DataSourceID property can be set declaratively or programmatically.
Page 23 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
Example of DetailView <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataKeyNames="ProductID" DataSourceID="ObjectDataSource1"
AllowPaging="True" EnableViewState="False">
<Fields> <asp:BoundField DataField="ProductName" HeaderText="Product" SortExpression="ProductName" />
<asp:BoundField DataField="CategoryName" HeaderText="Category" ReadOnly="True" SortExpression="CategoryName" />
<asp:BoundField DataField="SupplierName" HeaderText="Supplier" ReadOnly="True" SortExpression="SupplierName" /> <asp:BoundField DataField="QuantityPerUnit"
HeaderText="Qty/Unit" SortExpression="QuantityPerUnit" /> <asp:BoundField DataField="UnitPrice" HeaderText="Price" SortExpression="UnitPrice" />
<asp:BoundField DataField="UnitsInStock" HeaderText="Units In Stock" SortExpression="UnitsInStock" />
<asp:BoundField DataField="UnitsOnOrder" HeaderText="Units On Order" SortExpression="UnitsOnOrder" /> <asp:CheckBoxField DataField="Discontinued"
HeaderText="Discontinued" SortExpression="Discontinued" /> </Fields> </asp:DetailsView>
Note : Related code can be considered
c) ( correct Desclaration of Object – 2marks) Import system.data
Import System.data.client Public class form2
Private sub button1_click(byval sender as systm.object , byval e as system.EventArgs) handles button1.click Dim dt As New DataTable("Students")
Dim dr As Datarow Dim dc As Datacolumn
( Creation and adding data to column object – 2marks for min. four coulmns)
dc.datatype= System.Type.getType(―System.Int32‖) dc.ColumnName=‖ID‖ dt.coumns.add(dc)
Dim dc As Datacolumn
dc.datatype= System.Type.getType(―System.String‖) dc.ColumnName=‖Name‖ dt.coumns.add(dc)
Page 24 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
Dim dc As Datacolumn dc.datatype= System.Type.getType(―System.String‖)
dc.ColumnName=‖Class‖ dt.coumns.add(dc)
Dim dc As Datacolumn dc.datatype= System.Type.getType(―System.String‖) dc.ColumnName=‖Gender‖
dt.coumns.add(dc)
Dim dc As Datacolumn dc.datatype= System.Type.getType(―System.String‖) dc.ColumnName=‖percentage‖
dt.coumns.add(dc) ( Creation and adding data to Row object – 2marks for min. four coulmns)
dt.Rows.Add(New Object() {1,"John", "BCOM", ―M‖, "92.5"})
dt.Rows.Add(New Object() {2,"Smith", "BSC", ―M‖,"86"}) dt.Rows.Add(New Object() {3,"Ayna", "HSC", ―F‖,"75"}) dt.Rows.Add(New Object() {4,"Donalds", "MSC", ―M‖,"52"})
( displaying data on dataGrid – 2marks) Datagrid1 = new datagrid()
datagrid1.DataSource = dt end sub
end class
Note: Related code can be considered
Q. 4 a) Attempt any Three of the following: 4 each
i. ASP.NET Web page life Cycle: 4 Marks
When an ASP.NET page run, the page goes through a life cycle in which it performs a series of
processing steps. These include initialization, in transitioning controls, restoring and maintaining,
running event handles code, and rendering.
In general term the page goes through various the stages:
1. Page request: The page request occurs before the page life cycle begins. When the page us
requested by a user, ASP.Net determines whether the page needs to be parsed and compiled,
or whether cache version of the page can be sent in response without running page.
2. Start: In the start stage page properties such as request and response are set.
3. Initialization: During page initialization, controls on the page are available and each control’s
unique property is set.
4. Load: During load, if the current –request is a post back, control properties are loaded with
information recovered from view state and control state.
5. Post-back event handling: if the request is post back control event handler are called.
Page 25 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
6. Rendering: During rendering stage, the page calls the render method for each control,
providing a text writer that writes its output to the output stream of the page response
property.
7. Unload: It is raised after the page has been fully sent to the client and is ready to be discarded.
At this point, page properties such as response and request are unloaded and cleanup is
performed.
ii. Session Object:
A session object stores information about a user or change settings for a user session. Variables stored
in a session object contain information about one single user, and are available to all pages in one
application. Common information stored in session variables in name, id and preference. The server
creates a new session object for each new user and destroys the session object when session expires.
ASP.NET provides a class called HTTP session state which is part of the name space system.
.Web.SessionState. An HTTPSessionState object is created automatically for ASP.Net pages. This
object is called as session object. 2 Marks
To disable session state: 2 Marks
At the application level- Web configuration can be modified by setting ‘mode’ value to off for
<session State> section. This disables session state throughout all pages in the application.
At the page level- The ‘aspx’ file can be modified by adding EnablesessionState=’false’ in the
@page directive.
iii. Repeater Control:
Repeater control is used to display a repeated list if items that are bound to the control. It doesn’t
provide any extra support for selection, editing or sorting, the repeater control can be bound to a
database table, an XML file, or any other list of items. Some important properties of repeater control
are:
Footer template- used to define how to render the footer.
Header template- used to define how to render the header.
Item – used to get collection of repeated item. 2 Marks
Item template- used to define how items are rendered.
Separator template- used to define how separator between items will be rendered.
Example 2 Marks
<%@Page Language =”VB” AutoEvent-Wireup= “false”
Code File= “default1.aspx.vb” Inherits=”Default1”%>
<!DocType……………….. >
<html xmlns=http://www.w3.org/1999/xhtml>
<head run at=”server”>
<title> untitled page</title>>
</head>
<body>
<form id = “form1” run at =”Server”> <div>
<asp: SQL DataSource ID=”dl” run at =”Server”
Connection string=”Datasource=.\sqlexpress; Initial
Catalog=studdata; Integrated security=True”
Select command=”select * from student”
Page 26 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
Provider Name=”System.Data.Sqlclient”/>
<asp:Repeater ID= “r1” run at =”Server”
DAtaSourceID=”dl”>
<ItemTemplate>
<%#Container.DataItem(“rollno”) %>
<% # Container.DataItem(“name”)%>
</ItemTemplate>
<Separator Template>
</hr>
</Separator Template>
</asp:Repeater>
</div>
</form>
</body>
Note: Any other example can be considered
iv. Transaction: A transaction is a set of components or procedures that must be executed as a unit. All
the methods should be executed successfully or the complete unit fails. It should describe ACID
properties as follows:
Atomicity: A transaction should be completely executed or none at all.
Consistency: Data should be in consistent state when a transaction starts or when it ends.
Isolation: Transaction that are running concurrently should get executed in such a way that
each one is sole occupant of the system. 2 Marks
Durability: Even in case of failure, state of consistency level should be maintained.
Methods of transaction:
SQL Transaction. Commit () – This can be called when entire code is successfully completed.
This makes all the modifications permitted.
SQL Transaction. Rollback()- It can be called when transaction is to be cancelled
SQL Transaction. Save()- This adds checkpoint in your transaction. This check point allows to
rollback a transaction to a certain point, but after SQltransaction. Commit() has been called,
you will not be able to rollback a transaction to a saved point. 2 marks
Q. 4 b) (Explanation 02 marks, program 4 Marks)
i) Parameterized Query:
A query written in SQL can take value at runtime with the help of parameterized query. The values can be set
to memory variables with the help of @ sign added as a prefix to the variables. Eg. @rollno, @name. These
values can be taken at the runtime and can be substituted in the query with add() method with SQL parameter
object.
Eg. cmd.Parameters .Add(New SqlParameter("@r1", roll))
Where r1 is a memory variable and roll is a column from the table.
(Any other method can also be considered)
Page 27 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim roll As Integer
Dim str As String
Console.WriteLine("Enter rollno")
roll = Console.ReadLine
Console.WriteLine("Enter Name")
str = Console.ReadLine
Dim con As SqlConnection = New SqlConnection("Data Source=.\sqlexpress;Initial
Catalog=mydb;Integrated Security=True;Pooling=False")
con.Open()
Dim cmd As New SqlCommand("insert into student values(@r1,@s1)", con)
With cmd.Parameters
.Add(New SqlParameter("@r1", roll))
.Add(New SqlParameter("@s1", str))
End With
cmd.ExecuteNonQuery()
Console.WriteLine("Record inserted")
Console.ReadLine()
con.Close()
con = Nothing
End Sub
End Module
Q.4 b) ii) (Logic – 3 Marks, Syntax – 3 Marks)
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<%@ Import Namespace="system.data.sqlclient" %>
<%@ Import Namespace="system.data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<script runat="server" >
Page 28 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim con As SqlConnection
con = New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=mydb;Integrated
Security=True;Pooling=False")
con.Open()
Dim ds As New DataSet
Dim da As SqlDataAdapter
da = New SqlDataAdapter("select * from student order by rollno", con)
da.Fill(ds, "student")
dg1.DataSource = ds
dg1.DataMember = "student"
dg1.DataBind()
End Sub
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:DataGrid ID="dg1" runat="server">
</asp:DataGrid></div>
</form>
</body>
</html>
Note: Any other suitable code can be considered
Q. 5 a) Attempt any FOUR of the following: (4 Marks Each)
File Object: File object represents a specified file on the locale machine or on network. To work with file
objects properties and methods, you need to create an instance of the file SystemObject object and then
instantiate file object through Get File() method. 2 Marks
File Object Methods:- 1 Mark
1) Copy (Source file, Target file) – copies source filename from specified path to target filename
at specified path.
Eg.- File.Copy(“C:\abc.txt”, “c:\xyz.txt”);
2) Delete( filename) Deletes specified file.
Eg. File.Delete(“C:\xyz.txt”);
3) Move(Source file, Target file): This method moves source filename at new location specified by
target filename. E.g. File.Move(“C:\abc.txt”, “C:\abc.txt”);
4) Create()/ Createtext()- These methods let you to create file at the end of the fully qualified
path.
Create Text() can be used to open a file for writing in UTF encoded data. Eg.
createText(Filepath);
5) Get Attribute()- It can be used to retrieve the attributes of the file given by file path
Syntax: File.GetAttribute(File Path);
6) Set Attribute()- It can be used to set new value for the file attribute. Eg.
Page 29 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
Syntax: File.SetAttribute(File Path, FileAttributes.hidden);
Note: Any 2 methods from the above can be considered. Any other methods properly explained from the
following list also can be considered:
1) Append Text()
2) Exists ()
3) Open()
4) Get Creation Time()
5) Get List Access Time()
6) Get LastWrite Time()
7) Open Record()
8) Open Text()
9) Open Write()
10) Set Creation time ()
11) Set Last Access Time()
12) Set Last write Time()
Properties: (1 Mark)
1. Attributes: it sets or returns the attributes of the specified file.
2. Data Created: returns date and time that the specified file was created.
3. Data Last Accessed: It returns date and time that the specified file was last accessed.
4. Data last Modified: Returns date and time that the specified file was last modified. It returns the most
recent date the file was altered; not just opened or examined.
5. Drive: Return drive letter of the drive on which the specified file or folder resides.
6. Name: the name property sets or return the name of the specified file.
7. Parent folder: Returns the folder object for the parent folder of the specified file.
8. Path: Returns absolute path of specified file.
9. Short name-Returns DOS- style version of the file name ( 8.3 (File. Extension) naming convention)
10. Short Path- Returns DOS style version of absolute path of specified file.
11. Size: returns size of the file in bytes.
12. Type: Returns type of file.
*Note: Any 2 properties from the above list can be considered.
Q. 5 b) Text Stream Object: The text stream object provides sequential access to the contents of text files. This
allows you to read write or append characters or lines to a text files. (2 Marks)
*Program to create web application to write and red text from sample.txt file. (2 Marks)
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb"
Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
Page 30 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
<body>
<form id="form1" runat="server">
<div>
<% Dim objfso, objts As Object
objfso = Server.CreateObject("Scripting.FileSystemObject")
objts = objfso.CreateTextFile("c:\sample.txt", True)
objts.WriteLine("Welcome")
objts.WriteLine("this is a text stream file")
objts = objfso.OpenTextFile("c:\sample.txt", 1)
Do Until objts.AtEndOfStream
Response.Write("line:" & objts.Line & ":" & objts.ReadLine & "<br>")
Loop
objts.close()
objts = Nothing
objfso = Nothing
%>
</div>
</form>
</body>
</html>
Q. 5 C. Steps to create Global.asax file are as follows:
1. Create a new web site →File → new →
2. Click on website menu →Add New Item and
Select “Global Application Class” option 1 Mark
3. Open Global.asax file and add following code in it.
<%@ Application Language="VB" %>
<script runat="server"> 3 Marks
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application startup
Response.Write("Appl started")
End Sub
Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application shutdown
Response.Write("Appl ended")
End Sub
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
End Sub
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when a new session is started
End Sub
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
Page 31 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
' Code that runs when a session ends.
' Note: The Session_End event is raised only when the sessionstate mode
' is set to InProc in the Web.config file. If session mode is set to
StateServer
' or SQLServer, the event is not raised.
End Sub
</script>
Q. 5 d) Inheritance in VB .Net :
Inheritance is the mechanism of deriving a new class from existing class. The existing class is known as base
or super or parent class and new class is known as derived sub or child class.
There are three modifiers as 1) Inherits 2) Non inheritable 3) Must Inherit
1. Syntax - Public Class B
Inherits A
End Class
Class B is derived from base class A
2. Must inherit Public class Student
:
:
Statements
:
End Class
Here student cannot be instantiated and must be inherited by other derived class. Must Inherit
make a class as abstract class.
3. Non inheritable class Student
:
Statements
:
End Class
A
B
Base
Derived
Page 32 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
Here class student cannot be inherited
Overriding methods can be achieved using “overridable” keyword to base class method and
“overrides” keyword is derived class method as
In base Class B
:
Public Overridable subProc()
:
:
End Sub
In derived Class C
Public overrides sub Proc()
:
: 3 Marks
End Sub
Example of inheritance- 1 Mark
Module Module1
Sub main()
Dim 0 as New displaydata
0.show()
Console.readLine()
End Sub
Public class Student
Public nm as string = “abc”
End class
Public class displaydata
Inherits student
Public function show()
Console.writeLine(“name” &num)
End function
End class
End module
*note : any other example can be considered
Q. 5. e)
Month calender and Date Tine Picker Control:
1. Month calender provides a graphical interface in the form of a calender to allow you to view
and set date information. The control displays a calender that contains numbered days of the
month, arranged in columns underneath the days of week, with selected range of dates
highlighted . the user can select a different month by clicking the arrow buttons that appear on
Page 33 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
either side of the month caption. This control lets the user select more than one date it
appears as follows:
To display selected date code can be written as:
Private sub monthCalender1_dateChanged(By val sender as
System.Object, ByVal e as System.windows.form.DateRangeEvenArgs) handldes
MonthCalender1.Date.Changed
Label1.Text= MonthCalender1.Selection StartToLong Date String
End Sub. 2 Marks
2. Date Time Picker control lets the user select a single item from a list of dates or times. It
displays only day and date unless the user drops down the calender, so it requires less space
on screen. When you make a selection that selection appears in the textbox part of the Date
Time Picker control.
It appears on screen as
Code can be written as
Private sub Date TimePicker1 _value Changed( By Val sender as
System.Object, By Val e as System.EvenArgs) Handles
DateTimePicker1.Value changed
Label1.Text=DateTimePicker1.To ShortDate String
End Sub 2 Marks
Q. 6 a) Procedure and Function in VB.Net ( 2 Marks + 2Marks)
In all modern computer languages , methods can be constructed to return with or without value to the calling
method. The methods that return a value are called as functions and the methods that don’t return values are
called a subroutines or sub procedures. In VB .Net procedures that don’t return value are declared with the
sub keyword whereas methods which can return value are declared with keyword ‘function’.
Syntax of procedure
April-2012
Sun Mon Tue Wed Thu Fri Sat
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
Page 34 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
Sub proc-name()
:
Statements
:
End Sub
Syntax of Function
Function Function-name*as….+
:
Statements
:
End Functions
Both function and procedures can have access modifier as Public, Private, Protected, Friend, Protected friend.
These modifiers define scope and visibility of methods
Example of sub-procedure
Module Module1
Sub Main()
Console.WriteLine(“In Main”)
Display()
End Sub
Sub Display()
Console.WriteLine(“In Display”);
End Sub
End Module
Example of Function:
Module Module1
Dim r as Integer
Dim a as Double
Sub Main()
Console.writeLine(“Enter Radius”);
r = console.ReadLine()
a=Area(r);
Console.writeLine(“Area “ &a)
Console.ReadLine()
End sub
Public function area( By Val radius as Integer)
As Double
Area = 3.14 * radius * radius
End Function
*Note: Any other examples can be considered.
Page 35 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
Q. 6 b) Code To Send a Text Mail: (Logic 2 Marks + Syntax 2 Marks) <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb"
Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<% Dim objmail As Object
objmail = Server.CreateObject("CDO.Message")
objmail.Subject = "Important"
objmail.From = "[email protected]"
objmail.To = "[email protected]"
objmail.TextBody = "This is a trial mail"
objmail.AddAttachment("c:\sample.txt")
objmail.Send()
objmail = Nothing
%>
</div>
</form>
</body>
</html>
Q. 6 c) CODE: a web application to check whether text box input is even or odd number:
(Logic 2 Marks + Syntax 2 Marks)
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Enter a number"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<br />
Page 36 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
<br />
<asp:Button ID="Button1" runat="server"
Text="Check" />
<asp:Label ID="Label2" runat="server"></asp:Label></div>
</form>
</body>
</html>
=====================================================================================
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If Val(TextBox1.Text) Mod 2 = 0 Then
Label2.Text = "number is even"
Else
Label2.Text = "number is odd"
End If
End Sub
End Class
Q. 6 d) Validation server controls: Validation server controls are used to validate the values that are entered
into other controls of the page. Validation controls perform client side validation, server side validation or
both, depending on the capabilities of the browser in which the page is displayed.
Validation controls in ASP.Net are 2 Marks
1. Required Field Validater- If input does not contain any empty string.
2. Range Validater: If the input control contain a value within a specific numeric, alphabetic or date range.
3. Compare Validater: If input control contains a value that matches the value in another, specified input control.
4. Regular Expression Validater: If input control matches a specified regular expression
5. Custom Validater: Validation is performed by user defined function.
Compare Validater compare the value of one input control to the value of another input control or to a fixed
value. 2 Marks.
Code : ( Any other example can be considered).
Page 37 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
6d)CompareValidator example
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="TextBox1"
ControlToValidate="TextBox2" ErrorMessage="Does not match"></asp:CompareValidator></div>
</form>
</body>
</html>
Q. 6 e) Use of Web Config. File:
ASP.Net configuration setting can be done by configuring a special file called as web.config, which is of XML
format. You can create a web config file for your application that contains all the special settings. Web.config
has several advantages over traditional configuration such as; it is never locked and can be updated at any
point. Its easily accessed and replicated and it is easy to understand. 2 Marks
Web.Config file uses a special XML format everything is nested inside a root<configuration> element; which
contains a <system.web> element. Inside <system.web> element are separate elements for each aspect of
configuration.
< ? xml version=”1.0” encoding=”utf-8”?>
<configuration>
<system.web>
<!—Configuration section go here -- > 2 Marks
</system.web>
</configuration>
Custom settings can be added to web.config with a special element called as <app settings>. This is nested
inside <configuration> and not in <system.web> element.
< ! xml version=”1.0” encoding = “utf-8”?>
<Configuration>
Page 38 of 38 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
SUMMER – 12 EXAMINATIONS
Subject code: 12261 Model Answer
<app settings>
<!—Special application settings go here -- >
</app settings>
<system.web>
<!—Configuration section go here -- >
</system.web>
</configuration>