Anda di halaman 1dari 34

O F F I C I A L M I C R O S O F T L E A R N I N G P R O D U C T

2373B
Programming with Microsoft Visual Basic
.NET
Companion Content
Information in this document, including URL and other Internet Web site references, is subject to change
without notice. Unless otherwise noted, the example companies, organizations, products, domain
names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no
association with any real company, organization, product, domain name, e-mail address, logo, person,
place or event is intended or should be inferred. Complying with all applicable copyright laws is the
responsibility of the user. Without limiting the rights under copyright, no part of this document may be
reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means
(electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express
written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property
rights covering subject matter in this document. Except as expressly provided in any written license
agreement from Microsoft, the furnishing of this document does not give you any license to these
patents, trademarks, copyrights, or other intellectual property.

The names of manufacturers, products, or URLs are provided for informational purposes only and
Microsoft makes no representations and warranties, either expressed, implied, or statutory, regarding
these manufacturers or the use of the products with any Microsoft technologies. The inclusion of a
manufacturer or product does not imply endorsement of Microsoft of the manufacturer or product. Links
may be provided to third party sites. Such sites are not under the control of Microsoft and Microsoft is not
responsible for the contents of any linked site or any link contained in a linked site, or any changes or
updates to such sites. Microsoft is not responsible for webcasting or any other form of transmission
received from any linked site. Microsoft is providing these links to you only as a convenience, and the
inclusion of any link does not imply endorsement of Microsoft of the site or the products contained
therein.

2002 Microsoft Corporation. All rights reserved.


Microsoft and the trademarks listed at
http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx are trademarks
of the Microsoft group of companies. All other marks are property of their respective owners.

Product Number: 2373B

Released: 02/2002
Overview of the Microsoft .NET Platform 1-1

Module 1
Overview of the Microsoft .NET Platform
Contents:
Question and Answers 2
1-2 Programming with Microsoft Visual Basic .NET

Question and Answers


Review
Question: What is the .NET Platform?

Answer: The .NET Platform is a set of technologies designed to transform the Internet into a full-
scale distributed computing platform. It provides new ways to build applications from collections
of Web Services. The .NET Platform fully supports the existing Internet infrastructure (HTTP,
XML, SOAP).

Question: What are the core technologies in the .NET Platform?

Answer: .NET Framework, .NET Enterprise Servers, .NET Building Block services, Visual Studio
.NET, and Windows.

Question: List the components of the .NET Framework.

Answer: Common language runtime, .NET Framework Class Library, data and XML, Web Services
and Forms, and Windows Forms.

Question: What is the purpose of common language runtime?

Answer: It provides an environment in which you can execute code.

Question: What is the purpose of common language specification?

Answer: It defines a set of features that all .NET-compatible languages should support.

Question: What is a Web Service?

Answer: A Web Service is a programmable Web component that can be shared between
applications on the Internet or an intranet.

Question: What is a managed environment?

Answer: A managed environment is one in which the environment provides services, such as
garbage collection, security, and other similar features.
Development Environment Features 2-1

Module 2
Development Environment Features
Contents:
Question and Answers 2
2-2 Programming with Microsoft Visual Basic .NET

Question and Answers


Review
Question: List the file extensions for the following Visual Basic .NET files: Visual Basic .NET project
files, classes, and modules.

Answer: .vbproj, .vb, and .vb

Question: Describe the purpose of namespaces and the Imports keyword.

Answer: Namespaces organize the objects and items found in an assembly and prevent
ambiguity when calling an object.

The Imports keyword allows you to access an object from within a namespace without using the
object's fully qualified name.

Question: Describe the purpose of Server Explorer.

Answer: Server Explorer allows you to view and manipulate databases and various server items,
such as message queues, event logs, Windows services, and XML Web Services. You can also
use Server Explorer to access these items from within your code.

Question: The Object Browser is exactly the same as in previous versions of Visual Basic. True or
false? If false, explain why.

Answer: False. The Object Browser has been enhanced to include inheritance and interfaces in
the object hierarchy.

Question: Describe the purpose of a conditional breakpoint and how to create one.

Answer: Conditional breakpoints halt execution when a particular condition is met, such as when
a variable equals a certain value.

To set a conditional breakpoint, you add a standard breakpoint, and then use the Breakpoint
Properties dialog box to modify the conditions.
Language and Syntax Enhancements 3-1

Module 3
Language and Syntax Enhancements
Contents:
Question and Answers 2
3-2 Programming with Microsoft Visual Basic .NET

Question and Answers


Review
Question: Declare and initialize an array that contains the following strings: "one", "two", "three", "four".

Answer:

Dim myArray( ) As String = {"one", "two", "three", "four"}

Question: What types of variables are created by the following declaration if Option Strict is off?

Dim a, b As Integer, c

Answer: The variables a and b are created

as Integers; c is created as an Object.

Question: What is the value of c after the following code executes:

Dim c As Integer
c = 1
CheckValue(c)
...
Sub CheckValue(ByVal iValue As Integer)
...
iValue = 13
End Sub

Answer: The variable c remains equal to 1 because the default passing mechanism is by value.

Question: Assuming you have an open Recordset called rs and a TextBox control called txtData,
which of the following statements will create a compiler or run-time error with Option Strict off? Why?

a. txtData.Text = rs(0)

b. txtData.Text = rs.Fields.Item(0)

c. txtData.Text = rs.Fields(0).Value

Answer: Statement (a) will fail because rs(0) returns a Field object; the Fields collection is the
default property of the Recordset object. This cannot be assigned to the Text property of the
txtData TextBox because the data types are not compatible.

Statement (b) will fail because Value is the default property of the Field object, and it does not
take a parameter. This causes the compiler to attempt to assign the Field object to the
txtData.Text property, resulting in an error.

Statement (c) will succeed because Item is the default property of the Fields object, and it does
take a parameter.
Language and Syntax Enhancements 3-3

Question: What is the method or property of the System.Exception class that retrieves the most
information about an exception?

Answer: The ToString method provides the fully qualified class name, and the error message (if
available), the name of the inner exception, and the stack trace of the exception.
Object-Oriented Design for Visual Basic .NET 4-1

Module 4
Object-Oriented Design for Visual Basic .NET
Contents:
Question and Answers 2
4-2 Programming with Microsoft Visual Basic .NET

Question and Answers


Review
Question: An actor must be a person that interacts with the system. True or false?

Answer: False. An actor can also be another system or a part of a system.

Question: Define the object-oriented term encapsulation.

Answer: Encapsulation is the hiding of the details about how an object performs various
operations.

Question: Define the object-oriented term inheritance.

Answer: Inheritance is the reuse of the methods and attributes of a general class in more
specialized classes.

Question: Describe freeform modeling.

Answer: Freeform modeling is the ability to use UML and non-UML shapes in a Visio diagram.

Question: In the following use case description, what are the likely classes and attributes?

A user requests a listing of grades from a school based on a particular student ID. The ID is validated by
the database, and an error message appears if the student ID does not exist. If the ID matches a
student, the student's name, address, and date of birth are retrieved, in addition to the grades. The user
is prompted to verify the information, and the grades are displayed if the verification succeeds. An error
message is displayed if the user is unable to verify the information. Three verification attempts are
allowed before the user is automatically logged off. The user is automatically logged off after five minutes
of inactivity.

Answer:

Class Attributes
User <Unknown at this stage>
Student StudentID
Name
Address
Date of Birth
Grades
Grades ID
Object-Oriented Programming in Visual Basic .NET 5-1

Module 5
Object-Oriented Programming in Visual Basic .NET
Contents:
Question and Answers 2
5-2 Programming with Microsoft Visual Basic .NET

Question and Answers


Review
Question: Create code that defines multiple constructors for a Person class. The first constructor will
not take any arguments. The second will take two string values: FirstName and LastName.

Answer:

Class Person

Sub New( )

'Default constructor

End Sub

Sub New(ByVal FirstName As String, _

ByVal LastName As String)

'Second constructor

End Sub

End Class

Question: Garbage collection occurs immediately after all references to an object are removed. True or
false? If false, explain why.

Answer: False. Garbage collection may happen at any time after all object references have been
removed.

Question: Describe the functionality of the MyBase keyword.

Answer: MyBase is used in a derived class to access methods and properties in the immediate
base class.

Question: What is a potential problem that may result from the following class code sample? How can
you rewrite the code to resolve the problem?

Class Person
Private Sub Save( )
'Save the local data in a database
End Sub

Sub Dispose( )
Save( )
End Sub

Protected Overrides Sub Finalize( )


Dispose( )
MyBase.Finalize( )
End Sub
End Class
Object-Oriented Programming in Visual Basic .NET 5-3

Answer: The Dispose method can be called directly from a client and might be called again when
the object is destroyed by garbage collection. This would result in the Save method being called
twice, which may create data inconsistencies.
To avoid this, use the SuppressFinalize method of the GC class to stop the Finalize method being
called after Dispose. Add the line "GC.SuppressFinalize( )" in the Dispose method after the Save
line as follows):

Sub Dispose()

Save()

GC.SuppressFinalize()

End Sub

Question: You can create an interface explicitly in Visual Basic .NET. True or false? If false, explain
why.

Answer: True. You can create an interface explicitly by using the Interface...End Interface
statement block.

Question: Will the following code compile correctly? If not, why?

Class Person
Event NameChanged( )
Private strName As String

Sub ChangeName(ByVal strNewName As String)


strName = strNewName
RaiseEvent NameChanged( )
End Sub
End Class

Module TestCode
Sub Main( )
Dim x As New Person( )
AddHandler x.NameChanged, AddressOf HandleIt
x.ChangeName("Jeff")
End Sub

Sub HandleIt(ByVal strValue As String)


MsgBox(strValue)
End Sub
End Module

Answer: The code will not compile correctly because the signature of the event does not match
the signature of the delegate in the AddHandler statement.
Using Windows Forms 6-1

Module 6
Using Windows Forms
Contents:
Question and Answers 2
6-2 Programming with Microsoft Visual Basic .NET

Question and Answers


Review
Question: Identify some of the benefits of Windows Forms.

Answer: Rich set of controls, GDI+ support, advanced layout possibilities, accessibility support,
advanced printing support, visual inheritance, extensibility.

Question: The ContainerControl class is the fundamental base class for all other controls. True or
false?

Answer: False. The Control class is the fundamental base class for all other controls.

Question: Write the code to access the path from which an executable is running.

Answer:

Dim strAppPath as String

strAppPath = Application.StartupPath

Question: Describe an owned form.

Answer: An owned form is always displayed on top of its owner. It is minimized or closed when
the owner is minimized or closed.

Question: Write code to make the code behind a button called btnOK execute when a user presses
RETURN.

Answer:

Me.AcceptButton = btnOK

Question: List two ways to provide Help to the user.

Answer: ErrorProvider, HelpProvider, or ToolTip controls.

Question: Write code to create a Help menu with one menu item-About- at run time.

Answer:

Dim mnuMain As New MainMenu( )

Dim mnuItem1 As New MenuItem( )

Dim mnuItem2 As New MenuItem( )

mnuItem1.Text = "Help"
Using Windows Forms 6-3

mnuMain.MenuItems.Add(mnuItem1)

mnuItem2.Text = "About"

mnuMain.MenuItems(0).MenuItems.Add(mnuItem2)

AddHandler mnuItem2.Click, AddressOf AboutClick

Menu = mnuMain
Building Web Applications 7-1

Module 7
Building Web Applications
Contents:
Question and Answers 2
Multimedia 3
7-2 Programming with Microsoft Visual Basic .NET

Question and Answers


Review
Question: Describe some of the features of ASP.NET.

Answer: Compiled code, multiple browser clients, session state that supports Web farms, and
easy deployment.

Question: Explain why updates to an ASP.NET application do not require you to restart IIS.

Answer: No items are locked by IIS, so updating does not require you to restart IIS.

Question: Create a line of code that uses the Response object to retrieve a userCountersession
variable and display it to the user.

Answer:

Response.Write("Value: " & Session("userCounter").ToString)

Question: Convert the following HTML control tag into a server-side control.

<input type=text id=mytext value="hello">

Answer:

<input type=text id=mytext value="hello" runat=server>

Question: What attribute do you add to class methods when creating a Web Service?

Answer: WebMethod.

Question: Visual Basic .NET allows early binding to a Web Service. True or false?

Answer: True. Setting a Web reference to a discovery document allows Visual Basic .NET to
create a proxy class that allows early binding in the client application.
Building Web Applications 7-3

Multimedia
Media Type Title

Macromedia Flash Animation How Web Services Work


Using ADO.NET 8-1

Module 8
Using ADO.NET
Contents:
Question and Answers 2
8-2 Programming with Microsoft Visual Basic .NET

Question and Answers


Review
Question: State three benefits that ADO.NET has over earlier data access technologies.

Answer: It is part of the .NET Framework, it is designed for disconnected data, and it is integrated
with XML.

Question: You have the following code in your application. What would you do to make the code more
efficient? Why?

Dim sqlConn As New SqlClient.SqlConnection("Integrated Security=True;Data


Source=LocalHost;Initial Catalog=Pubs;")
sqlConn.Open( )
Dim sqlAdapt As New SqlClient.SqlDataAdapter("Select au_lname from authors", sqlConn)
Dim sqlDataSet As New DataSet( )
sqlAdapt.Fill(sqlDataSet, "Authors")
Dim i As Integer
For i = 0 To sqlDataSet.Tables("Authors").Rows.Count - 1
MessageBox.Show(sqlDataSet.Tables("Authors").Rows(i).Item(0).ToString)
Next

Answer: You should replace the DataSet with a DataReader because a DataReader is more
efficient for read-only, forward-only data access. This is because a DataReader only holds one
record in memory at a time.

Question: If you change the contents of a DataTable in a DataSet, will those changes be reflected in the
underlying data source? Why, or why not?

Answer: The changes will only be reflected if you explicitly call the Update method of the
DataAdapter. If you do not do this, the changes are made locally in the DataSet, which has no
permanent connection to the source.

Question: You have the following code in the Page_Load event of a Web Form, but the DataGrid does
not appear. What is wrong, assuming all objects are correctly declared and instantiated?

sqlReader = sqlComm.ExecuteReader
DataGrid1.DataSource( ) = sqlReader

Answer: You have neglected to call the DataBind method of the DataGrid, as shown in the
following line of code:

DataGrid1.DataBind( )

Question: Write the code to load an XML document called Books.xml into a DataSet.

Answer:

Dim ds As New DataSet( )

ds.ReadXml("books.xml")
Developing Components in Visual Basic .NET 9-1

Module 9
Developing Components in Visual Basic .NET
Contents:
Question and Answers 2
9-2 Programming with Microsoft Visual Basic .NET

Question and Answers


Review
Question: An unmanaged client application uses a class created in Visual Basic .NET but cannot
access any methods of the class. What is the likely cause of this problem, and how would you fix it?

Answer: The class may have public methods defined without using an interface or any class-
level attributes. To solve this problem, create and implement methods in interfaces rather than
classes, use the ClassInterface attribute, or use the COMClass attribute.

Question: Modify the following code to use auto completion of transactions rather than the explicit
SetAbort and SetComplete methods.

<Transaction(TransactionOption.Required)> _
Public Class TestClass
Public Sub MySub( )
Try
'Perform action
ContextUtil.SetComplete( )
Catch ex As Exception
ContextUtil.SetAbort( )
Throw ex
End Try
End Sub
End Class

Answer:

<Transaction(TransactionOption.Required)> _

Public Class TestClass

<AutoComplete( )> Public Sub MySub( )

'Perform action

End Sub

End Class

Question: Create assembly attributes so Component Services can automatically create an application
named "TestComponents" that runs as server activation.

Answer

<Assembly: ApplicationName("TestComponents")>

<Assembly: ApplicationActivation(ActivationOption.Server )>

Question: Why would you use the IComponent interface?

Answer: The interface enables component classes to site other components and enables the
component class to be sited on other components.
Developing Components in Visual Basic .NET 9-3

Question: The following code causes a compilation error. Explain what is causing the error and how it
could be fixed.

Sub Main( )
Dim t As New Thread(AddressOf MySub)
t.Start(10)
End Sub

Sub MySub(ByVal x As Integer)


...
End Sub

Answer: The MySub procedure cannot be called directly because it expects an argument and the
Start method of a Thread cannot accept parameters. To fix this error, you could create the
following code:

Sub Main( )

Dim obj As New ThreadObj( )

Dim t As New Thread(AddressOf obj.MySub)

obj.x = 10

t.Start( )

End Sub

Class ThreadObj

Public x As Integer

Sub MySub( )

...

End Sub

End Class
Deploying Applications 10-1

Module 10
Deploying Applications
Contents:
Question and Answers 2
10-2 Programming with Microsoft Visual Basic .NET

Question and Answers


Review
Question: Name the four ways of distributing a Visual Studio .NET project and describe what each is
used for.

Answer: XCOPY deployment - for simple stand-alone applications

Copy Project deployment-for copying a Web project directly to the Web server

Windows Installer-for deploying Windows-based and Web-based applications

Merge Module-for packaging reusable, shared components

Question: How do you create a strong-named assembly?

Answer: Use sn.exe to create a public-private key pair and apply it to the assembly by adding the
AssemblyKeyFile attribute to the AssemblyInfo.vb file.

Question: Describe the use of the Launch Conditions Editor.

Answer: The Launch Conditions Editor allows you to define certain conditions under which the
installation of an application fails, for example, the absence of a required database on a server.
Upgrading to Visual Basic .NET 11-1

Module 11
Upgrading to Visual Basic .NET
Contents:
Question and Answers 2
11-2 Programming with Microsoft Visual Basic .NET

Question and Answers


Review
Question: List two benefits of upgrading an application and how those benefits are gained.

Answer: Scalability can be gained through the use of ASP.NET. Performance can be improved
through the use of ASP.NET and ADO.NET.

Question: What is the most commonly followed upgrade path? Why?

Answer: Partial upgrade, because a complete rewrite is generally too expensive and a complete
upgrade too impractical.

Question: Which upgrade comments are not listed in the Task List? Why?

Answer: UPGRADE_NOTE comments are not listed because they only highlight potential
problems, and the code will run without any modifications.
Programming with Microsoft Visual Basic .NET 1-1

Send Us Your Feedback


You can search the Microsoft Knowledge Base for known issues at Microsoft Help and Support before
submitting feedback. Search using either the course number and revision, or the course title.

Note Not all training products will have a Knowledge Base article if that is the case, please ask
your instructor whether or not there are existing error log entries.

Courseware Feedback
Send all courseware feedback to support@mscourseware.com. We truly appreciate your time and effort.
We review every e-mail received and forward the information on to the appropriate team. Unfortunately,
because of volume, we are unable to provide a response but we may use your feedback to improve your
future experience with Microsoft Learning products.

Reporting Errors
When providing feedback, include the training product name and number in the subject line of your e-
mail. When you provide comments or report bugs, please include the following:

Document

Page number or location


Complete description of the error or suggested change

Please provide any details that are necessary to help us verify the issue.

Important All errors and suggestions are evaluated, but only those that are validated are added
to the product Knowledge Base article.

Anda mungkin juga menyukai