100% found this document useful (12 votes)
241 views

[FREE PDF sample] Advanced Programming Using Visual Basic 2008 4th Edition Julia Case Bradley ebooks

Bradley

Uploaded by

rukabmittln6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (12 votes)
241 views

[FREE PDF sample] Advanced Programming Using Visual Basic 2008 4th Edition Julia Case Bradley ebooks

Bradley

Uploaded by

rukabmittln6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Download the full version of the ebook at

https://ebookfinal.com

Advanced Programming Using Visual Basic 2008


4th Edition Julia Case Bradley

https://ebookfinal.com/download/advanced-
programming-using-visual-basic-2008-4th-edition-
julia-case-bradley/

Explore and download more ebook at https://ebookfinal.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Clearly Visual Basic Programming with Microsoft Visual


Basic 2010 2nd Edition Diane Zak

https://ebookfinal.com/download/clearly-visual-basic-programming-with-
microsoft-visual-basic-2010-2nd-edition-diane-zak/

ebookfinal.com

Simply Visual Basic 2008 With DVD ROM 3rd ed Edition


Deitel

https://ebookfinal.com/download/simply-visual-basic-2008-with-dvd-
rom-3rd-ed-edition-deitel/

ebookfinal.com

Process engineering and design using Visual Basic Second


Edition Datta

https://ebookfinal.com/download/process-engineering-and-design-using-
visual-basic-second-edition-datta/

ebookfinal.com

Advanced Graphics Programming Using OpenGL 1st Edition Tom


Mcreynolds

https://ebookfinal.com/download/advanced-graphics-programming-using-
opengl-1st-edition-tom-mcreynolds/

ebookfinal.com
Practical Database Programming with Visual Basic NET 1st
Edition Ying Bai

https://ebookfinal.com/download/practical-database-programming-with-
visual-basic-net-1st-edition-ying-bai/

ebookfinal.com

Practical Database Programming with Visual Basic NET 2nd


Edition Ying Bai

https://ebookfinal.com/download/practical-database-programming-with-
visual-basic-net-2nd-edition-ying-bai/

ebookfinal.com

Numerical simulations and case studies using Visual C Net


1st Edition Shaharuddin Salleh

https://ebookfinal.com/download/numerical-simulations-and-case-
studies-using-visual-c-net-1st-edition-shaharuddin-salleh/

ebookfinal.com

Microsoft Visual Basic NET Programming for the Absolute


Beginner 1st Edition Jonathan S. Harbour

https://ebookfinal.com/download/microsoft-visual-basic-net-
programming-for-the-absolute-beginner-1st-edition-jonathan-s-harbour/

ebookfinal.com

Microsoft Visual Basic Game Programming for Teens 2nd


Edition Jonathan S.(Jonathan S. Harbour) Harbour

https://ebookfinal.com/download/microsoft-visual-basic-game-
programming-for-teens-2nd-edition-jonathan-s-jonathan-s-harbour-
harbour/
ebookfinal.com
Advanced Programming Using Visual Basic 2008 4th
Edition Julia Case Bradley Digital Instant Download
Author(s): Julia Case Bradley, Anita Millspaugh
ISBN(s): 9780073517223, 0073517224
Edition: 4
File Details: PDF, 18.42 MB
Year: 2009
Language: english
Computer and Information Technology

Advanced Programming Using Visual


Basic 2008
2008 Edition

Bradley−Millspaugh

McGraw-Hill
=>?
McGraw−Hill Primis

ISBN−10: 0−39−012228−9
ISBN−13: 978−0−39−012228−5

Text:

Advanced Programming Using Visual Basic


2008
Bradley−Millspaugh
This book was printed on recycled paper.

Computer and Information Technology

http://www.primisonline.com
Copyright ©2009 by The McGraw−Hill Companies, Inc. All rights
reserved. Printed in the United States of America. Except as
permitted under the United States Copyright Act of 1976, no part
of this publication may be reproduced or distributed in any form
or by any means, or stored in a database or retrieval system,
without prior written permission of the publisher.

This McGraw−Hill Primis text may include materials submitted to


McGraw−Hill for publication by the instructor of this course. The
instructor is solely responsible for the editorial content of such
materials.

111 COMPGEN ISBN−10: 0−39−012228−9 ISBN−13: 978−0−39−012228−5


Computer
and
Information
Technology

Contents

Bradley−Millspaugh • Advanced Programming Using Visual Basic 2008

Front Matter 1
Preface 1
To the Student 9

1. Visual Studio and the .NET Framework 11


Text 11

2. Building Multitier Programs with Classes 59


Text 59

3. Windows Database Applications 115


Text 115

4. Windows Database Using Related Tables 159


Text 159

5. Windows Database Updates 197


Text 197

6. Services 259
Text 259

7. Web Applications 285


Text 285

8. Web Database Applications 361


Text 361

iii
9. Reports 413
Text 413

10. Collections 441


Text 441

11. User Controls 475


Text 475

12. Help Files 501


Text 501

13. Additional Topics in Visual Basic 517


Text 517

Back Matter 551


Appendix A: Answers to Feedback Questions 551
Appendix B: Review of Introductory VB Concepts 563
Appendix C: Deployment 609
Appendix D: Tips and Shortcuts for Mastering the Environment 617
Glossary 635
Index 644

iv
Bradley−Millspaugh: Front Matter Preface © The McGraw−Hill 1
Advanced Programming Companies, 2010
Using Visual Basic 2008

PREFACE

Visual Basic (VB) has become the most popular programming language for
several reasons. VB is easy to learn, which makes it an excellent tool for un-
derstanding programming concepts. In addition, it has evolved into such a
powerful and popular product that skilled Visual Basic programmers are in
demand in the job market.
Visual Basic 2008, the latest version of VB, has many new features, espe-
cially in queries and Web application development. Visual Basic is designed
to allow the programmer to develop applications that run under Windows
and/or in a Web browser without the complexity generally associated with
programming.
This edition of the text is updated to Visual Studio 2008, .NET 3.5, and
ASP.NET 3.5. The screen captures are based on Windows Vista, but all pro-
grams can be run in Windows XP, although the special effects of WPF cannot
be seen in XP.

About This Text


This textbook is intended for use in an advanced programming course, which
assumes completion of an introductory course. The text incorporates the basic
concepts of programming, problem solving, programming logic, as well as the
design techniques of an object-oriented language.
Appendix B contains a summary of topics normally covered in an introduc-
tory text, as a tool for review.

Approach
Chapter topics are presented in a sequence that allows the programmer to learn
how to deal with a visual interface while acquiring important programming
skills such as accessing and updating data in a relational database, developing
applications for the Web and for mobile devices, and adding browser-based
Help files to an application.
The chapters may be used in various sequences to accommodate the needs
of the course, as well as a shorter quarter system or a semester-long course.

Changes in This Edition


This edition presents material in a sequence designed for teaching students
and does not attempt to cover all topics for certification exams.
iii
2 Bradley−Millspaugh: Front Matter Preface © The McGraw−Hill
Advanced Programming Companies, 2010
Using Visual Basic 2008

FEATURES OF THIS TEXT


With StoresBindingSource
Hands-On Programming Examples C H.EndEdit()
A P T E R
.AddNew()
These complete programming exercises guide
students through the process of planning,
writing, and executing Visual Basic programs.
4 End With
AddingBoolean = True
SetComboBoxBinding()
Stor_nameComboBox.Focus()
SetControlsReadOnly(False)

Your Hands-On Programming Example Windows Database


SetButtonsForEdit()
If Stor_nameComboBox.SelectedIndex <>
' Save the index of the new record
Create a multiple-tier project to obtain data from the employee table in the
Pubs database using a stored procedure. Use an ORDER BY clause in the stored
procedure to sort the data in order by last name. Display the full employee
names (last name, first name, and middle initial) in alphabetic order in a combo
Using Related Tables
Else
PreviousSelectedIndex = Stor_nameC
box. Do not display the first and last name fields other than in the combo box.
Show the remaining fields in text boxes for the selected record, with meaning- PreviousSelectedIndex = 0
ful identifying labels. Do not include a navigation toolbar. Include a File / Exit
menu item to terminate the program. End If
Planning the Project at the completion of this chapter, you will be able to . . .
Sketch a form (Figure 3.30) that your users sign off as meeting their needs.
1. Explain the types of table relationships.
Figure 3.30 2. Display master/detail records.
A planning sketch for the 3. Display a field from a second table using a lookup.
File hands-on programming
Name: FullNameComboBox example. 4. Create a search using a parameterized query and write a filter to retrieve specific data.
Employee ID: Emp_idTextBox
5. Assign data values to unbound controls.
Job ID: Job_idTextBox
Job Level: Job_lvlTextBox 6. Retrieve and display the parent row for a selected child row.

Pub ID: Pub_idTextBox 7. Retrieve and display an array of child rows for a selected parent row.
Hire Date: Hire_dateTextBox
8. Create an application that displays data from a many-to-many relationship.

9. Select the correct locations for handling and formatting data in a multitier application.

Plan the Objects, Properties, and Methods Plan the two tiers. Determine the
objects and property settings for the form and its controls and for the data-tier
component. Figure 3.31 shows a diagram of the components in the two tiers.

Presentation Tier

Object Property Setting

EmployeeForm Name
Text
EmployeeForm
Employees Learning Objectives
FullNameComboBox Name FullNameComboBox
Text boxes for all database
fields (including Hire Date)
Specific objectives tell students what
will be covered in the chapter and
what they will be able to do after
completing the chapter.

TIP
➤ Feedback 4.2 If the drop-down arrows do not
1. What Fill method statements are created for a relationship for appear in the Data Sources window,
Customers and Orders? Assume that the project contains two make sure that you have a form
TableAdapters called CustomersTableAdapter and OrdersTableAdapter displaying in the designer. ■
as well as a DataSet called NorthwindDataSet.
2. How can you view the relationship between two tables?
3. Describe the necessary steps to display the job description from the
jobs table rather than the job id when displaying the employee table.

TIPs
Feedback Questions Tips, found in the margins throughout
the text, help students avoid potential
Feedback questions encourage students to reflect on trouble spots in their programs and
the topics covered and evaluate their understanding of encourage them to develop good
details relating to that topic. programming habits.
Bradley−Millspaugh: Front Matter Preface © The McGraw−Hill 3
Advanced Programming Companies, 2010
Using Visual Basic 2008

Case Studies Security Issue


Case Studies provide continuing-theme Any coverage that discusses security
exercises that may be used throughout concerns is pointed out with a Security
the course. Issue icon.

Case Studies files have the same name, you are prompted to select the file to keep. A check
box allows you to show the deleted files since the last copy operation.
See “How to: Copy Web Site Files with the Copy Web Site Tool” in MSDN for
steps to copy all files at once, copy files individually, or synchronize files.
Claytor’s Cottages
Modify your Claytor’s Cottages case study project to the room has a Jacuzzi, Private access, and/or Fire-
Publishing a Web Site
display the room information. The Room form should place. Display the Bed type and the room rates from
display for the Edit / Rooms menu item. the Beds table. The Publish Web Site utility precompiles the Web pages and code content. The
On the Room form, include a combo box that Hint: You can bind the checked property of a compilation process removes the source code from the files and leaves only
holds the room name. Use check boxes to indicate if check box to a Boolean data field. stub files and compiled assemblies for the pages. You can specify the output
location as either a directory or a server location.
Precompiling the Web pages offers a couple of advantages over just copy-
ing the pages. One advantage is response speed. When pages are just copied to
Christian’s Car Rentals
a site, they must compile when a request is made for the page. Not having the
Modify your case study application to display the price and mileage rate in text boxes. The related mod- source code on the site also provides some security. During the publish pro-
vehicle information. Display a combo box that contains els and manufacturer should display in a grid. cess, you have the option of having markup protection, which does not allow for
the car sizes. When the user selects a size, display the later updates to the pages. If you opt to not have the files updatable, the code
in single-file pages is deployed as source code rather than being compiled into
an assembly.

Online Learning Center


Visit the Advanced Programming Using Visual Basic 2008 Web site at
http://www.mhhe.com/AdvVB2008/ for instructor and student resources.
4 Bradley−Millspaugh: Front Matter Preface © The McGraw−Hill
Advanced Programming Companies, 2010
Using Visual Basic 2008

vi P R E F A C E

Many topics from the introductory course are presented in greater detail
and demand more from the students. Many other advanced topics are pre-
sented, including displaying and updating relational databases, WCF Services,
data structures, user controls, Help files, and mobile application development
for Windows devices, along with expanded coverage of cascading style sheets
and AJAX for Web development.
This edition now includes coverage of the many new features in Visual
Studio including LINQ, WPF, and WCF. Both LINQ and WPF have been
placed in Chapter 13, the “Additional Topics” chapter, allowing you to cover
them at any point in the course.
The layout for Web pages uses the preferred method of incorporating <div>
for sections and all formatting with styles. Tables are only used within a <div>.

Major Revisions and Additional Topics in This Edition


With the exception of small, concept-demonstrating programs, all programs
are written as multitier applications. WCF Services are covered prior to Web
applications, and the middle-tier components are written as services.
The text covers the new features of Visual Studio 2008 and many useful
existing features, including
• Windows Presentation Foundation (WPF).
• Windows Communication Foundation (WCF).
• Language-Integrated Queries (LINQ).
• Creation of DataContext objects from database tables for use with LINQ.
• AJAX.
• Cascading style sheets.
• Adding of validation code to the DataSet object.
• Crystal Reports using local databases for both Windows and Web
applications.
• Partial classes.
• The singleton design pattern for a class that should be instantiated only
once.
• Validation of user input using TryParse.
• ClickOnce deployment.
• Generics and generic collections.
• Master pages.
• SQL Server Express, which provides the advantage of local database files
for development and testing.
• TableAdapter, BindingSource, TableAdapterManager (new), and Binding-
Navigator objects.
• Table lookups for populating a combo box from a related table.
• Use of properties and methods of the BindingSource to filter, navigate, and
update database tables.
Bradley−Millspaugh: Front Matter Preface © The McGraw−Hill 5
Advanced Programming Companies, 2010
Using Visual Basic 2008

P R E F A C E vii

• Use of named table relationships.


• Use of related tables in a Web service.
• The Login controls for Web applications.
• Display and updating of data using the Web DataSource objects and data
components: GridView, DetailsView, and FormView.
• The built-in Web server, which allows development of Web applications
without the necessity of running IIS. This feature also allows development
on the home editions of Windows XP and Vista, and does not require
administrative rights for all Web development.
• Smart Device applications, including the new device emulators.
• Use of My.Application for changing culture settings.
• The BackgroundWorker component for executing more than one thread.
New features of the Visual Studio IDE that are covered in the text include
• The Object Relational O/R Designer.
• XAML split windows.
• The TableAdapterManager.
• CSS Properties window, Manage Styles window, and Apply Styles window.

Chapter Organization
Each chapter begins with identifiable objectives and a brief overview. Numer-
ous coding examples as well as hands-on projects with guidance for the coding
appear throughout. Thought-provoking feedback questions give students time
to reflect on the current topic and to evaluate their understanding of the de-
tails. The end-of-chapter items include key terms, a chapter review, questions,
programming exercises, and two case studies. The case studies provide a
continuing-theme exercise that may be used throughout the course. The
in-chapter programs are included on the student Web site, allowing the student
to test and modify existing code. Of course, it is also important to develop a
complete application from scratch to really learn the programming techniques.
Chapter 1, “Visual Studio and the .NET Framework,” discusses the
features of the Visual Studio IDE and the .NET Framework. Applications
demonstrate how to display data from the AssemblyInfo.vb file using the
My object. MDI projects, toolbars, and status bars are reviewed.
Chapter 2, “Building Multitier Programs with Classes,” reviews
object-oriented terminology, creating classes, and instantiating objects.
Creating and throwing exceptions from the business services tier is
introduced. The ErrorProvider and TryParse are demonstrated to
improve the efficiency of validation in the presentation tier.
Chapter 3, “Windows Database Applications,” explains the
relationship of datasets, tables, rows, and constraints. Database
applications use SQL Server databases to display information in grids,
combo boxes, labels, and the database display controls.
6 Bradley−Millspaugh: Front Matter Preface © The McGraw−Hill
Advanced Programming Companies, 2010
Using Visual Basic 2008

viii P R E F A C E

Chapter 4, “Windows Database Using Related Tables,” explores


the types of table relationships and covers the display of related tables on
Windows forms. The chapter discusses how to retrieve and display the
parent row for a selected child row and also an array of child rows for a
selected parent row.
Chapter 5, “Windows Database Updates,” performs updates on
data in a grid, in bound controls on a form, and in unbound controls.
Updating related tables also is covered. Both a combo box selection and
the form’s binding navigator are used to navigate records.
Chapter 6, “Services,” discusses the concepts of WCF Services.
Examples for services include calculations and database access.
Chapter 7, “Web Applications,” discusses the concepts of Web-
based applications and the files that make up a Web project. Hyperlinks
and link buttons allow navigation from one Web page to another while
maintaining the state (data values). The Validator controls test user
input. Master pages and cascading style sheets assist in designing the
layout for the Web site.
Chapter 8, “Web Database Applications,” covers the techniques
for accessing data using data source controls. The chapter discusses
displaying data from related tables and updating databases from a Web
page. Multitier development uses a service for database access and
updates.
Chapter 9, “Reports,” uses advanced reporting features, such as
numeric functions, grouping, sorting, and special fields. Both Windows
applications and Web applications are covered.
Chapter 10, “Collections,” discusses types of collections including
stacks, queues, dictionaries, hash tables, sorted lists, and array lists. The
chapter demonstrates adding objects to the Items collection of a list box.
The chapter also demonstrates implementing the generics and generic
collections.
Chapter 11, “User Controls,” creates Windows user controls and Web
controls. The techniques for raising an event and writing code in the form
to handle the event are discussed.
Chapter 12, “Help Files,” creates the necessary files to set up HTML
Help and uses HTML Help Workshop to create a Help file.
Chapter 13, “Additional Topics in Visual Basic,” demonstrates how
to develop applications for mobile devices, how to create interfaces with
WPF and use the WPF controls in a Windows Form Application, how to
localize an application, and how to use the BackgroundWorker class to
run processes in a separate thread. LINQ is introduced with arrays, LINQ
to SQL, and LINQ to XML.
The appendices offer important additional material. Appendix A
holds the answers to all Feedback questions. Appendix B is an
extensive review of VB topics generally covered in an introductory
course. Appendix C covers deployment using ClickOnce and
Appendix D contains many helpful tips and shortcuts for mastering
the Visual Studio environment.
Bradley−Millspaugh: Front Matter Preface © The McGraw−Hill 7
Advanced Programming Companies, 2010
Using Visual Basic 2008

P R E F A C E ix

Resources for Instructors


The Online Learning Center (OLC) available at www.mhhe.com/
AdvVB2008 contains the following supplemental materials:
Instructor’s Manual
• Objectives with built-in summaries for each chapter.
• Teaching suggestions.
• Answers to the Review Questions from the end-of-chapter material.
• Chapter topics covered in the Programming Exercises.
Testbank offers over 500 questions covering key terms and concepts found
in each chapter. The test questions appear in the form of true-false and
multiple-choice questions. Text page references have been provided for all
questions, including level-of-difficulty rating. A computerized version of
the testbank in EZTest is also available.
PowerPoint Presentation, authored by Brenda Nielsen of Mesa
Community College–Red Mountain, follows the outline of the Instructor’s
Manual and gives instructors a resource for presenting the text material
to a classroom.
Text figures are available electronically for use in presentations,
transparencies, or handouts. These include all the illustrations,
screenshots, and tables featured throughout the book.
An Online Learning Center (OLC) is also available for students and
instructors. The OLC can be found at www.mhhe.com/AdvVB2008 and
offers a wide variety of learning opportunities for students, including
additional case studies, self-quizzes, and downloadable data files.
Instructors also will find the OLC a useful resource.

Acknowledgments
We would like to express our appreciation to the many people who have con-
tributed to the successful completion of this text. Most especially, we thank the
students at Mt. San Antonio College who helped class-test the material and
who greatly influenced the manuscript.
Many people have worked very hard to design and produce this text.
We would like to thank our editors Liz Haefele, Scott Davidson, and Alaina
Grayson. Our thanks also to the many people who produced this text including
Marlena Pechan, and Betsy Blumenthal.
We greatly appreciate John Blyzka, Peter van der Goes, and Robert Price
for their thorough technical reviews, constructive criticism, and many valuable
suggestions. And most importantly, we are grateful to Dennis and Richard for
their support and understanding through the long days and busy phone lines.
8 Notes
Bradley−Millspaugh: Front Matter To the Student © The McGraw−Hill 9
Advanced Programming Companies, 2010
Using Visual Basic 2008

TO THE STUDENT

Welcome to the exciting new features of Visual Basic 2008. You have probably
already learned that the best way to learn how to program is to actually sit at
a computer and write code, change things, and test it again. Stepping through
existing code is also a great tool in learning new techniques. With that in mind,
we have included all of the code from the examples within the chapters on your
student text Web site. Please feel free to load the programs, change things, and
test it again.
But . . . if you really want to learn how it works, it is critical that you create
a blank project and try the techniques yourself. If you run into a problem, take
a look at the sample and compare properties and code.
There are several tools in this text to help you on your way.
• Each chapter begins with a list of topics and ends with a summary. Com-
bine these for a thumbnail review of the chapter. Understanding the ter-
minology is an important part of learning any new language, which is also
true with programming languages.
• A list of key terms is at the end of each chapter. Each of those terms is in
boldface within the chapter. There is also a glossary at the end of the text
where you can look up the definition of the terms.
• Test yourself with the Feedback questions as you work through each sec-
tion of a chapter. The review questions at the end of the chapter can test
your understanding of the topics.
• Tips are included to give suggestions in situations where you may run into
problems caused by the version of software installed/not installed or with
settings.
• Make sure to check out the appendixes, which hold a wealth of support
material.
J.C.B.
A.C.M.

xi
10 Notes
Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill 11
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

Try
With StoresBindingSource
C H .EndEdit()
A P T E R
.AddNew()

1 End With
AddingBoolean = True
SetComboBoxBinding()
Stor_nameComboBox.Focus()
SetControlsReadOnly(False)

Visual Studio and the


SetButtonsForEdit()
If Stor_nameComboBox.SelectedIndex <> -1
' Save the index of the new record fo
.NET Framework
Else
PreviousSelectedIndex = Stor_nameComb

PreviousSelectedIndex = 0
End If
at the completion of this chapter, you will be able to . . .

1. Distinguish the features of the Visual Studio IDE and the .NET Framework.

2. Identify and understand the purpose of each of the files listed in the Solution Explorer.

3. Understand what happens at compile time.

4. Set and display data from the application’s assembly attributes.

5. Create an MDI project with a parent form, child forms, a toolbar, status bar, context menus,
and ToolTips.

6. Use the singleton design pattern to create a class that should be instantiated only once.
12 Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

2 A D VA N C E D P R O G R A M M I N G U S I N G V I S U A L B A S I C 2 0 0 8 Visual Studio and the .NET Framework

Microsoft revolutionized the programming for Windows applications and be-


came a bigger player in the development of Web applications with the introduc-
tion of the .NET Framework and Visual Studio (VS). These products introduced
significant changes into program development for Visual Basic (VB). Not only
did .NET bring true object orientation to the language; it also provided great
advances in the ease of developing projects for cross-platform compatibility.
The two major parts of .NET are the Microsoft .NET Framework and the
Visual Studio integrated development environment (IDE). The IDE is used to
develop programs and the Framework runs the programs.

The .NET Framework


The .NET Framework provides a platform for developing and running applica-
tions and Windows Communications Foundation (WCF) services written in mul-
tiple languages on multiple platforms. The Framework is composed of the common
language runtime, class libraries, and ASP.NET—a component-based version of
active server pages (ASP).

The Common Language Runtime


The common language runtime (CLR) is an environment that manages
execution of code. It provides services for tasks such as integrating components
developed in different languages, handling errors across languages, providing
security, and managing the storage and destruction of objects.
Any code that is compiled to run in the CLR is called managed code.
The managed code automatically contains metadata, which means data that
describe data. A common language runtime portable executable (PE) file con-
tains the metadata along with the code. The metadata include data types, mem-
bers, references, and information needed to load classes and to call methods
from a class.
The CLR also manages memory used by .NET applications. Objects that
are no longer being used are automatically removed from memory by the gar-
bage collector component of the CLR. When you allow the runtime to handle
the garbage collection of objects, the data are referred to as managed data.
Although you can manage application memory yourself, it is usually better and
more secure to let the runtime handle it.
Your code can be integrated with classes and methods of managed code
written in other programming languages. The CLR has standards for data types
that allow you to pass an instance of one of your classes to a method created in
a different language. Although we will not be doing any cross-language pro-
gramming in this text, you should be aware of this powerful feature. Note that it
is also possible to integrate methods and components created in unmanaged
code, but beware of calling unmanaged code such as C++ functions or COM
components as they may introduce security risks to your program.

The Class Library


All of the .NET classes and interfaces are stored in a library known as the
.NET Framework class library. The library is organized into sections or
groups known as namespaces. You should be familiar with some of the common
Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill 13
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

C H A P T E R 1 3

namespaces such as System and System.Drawing. Each namespace contains


classes, structures, enumerations, delegates, and/or interfaces that you can use
in your programs. Table 1.1 shows some of the namespaces in the .NET Frame-
work class library.

Selected Namespaces from the .NET Class Library Ta b l e 1.1


Namespace Contents

System Base classes and fundamental classes for data types,


events, and event handlers.

System.Collections Definitions of collections of objects such as lists,


queues, and dictionaries.

System.Data ADO.NET architecture used to access databases.

System.Drawing GDI+ graphics for drawing on the screen, printer, or


any other graphic device.

System.IO Types for reading and writing data streams and files.

System.Linq Supports queries for Language-Integerated Queries

System.Security Base classes for permissions.

System.Threading Classes for multithreaded programming.

System.Web.Services Classes for building and using Web Services.

System.Windows.Forms Classes for creating graphical components for programs


that execute in the Windows operating environment.

System.XML Support for XML processing. XML is a standard for


transferring data.

The classes in the library comply with published standards known as the
Common Language Specification (CLS). The CLS specifies how a lan-
guage that interacts with the CLR should behave. If you want a program to in-
teract with programs and components written in other languages, you should
make sure that it is CLS compliant. The rules for CLS compliance can be found
in the .NET Framework Developer’s Guide under the heading “Writing CLS-
Compliant Code.” Note that all VB programs that you write using the VS IDE
will be CLS compliant automatically.

Types
The .NET documentation uses the general term types to refer to the classes,
structures, enumerations, delegates, interfaces, and data types in the library, as
well as any that you define. You can think of a type as any element that you can
use in the As clause of a declaration:

Dim AnyName As SomeType

Value Types versus Reference Types


When you declare a variable, it may be considered a value type or a refer-
ence type. The difference between the two determines how the runtime will
14 Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

4 A D VA N C E D P R O G R A M M I N G U S I N G V I S U A L B A S I C 2 0 0 8 Visual Studio and the .NET Framework

treat the variables when you assign one variable to another. For example, if you
assign one integer variable to another, you have two memory locations with the
same value:

SecondValueInteger = FirstValueInteger

However, if you assign one reference type to another, you have two variables
that point to the same object in memory:

SecondForm = FirstForm ' Assign reference for first form to second form.

Any changes that you make to either variable are made to the one object in
memory to which both variables refer. In some previous versions of VB, refer-
ence types were called object variables. However, VB reference types include
more types than the more restrictive object variables.

' Value types.


Dim FirstValueInteger As Integer = 10
Dim SecondValueInteger As Integer
SecondValueInteger = FirstValueInteger
FirstValueInteger = 5
' What is the value in each of the variables?
Debug.WriteLine("FirstValueInteger = " & FirstValueInteger.ToString() & _
"; SecondValueInteger = " & SecondValueInteger.ToString())

' Reference types.


Dim FirstForm As New Form1()
Dim SecondForm As Form1
SecondForm = FirstForm ' Assign reference for first form to second form.
SecondForm.Text = "Second Form Caption"
FirstForm.Text = "New Caption for First Form"
' What is the Text property of FirstForm? Of SecondForm?
Debug.WriteLine("FirstForm = " & FirstForm.Text & _
"; SecondForm = " & SecondForm.Text)

Can you predict the debug output from the two groups of statements above?
Follow the logic and write down your answer; then look back here to check
your understanding.

FirstValueInteger = 5; SecondValueInteger = 10
FirstForm = New Caption for First Form; SecondForm = New Caption for First Form

All numeric data types are value types. Reference types include class types,
arrays (even if the individual elements are numeric), and strings. A value type
always holds a value; when you declare a new variable of a value type, the vari-
able is always initialized, either to a value that you supply or to the default value.
A reference type may or may not hold a value; you can use the IsNot Nothing
condition to determine whether the variable refers to an instance of an object.

Compiling to Intermediate Language


The program code that you write is referred to as source code. The compiler
translates your code into Microsoft intermediate language (MSIL) or
Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill 15
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

C H A P T E R 1 5

sometimes referred to as just IL. MSIL is a platform-independent set of in-


structions that is combined with the metadata to form a file called a portable
executable (PE) file, which has an .exe or .dll extension. When your program
runs, the MSIL is converted to the native code of the specific machine only
as it is needed, using a just-in-time (JIT) compiler, which is part of the CLR
(Figure 1.1).
Figure 1.1

The steps in compiling and


CLS PE Native code
Managed executing a program using the
compliant JIT for target
source .NET CLR.
language MSIL and compiler computer
code
compiler Metadata

Assemblies
An assembly is a basic unit of code that may be a single PE file or multiple
files. Each of your applications will be contained in a single assembly, which
is the smallest deployable piece of code. An assembly has an assembly man-
ifest that contains metadata about the version, a table describing all of the
files needed by the assembly, and an “assembly reference list” that specifies
all of the external files needed, such as DLLs created by someone else. An
assembly is similar to an .exe or a .dll file written in earlier versions of Visual
Basic—it contains all of the necessary information to run the application or
component.
Recall that the .NET Framework class library is not one big file but
rather a collection of files. The classes are stored in many files with the ex-
tension .dll and referred to as DLLs (for dynamic link libraries). Each of the
DLLs in the class library is one assembly. As your program begins execu-
tion, only the needed assemblies are loaded into memory. When you want to
use a type that is not already referenced, you must add a reference to the
DLL (assembly).

Attributes
Attributes are tags containing information about parts of a program such as
types or methods. The system defines many attributes of your assembly, such
as the name, version, culture, and security. The attributes are part of the meta-
data in a .NET assembly. The process of examining the metadata in an assem-
bly’s attributes is called reflection.
Later in this chapter, you will learn to retrieve and use the custom attri-
butes in a project’s assembly information, which is stored in the Assembly-
Info.vb file.

The References Collection


A reference object is used to connect a Visual Basic project to external com-
ponents. The two types of reference objects are assemblies and COM objects.
A reference to another project is an assembly reference and is called a project-
to-project reference. COM objects are components written in versions of VB
prior to .NET, or other non-CLS-compliant languages.
16 Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

6 A D VA N C E D P R O G R A M M I N G U S I N G V I S U A L B A S I C 2 0 0 8 Visual Studio and the .NET Framework

ASP.NET
Another big part of the .NET world is the improvement in Web development.
ASP.NET 3.5 is the newest version of Active Server Pages (ASP). It is a Web
development environment that can compile applications written in any .NET-
compatible language including Visual Basic. This means that the benefits of the
common language runtime and managed code are available for developing Web
applications. ASP.NET makes Web development easier by providing the same
debugging support for Web Forms and Web Services as for Windows applications.
You will begin working with ASP.NET in Chapter 7. Chapters 8 and 9
cover accessing databases from ASP.NET, which is a common technique for
displaying data on a Web site.

➤ Feedback 1.1
1. What is meant by the term .NET Framework?
2. What are the meaning and function of each of these terms?
a. CLR
b. CLS
c. MSIL
d. PE
3. What is the difference between a reference type and a value type? Why
is it important to know the difference?

Visual Studio
Although you could write your programs in any editor and then use the VB com-
piler to compile them, Visual Studio provides an environment to make your devel-
opment task easier. You should already be familiar with the various windows in the
environment as well as the basic debugging capabilities. For a review of the VS
IDE, as well as tips and shortcuts, see Appendix D. This section introduces you to
more details about the parts of a project and changes to the VS environment.
Note: This chapter introduces writing Windows applications. You also have
the option of writing Windows Presentation Foundation (WPF) applications.
Although WPF applications are introduced in Chapter 13, you might prefer to
begin there and write all of your programs using WPF.

Temporary Projects
You can create temporary projects for testing, without saving them. This can be
both good and bad: You don’t have to clutter your drive with small projects that
you create just to test something, but you may forget to save a project that you
wanted to keep.
When you create a new project, by default it is a temporary project, which
VS stores in a temporary folder on the hard drive. So even when you compile
and run the project, the compiler saves the files in the temporary folder. When
you exit VS or choose to begin another project, you are presented with the
option to save or discard the project (Figure 1.2).
If you want to always save new projects, you can select that option in the
Options dialog box. Choose Tools / Options / Projects and Solutions and select
Save new projects when created.
Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill 17
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

C H A P T E R 1 7

Figure 1.2

You can save or discard a


temporary project.

Setting Environment Options


The Options dialog box provides several useful features. Select Tools / Options
and select the check box for Show all settings (Figure 1.3). By default, for a VB
developer profile, the Options dialog box shows a limited subset of the options
you can set. You may want to spend some time exploring the various options.
Figure 1.3

Select Show all settings to see


all of the options that you can
view and change in the Options
dialog box.

Select Show all settings

Selecting the Visual Basic Development Settings


When you install VS 2008, you are prompted to specify the profile for the
default settings. This text is based on choosing the Visual Basic Development
settings. If you are sharing a computer with someone developing in a different
language, or the proper settings were not chosen, you may need to reset the
defaults. Choose Tools / Import and Export Settings. In the wizard, specify Reset
all settings. Next you can choose to save the current settings or just overwrite
them (likely the best choice), and then select Visual Basic Development
Settings.

Setting the Location of Project Files


You can change the default folder that VS uses to store and retrieve project
files. Select Tools / Options; in the Options dialog box, select Projects and
Solutions and change the entry for Visual Studio projects location.
18 Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

8 A D VA N C E D P R O G R A M M I N G U S I N G V I S U A L B A S I C 2 0 0 8 Visual Studio and the .NET Framework

Setting Option Explicit and Option Strict Defaults


It’s best to set the Option Strict default for all projects, rather than set it in ev-
TIP
Set the default for Option Strict to
ery project. Select Projects and Solutions / VB Defaults in the Options dialog box
On now so that you don’t have to be
and set both Option Explicit and Option Strict on.
concerned about it in the future. ■
Displaying the Grid on Windows Forms
The Windows Form Designer includes snap lines, which is a great feature that can
help you to align controls. Blue snap lines appear when the edges of controls are
aligned; red snap lines appear when the text baselines of controls are aligned; and
dotted lines appear when two controls are the recommended distance apart. The
visible grid does not appear on a Windows Form by default, but you can make the
grid dots appear to match early versions of VB. In the Windows Forms Designer
section of the Options dialog box, select SnapToGrid for LayoutMode and True for
ShowGrid. Before setting this option, however, make sure to try using snap lines,
which make form design much easier than the old snap-to-grid method.

The Solution Explorer


Take a look at the files in the Solution Explorer for a new Windows application
(Figure 1.4). When you click on the Show All Files button, you can see the
Figure 1.4

Show All Files Click the Show All Files button


to see all of the files and folders
in the Solution Explorer.

bin\Debug folder
obj folder
Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill 19
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

C H A P T E R 1 9

hidden files and folders. The My Project folder holds several files for project
configuration, including AssemblyInfo.vb. You will learn to view and set con-
figuration options in the Project Designer, which is discussed in the “The
Project Designer” section later in this chapter.
In Figure 1.4, you can see the expanded References collection, the bin and
obj folders, and the form files for Form1.vb. You can expand each of the nodes
to see more details. Note that the solution name does not display by default. To
show the solution name, as in Figure 1.4, select Tools / Options / Projects and
Solutions and check Always show solution. You will want to always show solu-
tions so that you can edit solution names.

References
In the References folder, you can see a list of System libraries (DLLs), such as
System, System.Deployment, System.Drawing, and System.Windows.Forms.
These are the references included by default for a new Windows application.
You can add a reference by right-clicking on the References folder and select-
ing Add Reference from the context menu. You also can add references in the
Project Designer, which is discussed a little later. You may need to add a refer-
ence if you want to refer to objects in another assembly or components written
in a different language.

The Bin and Obj Folders


Notice the organization of the bin and obj folders:
bin
Debug
Release
obj
Debug
Release
When you compile and run a project using the debugger, you are running the
program stored in the bin\Debug folder. The debug versions of the compiled proj-
ect are not optimized for release. If you compile a program for release, the com-
piled versions are placed in the Release folders. Notice the files in the bin\Debug
folder in Figure 1.5, which shows the Solution Explorer after compiling a project.
Figure 1.5

After compiling a project and


clicking the Refresh button,
the bin\Debug folder holds the
files needed to run the program
in the debugger.

The executable
Debugging information
20 Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

10 A D VA N C E D P R O G R A M M I N G U S I N G V I S U A L B A S I C 2 0 0 8 Visual Studio and the .NET Framework

The project’s .exe file is the executable, which is used to run the program; the
.pdb file holds debugging information. If you are distributing your application,
you only need to distribute the .exe file, not the .pdb file. The ProjectName.
vshost.exe file is a small application that runs the project in the environment.

Project Resources
The Resources folder holds resources that you add to your project. Figure 1.6
shows a graphic file stored in the Resources folder; you can also add sound
files and text strings to the resources.
Figure 1.6

The Resources folder holds the


project resources, such as
graphic and sound files, and
text strings.

Visual Studio provides several ways to add resources to the folder and to
access those resources. You can add resources in the Project Designer, dis-
cussed later in this chapter. You also can add resources from the Properties
window, such as when you set the Image property of a PictureBox control. At
design time, you can assign properties of controls to resources that are in the
Resources folder, and you can retrieve resources at run time using the My.Re-
sources object, which also is discussed later in this chapter.
Each form in your project also has a resource file, which has a .resx exten-
sion. For example, Form1.vb has a Form1.resx file, which you can see in the
Solution Explorer when you click on the Show All Files button and expand the
form’s node.
The .resx file is mostly text in XML format, which you can open and view
in the IDE. The .resx file holds pointers to the files in your Resources folder
and supplies the resources to the form at compile time. Any graphic elements
that you add to the form, such as a PictureBox’s Image property or a form’s
Icon property, also are stored in the .resx file in text that represents the binary
graphic file.
If you rename your form file in the Solution Explorer, the .resx file is auto-
matically renamed to match. At times you may find extra .resx files in the
project’s folder; you can safely delete any extra .resx files if their names do not
match any forms in the project.

Image Files in Visual Studio 2008 Microsoft is including many graphic files
with Visual Studio 2008. The graphics are those used in Windows so that you
can make your applications use the standard images. The default location for
Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill 21
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

C H A P T E R 1 11

the graphics is C:\Program Files\Microsoft Visual Studio 9.0\Common7\


VS2008ImageLibrary\1033\VS2008ImageLibrary.zip. You may have to unzip
the files to use them.

Partial Classes
Partial classes, also called partial types, is a feature that was added in the
2005 version of Visual Studio. In its simplest form, partial classes allow you to
split a class into two or more separate files.

The Form’s Designer-Generated Code


A big advantage of partial classes is that the VB Form Designer can split the
form’s class into two parts, separating the designer-generated code from the
developer-written code. In Figure 1.7, you can see that Form1 consists of two
files, plus the .resx file. Form1.vb holds the VB code that you write; Form1.
Designer.vb holds the designer-generated code. You don’t generally see these
extra files unless you select Show All Files in the Solution Explorer. You can
double-click a filename to see the contents of the file.
Figure 1.7

Form1.vb holds your VB code;


Form1.Designer.vb holds the
code automatically generated
by the Windows Form Designer.
Click on Show All Files to see
these normally hidden files.

Programmer-written VB code
Designer-generated VB code
Resource file for the form

The file that holds the designer-generated code includes the class inheri-
tance information:

Partial Class Form1


Inherits System.Windows.Forms.Form

The partial class instantiates the form and the visual components for the
form as well as stores property settings.
The form’s class file that holds the programmer-written code begins with
this line:

Public Class Form1

The compiler uses the statements in both files to create the compiled class.
Note that you can create multiple partial class files and one single file without
the “Partial” designation.
22 Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

12 A D VA N C E D P R O G R A M M I N G U S I N G V I S U A L B A S I C 2 0 0 8 Visual Studio and the .NET Framework

The Project Designer


The Project Designer is sometimes called the Project Properties dialog box. You
can open the Project Designer by double-clicking on the My Project folder in the
Solution Explorer or by selecting Project / ProjectName Properties. The Project
Designer includes tabs for Application, Compile, Debug, References, Resources,
Services, Settings, Signing, My Extensions, Security, and Publish (Figure 1.8).
Figure 1.8

Display the Project Designer by double-clicking on the My Project folder in the Solution Explorer.

Assembly
information

The Application Tab The Application tab is the default tab that appears on top
when you open the Project Designer. On the Application tab, you can set the ap-
plication type, the startup form, the icon, and the splash screen. You also can
display and set the application’s assembly information from this dialog. Later
in this chapter, we will use many of these options.

The Compile Tab On the Compile tab, you can set the path for the compiler
output. You also can alter the settings for Option Explicit and Option Strict
and specify which errors should be flagged by the compiler and which should
be ignored.

The References Tab The References tab displays the names and paths for the
project references. You can add and remove references to Windows or Web
library components, as well as external components, in this dialog.

The Resources Tab The Resources tab allows you to easily add and remove the
graphic files that you use for picture boxes and toolbars, any sound files, and
text strings in various languages to use for localization.
Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill 23
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

C H A P T E R 1 13

The Signing, Security, and Publish Tabs The settings on the Signing, Security,
and Publish tabs are used for ClickOnce deployment. Using ClickOnce deploy-
ment, you can set up applications to be deployed and updated on multiple sites
via the Web. This technique is primarily used by large organizations to facili-
tate deploying applications to many users.

Deploying Windows Applications


Most of this text is devoted to writing and testing applications using the Visual
Studio IDE. However, once you get an application tested and ready for use, you
will want to deploy it and run it on another computer. To run a .NET Windows
application, the target computer must have the .NET Framework or the .NET
Framework Redistributable installed. The Redistributable file is available for
free download on Microsoft’s Web site and is available for Windows XP and Vista.
You can choose from several methods for deploying your Windows applica-
tions: (1) XCopy deployment, (2) Windows Installer technology, (3) ClickOnce
deployment, or (4) third-party installer products.
XCopy deployment gets its name from the old DOS XCOPY command, which
copied all files in the current folder and all subfolders. Although you can use the
XCOPY command for copying files, XCopy deployment simply means that you
copy the necessary files from the development machine to the target machine.
Deploying a compiled Windows application can be as easy as copying the
.exe file from the bin folder to another computer. This technique is not very
robust but can work for a simple installation. However, deploying a Web ap-
plication is a little more complicated because more than one file is needed to
run an application.
Microsoft Windows Installer is a separate application that ships with Win-
dows. The installer creates .msi files that contain the application and any sup-
port files needed for deployment. Deployment is covered in Appendix C.

The VB My Objects
The Visual Basic My object provides several objects and properties. My gives
you easy access to information about your application and its resources, the
computer on which the application is executing, and the current user.
It is easy to discover the available objects using IntelliSense (Figure 1.9):
Application, Computer, Forms, Resources, Settings, User, and Web Services.

Figure 1.9

Type “My.” to see the available


My objects in IntelliSense.
24 Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

14 A D VA N C E D P R O G R A M M I N G U S I N G V I S U A L B A S I C 2 0 0 8 Visual Studio and the .NET Framework

You can retrieve information about the user’s computer, operating system,
and amount of memory with My.Computer.Info (Figure 1.10).
If you want to know the name of the user, you can use

UserNameString = My.User.Name

In the following section, you will use My.Application to retrieve the assem-
bly information about an application.
Figure 1.10

Use My.Computer.Info to
retrieve information about
the user’s computer.

Using Assembly Information


You can set an application’s assembly information, also called the assembly
attributes, and retrieve the information at run time.

Setting the Assembly Information


You can view and set an application’s assembly information in the Assembly
Information dialog box. Double-click on My Project in the Solution Explorer
TIP
to display the Project Designer’s Application tab (refer to Figure 1.8); then Always give the new project a name
click on the Assembly Information button, which displays the dialog box. when you create it, which sets the
Figure 1.11 shows the default information for an application called root namespace, assembly name,
WindowsApplication1. and project name. ■

Figure 1.11

The Assembly Information


dialog box with the values
supplied by default. You can
edit the entries to the values of
your choice.
Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill 25
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

C H A P T E R 1 15

Figure 1.12

The assembly information for


the chapter hands-on program-
ming example.

Type appropriate entries for your applications. Figure 1.12 shows the as-
sembly information for the chapter hands-on example program.
Another way to modify a project’s assembly information is to edit the
AssemblyInfo.vb file directly. You can see the file in the Solution Explorer
beneath the My Project folder when Show All Files is selected (Figure 1.13).
Double-click the filename to display the file in the editor.

Figure 1.13

You can modify the assembly information by editing the AssemblyInfo.vb file.
26 Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

16 A D VA N C E D P R O G R A M M I N G U S I N G V I S U A L B A S I C 2 0 0 8 Visual Studio and the .NET Framework

Retrieving the Assembly Information


You can retrieve assembly attributes in a VB program using the My.Application.
Info object. The properties of the object include many items that describe the
application, including
• AssemblyName
• CompanyName
• Description
• DirectoryPath
• Copyright
• Trademark
• Name
• ProductName
• Title
• Version
You can display the Title attribute in a label using the following statement:

TitleLabel.Text = My.Application.Info.Title

The following program displays the assembly attributes in labels on a form.

Write a Test Program


Begin a new project in VB and double-click on the My Project folder in the So-
lution Explorer to open the Project Designer. Click on the Assembly Information
button to open the Assembly Information dialog box and enter the information
(Figure 1.14).
On the form, add labels for Name, Title, Description, Company, Product,
Version, and Copyright.
Figure 1.14

Enter the assembly information


for the demonstration program.
Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill 27
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

C H A P T E R 1 17

Write the code to assign values to the labels in the Form_Load event
procedure. The code uses the My.Application.Info object to retrieve the
attributes.

Private Sub MainForm_Load(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles MyBase.Load
' Retrieve the assembly information.

With My.Application.Info
NameLabel.Text = .AssemblyName
TitleLabel.Text = .Title
DescriptionLabel.Text = .Description
CompanyLabel.Text = .CompanyName
ProductLabel.Text = .ProductName
VersionLabel.Text = "Version: " & .Version.ToString
CopyrightLabel.Text = .Copyright
End With
End Sub

Run the Test Program


Run the program. Your output should be similar to Figure 1.15.

Figure 1.15

The assembly information


displays in labels in the
example program’s output.

Viewing a Program’s Attributes


After you enter assembly information and compile your project, you can view
the attributes in Windows Explorer. Point to the filename in the project’s bin\
Debug folder, either an .exe or .dll file, and pause; the attributes pop up auto-
matically (Figure 1.16).
Figure 1.16

The application’s attributes


display when you pause the
mouse pointer over the filename
in Windows Explorer.
28 Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

18 A D VA N C E D P R O G R A M M I N G U S I N G V I S U A L B A S I C 2 0 0 8 Visual Studio and the .NET Framework

➤ Feedback 1.2
Write the statements necessary to retrieve and display the copyright attribute
in CopyrightLabel.

Menus, Toolbars, and Status Bars


To create menus, context menus, toolbars, and status bars, use the components
in the Menus & Toolbars section of the toolbox (Figure 1.17). The components
are MenuStrip, ContextMenuStrip, ToolStrip, and StatusStrip.
Visual Studio also includes designers that simplify creating menus, tool-
bars, and status bars. The designers are pretty smart; they give each element a
meaningful name so that you don’t have to rename your menu items. You also
can use the controls’ smart tags, which simplify setting properties.
Figure 1.17

The MenuStrip,
ContextMenuStrip, ToolStrip,
and StatusStrip components
are grouped together in the
Menus & Toolbars section of
the toolbox.

Creating Menus with MenuStrips


When you add a MenuStrip to a form, the component appears in the component
tray and the words “Type Here” appear in the new menu bar. Notice in Fig-
ure 1.18 that when you point to the new menu item, a drop-down arrow appears,
which you can use to add different controls to the menu bar. The selected menu
bar also shows a smart tag arrow, which you can use to set some of the proper-
ties of the menu bar.
Figure 1.18

The MenuStrip component


appears in the component tray.
Smart tag arrow for MenuStrip Type your first menu item where
the words “Type Here” appear.
Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill 29
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

C H A P T E R 1 19

The MenuStrip and ContextMenuStrip components allow you to select a


control or separator bar for each menu item. Drop down the list for a menu item
to see the choices (Figure 1.19). You can easily add a new item or a separator
bar in the menu.
Figure 1.19

Drop down the list for a new


menu item and make a
selection from the list.

You can use the MenuStrip’s smart tag (Figure 1.20) to set some properties of
the menu bar. Select Edit Items to open the Items Collection Editor (Figure 1.21),
where you can set properties of the menu items, and add, remove, and rearrange
the items.
When you use the visual menu designer to create menus and menu items,
each item is automatically given a meaningful name. But if you add a menu
item in the Items Collection Editor, you must name the item yourself.
Figure 1.20

MenuStrip's Smart tag Open the MenuStrip’s smart tag


to set properties of the menu
bar; select Edit Items to edit the
individual menu items.

TIP
The keyboard shortcut for opening
a smart tag when its arrow appears
is Alt + Shift + F10. ■

Menus and Menu Items


Each MenuStrip and ContextMenuStrip component is a container, which holds
a collection of menu items. Both top-level menus and the items below the menu
names are considered menu items. A menu item also can contain a collection
of items. For example, the File menu is a menu item, called FileToolStripMenu-
Item by default; the FileToolStripMenuItem contains a collection of the menu
items that appear in the File menu, such as ExitToolStripMenuItem.
Referring to Figure 1.21, notice that at the top-right side, the collection is
MenuStrip1, the MenuStrip itself. The items listed in the Members list are the
top-level menus.
30 Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

20 A D VA N C E D P R O G R A M M I N G U S I N G V I S U A L B A S I C 2 0 0 8 Visual Studio and the .NET Framework

Figure 1.21

In the Items Collection Editor, you can add and remove menu items, reorder items, and set properties of the items.

Sort properties in alpha order

Object type MenuStrip1 is selected

You can edit any of the items by selecting it in the Members list. Figure 1.22
shows the FileToolStripMenuItem selected. Notice that the top right now indicates
the selected item and that one of the properties of the FileToolStripMenuItem is a
DropDownItems collection. If you select that collection, the Items Collection

Figure 1.22

Edit the properties of the individual menu items in the Items Collection Editor. Notice that the FileToolStripMenuItem has a
DropDownItems property, which is a collection of the menu items that appear below the File menu.
FileToolStripMenuItem is selected

Open Collection Editor for


items below the File menu
Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill 31
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

C H A P T E R 1 21

Editor displays the items beneath the File menu. Also notice in Figure 1.22 that
the right side of the Items Collection Editor is similar to the Properties window in
the IDE. You can click on the buttons to display the properties in alphabetic order
or categorized view.

Creating Context Menus with ContextMenuStrips


Context menus are the shortcut menus that you display by pointing to an item
and right-clicking. You should plan your applications to include context menus
for all operations that the user might want to perform.
You create context menus in nearly the same way that you create menus.
Add a ContextMenuStrip to a form and add menu items using the visual menu
designer (Figure 1.23).

Figure 1.23

The ContextMenuStrip component appears in the component tray. When it is selected, the visual menu designer appears to
allow you to enter menu items.

A context menu does not include a top-level menu name; instead each of the
items belongs to the Items collection of the ContextMenuStrip. Notice that the
smart tag arrow appears on the component in the component tray, rather than on
the menu in the designer. You can select Edit Items from the smart tag or select
the Items property in the Properties window to edit the individual menu items.
The form and each of the controls that you add to the form has a Context-
MenuStrip property. You assign the context menu to the form or control by se-
lecting its name in the Properties window. Note that you can add multiple
context menus to the component tray and assign each to a different control.
If you assign a context menu to a form, it becomes the default context menu
for the form and most controls on the form. However, controls that allow text
entry, such as text boxes and combo boxes, have a default context menu that
contains the editing items Cut, Copy, and Paste. If you assign your own context
menu to a text control, you will lose the items on the default context menu.
You can easily assign a single event handler to both a menu item and a
context menu item. Add the second item to the Handles clause of the event
handler. In the following example, the event handler is executed for the Click
32 Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

22 A D VA N C E D P R O G R A M M I N G U S I N G V I S U A L B A S I C 2 0 0 8 Visual Studio and the .NET Framework

event of both the menu item and context menu item. Note that the menu
designer named the context menu item with the same name as the menu item,
with the addition of the numeral “1”.

Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs)_
Handles ExitToolStripMenuItem.Click, ExitToolStripMenuItem1.Click
' Exit the program.

Me.Close()
End Sub

Creating Toolbars with ToolStrips


Toolbars typically hold buttons that are shortcuts to menu items. You will use
ToolStrip components to create toolbars.
TIP
ToolStrips are very closely related to MenuStrips. In fact, the MenuStrip Beware of using Application.Exit( )
class inherits from the ToolStrip class and shares many of the same properties as any code in the FormClosing
and behaviors. event will not execute. ■
You have many choices for the types of controls to add to a ToolStrip
(Figure 1.24).

Figure 1.24

The ToolStrip component appears in the component tray. You can drop down the list for the types of buttons and controls that
you can add to the ToolStrip.

After you add the buttons to the ToolStrip container, you can set the prop-
erties of each button in the Properties window or in the Items Collection Editor, TIP
which you display from the smart tag. You will need to give the toolbar buttons Set the ToolTipText property of each
meaningful names; the visual designer assigns names like ToolStripButton1. toolbar button to aid the user, in
Your buttons can hold an image, text, or both. Generally you will want to case the meaning of each graphic is
place an image on the button and set the ToolTip text to indicate the purpose of not perfectly clear. ■
Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill 33
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

C H A P T E R 1 23

Figure 1.25

Set the Name, Image, and ToolTipText properties for each ToolStripButton.

Image property appears


above

ToolTip

Name

the button. Figure 1.25 shows a ToolStripButton’s properties with an image,


ToolTip text, and a meaningful name.

Creating Status Bars with StatusStrips


Status bars generally appear at the bottom of a form and supply information to
the user. Some applications display error messages in status bars; often a status
bar holds the system date and time.
VB uses StatusStrip components to create status bars. StatusStrip compo-
nents, like MenuStrips and ContextMenuStrips, inherit from ToolStrips and
share many of the same characteristics. Figure 1.26 shows the controls that you
can add to a StatusStrip.
To display text on a status bar, add a StatusLabel to the StatusStrip. You
will want to give StatusLabel objects meaningful names since you will refer to
the labels in code. You can control whether labels appear at the right or left
end of the status bar by setting the StatusStrip’s RightToLeft property to Yes or
No. By default, the property is set to No and labels appear at the left end of the
status bar. You also can set a StatusLabel to appear at the left end of a status
bar and fill the status bar, even though RightToLeft is set to Yes and some
labels appear at the right end: Set the StatusLabel’s Spring property to true.
You can display the date and time in status labels in the Form_Load event
handler.

Private Sub MenuForm_Load(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles MyBase.Load
' Set the date and time in the status bar.

DateToolStripStatusLabel.Text = Today.ToShortDateString
TimeToolStripStatusLabel.Text = Now.ToLongTimeString
End Sub
34 Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

24 A D VA N C E D P R O G R A M M I N G U S I N G V I S U A L B A S I C 2 0 0 8 Visual Studio and the .NET Framework

Figure 1.26

Drop down the list to add a


control to a StatusStrip.

Displaying the Date and Time


You use the properties and methods of the DateTime structure to retrieve
and format the current date and time. The Now property holds the system
date and time in a numeric format that can be used for calculations. You can
format the date and/or time for display using one of the following meth-
ods: ToShortDateString, ToLongDateString, ToShortTimeString, or
ToLongTimeString. The actual display format of each method depends on the
local system settings.
You can set the display value of StatusStripLabels in any procedure; however,
the display does not update automatically. Generally, you will set initial values in
the Form_Load event procedure and use a Timer component to update the time.

Using a Timer Component


To use a Timer component, you add the component to the form, set some
properties, and write code in the Timer’s Tick event handler. Add the Timer
component from the Components section of the toolbox. Then in the Properties
window, set the Enabled property to true and set the Interval property. The In-
terval is measured in milliseconds; set the Interval to 1000 to make the Timer’s
Tick event fire every second.

Private Sub Timer1_Tick(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles Timer1.Tick
' Update the time in the status bar.

DateToolStripStatusLabel.Text = Today.ToShortDateString
TimeToolStripStatusLabel.Text = Now.ToLongTimeString
End Sub
Bradley−Millspaugh: 1. Visual Studio and the Text © The McGraw−Hill 35
Advanced Programming .NET Framework Companies, 2010
Using Visual Basic 2008

C H A P T E R 1 25

➤ Feedback 1.3
What steps are necessary to display the current time in a StatusStrip label
called CurrentTimeStatusStripLabel?

MDI Applications
In this section, you will create a multiple document application with parent
and child forms, a menu bar, context menus, a toolbar, and a status bar.

Multiple Document Interface


You can create forms as a single document interface (SDI) or multiple
document interface (MDI). Using SDI, each form in the project acts inde-
pendently from the other forms. However, VB also allows you to create a mul-
tiple document interface. For an example of MDI, consider an application such
as Microsoft Word 2003, which has a parent form (the main window) and
child forms (each document window). You can open multiple child windows,
and you can maximize, minimize, restore, or close each child window, which
always stays within the boundaries of the parent window. When you close the
parent window, all child windows close automatically. Figure 1.27 shows an
MDI parent window with two open child windows.
Figure 1.27

The main form is the parent and


the smaller forms are the child
forms in an MDI application.

With MDI, a parent and child relationship exists between the main form
and the child forms. One of the rules for MDI is that if a parent form closes, all
of its children leave with it—a pretty good rule. Another rule is that children
cannot wander out of the parent’s area; the child form always appears inside
the parent’s area.
VB allows you to have forms that act independently from each other. You
may have a parent form and several child forms and some forms that operate
independently. For example, a splash form likely should remain SDI.
One feature of MDI is that you can have several child windows open at the
same time. The menu bar generally contains a Window menu that allows you to
display a list of open windows and move from one active window to another.
Random documents with unrelated
content Scribd suggests to you:
CHAPTER XIX
A GALLOPING TO AND FRO

THE dull, plodding peasants of Persia, Medea, Susiana, and


Babylonia wondered why so many messengers rode at breakneck
speed, on foaming, dusty horses, and so many squads of cavalry
galloped, along the roads, during those last days of the false
Smerdis, or Bardya, King of the World. They loved not these military
men, with their over-bearing ways, their oaths and blows, their
lawlessness and oppression. But they only sighed and remained
silent, hoping but not believing that some day the Great King would
lift them up and put the soldiers down. The shepherds on the hills
drove their flocks high up into the mountain fastnesses and
concealed them in gulches and ravines. For, it was whispered, an
immense army of Persians was marching up from the south. No one
knew why it was coming, but it was safer to keep the flocks out of
sight, lest the hungry hordes should have fresh meat at their
expense. Rumors of war flew about. Some said Babylonia was about
to revolt; others that the Scythians were threatening an invasion.
Meanwhile at the capital city, Hamadan, confusion reigned. Reports
came from Persia indicating that the King of Iran was gathering a
great army. Then came messengers from the army at Damascus
relating the departure of the Prince and the Guard. Patatheites and
Gaumata at once became uneasy and directed the governor of
Nineveh to march out and intercept the Prince. Then came
Prexaspes, who, knowing that he could expect no mercy from the
King of Iran and his son, offered his services to the usurper, and was
made commander of the army and satrap of Medea. He advised
immediate preparation for war. Decrees were issued to all the
governors of provinces commanding them to assemble their soldiers
and bring them to Hamadan. Heralds were dispatched to the King of
Iran demanding the reason for gathering an army at Persepolis.
Prexaspes personally went into western Medea, where he had large
estates, and directed that all Medean levies from that section should
gather at Nicæa. Then Gaumata and Patatheites, learning that their
ruse whereby Athura had been beguiled into the castle of the former,
had succeeded, departed from the capital city to visit her and make
some treaty with, or disposal of, her. They had barely departed when
Captains Arios and Mardux at the head of their combined companies
rode into the capital on horses almost dead with fatigue, and at the
palace gates demanded the person of the Princess Athura. The
commander of the palace-guard was insolent and insulting. He even
threatened to arrest the blustering captains, who thereupon suddenly
assaulted the palace with their bold troopers, before the guards
could be warned, and gained possession of it. The guards fled into
the city and called upon the citizens for aid. Captains Arios and
Mardux searched the palace in vain for the Princess Athura, but
found and released the usurper’s harem, in which was Phædima, the
daughter of Otanes. What next to do the captains knew not. But the
citizens of Hamadan, indignant that a company of freebooters should
dare to take the King’s palace, soon gave them something to do and
laid close siege to them in it. They were not to be dislodged,
however, and held the citizens at bay, trusting that they would
presently be rescued by the King of Iran.
The Prince of Iran, having marched by a short route across northern
Arabia, avoided Babylon on the right and Susa on the left and
arrived upon the great highway between Persepolis and the latter
city, where, as narrated, he received information that led him to
march at once to Susa, intent upon aiding in the rescue of the
Princess Athura. He seized Susa and deposed its governor, who
was a Mede in the service of Gaumata. He paused here two days to
rest and refit his command, meanwhile sending scouts northward to
gain information concerning the movements of the usurper. Then a
body of Persians, constituting the advance corps of the Persian
army, having arrived, the Prince left a garrison in the city and with
about twenty thousand men hurried northward on the road to
Hamadan, intent upon capturing that city before Gaumata could
prepare for resistance. On the first day out he was met by the
messenger from Athura, which caused him to change his intention
and march into western Medea upon Nicæa.
Meanwhile the Princess Athura remained in the castle. The
messenger had been duly dispatched by Captain Gustasp, who
advised his fair captive to wait patiently several days for his return or
until he himself could communicate with certain relatives who might
consent to conceal her in the mountains should it become necessary
to leave the castle. Then one day a company of cavalry rode into the
castle-yard and its commander, Captain Galutha, displayed an order
giving him chief command. The next day a large body of cavalry
appeared on the plain below the castle and encamped, while several
of their leaders came up to the castle. Two of these, before whom all
others bowed to the earth, were Gaumata, the usurper, and his chief
counselor, Patatheites. The Princess Athura observed these men
with dread. She recognized them and knew that a crisis in her affairs
had come. Later came Captain Gustasp in much agitation.
“Gracious lady,” he said, “Gaumata has come! He desires audience
with you. If he attempt any harm to you, I will slay him! So fear not. I
am at your service. Shall I slay him at once?”
“No. Let him enter,” she answered, seating herself on a divan at the
side of the chamber opposite the window, where the light was good
and where every expression of her countenance might be seen. She
was calm and self-possessed.
The captain’s daughter stood at her side, trembling and
apprehensive.
A moment later the door opened and the chamberlain appeared,
announcing: “Our Lord, the King, the Great King, King of the World,
and his illustrious Counselor!”
Entered then Patatheites, with somewhat shuffling gait and
embarrassed demeanor, a tall man whose rich habiliments and
mitered head-dress indicated his priestly rank. He bowed very low
and touched the floor with his hands, saying: “All hail, most beautiful
Princess, Daughter of Cyrus, the Great King, Light of the World! Live
forever!”
Following him came Gaumata, a tall man, with uncertain, shifting
eyes, a pallid face, somewhat resembling the dead Bardya, a puppet
evidently in the hands of the real ruler, Patatheites. He was about to
prostrate himself before royalty, as was his habit, when,
remembering his high position, he checked himself and stood erect,
folding his arms in much embarrassment and agitation. On his head
was a vari-colored turban, around which was a golden coronet.
“I give you greeting. What would you?” responded Athura, coldly.
Patatheites coughed slightly and glanced at the King; then,
assuming a very ingratiating tone and manner, he said:
“The fates—I should say, the gods—have ordered that this man shall
be King. It matters not whether he be truly Bardya or not,—the spirit
of Bardya is in him. It has come to pass that King Cambyses by his
own hand is dead. You alone, royal lady, remain of his family. By
right of birth you should be Queen of the World. Unless you so rule,
the kingdom will pass to the King of Iran. It has been announced to
all the world that this Bardya has taken to himself all the wives of
Cambyses. That is true, and you yourself are included. We come,
therefore, to make a treaty. Consent to a marriage with this King,
Bardya, and rule equally with him. Your presence with him will
reconcile all Iran and the world will remain at peace. You cannot rule
alone. He offers to share the throne with you. Let him speak for
himself. I, his Chief Counselor, have spoken!”
Gaumata, thus prompted, bowed low before her and said in high,
squeaky tones: “Years ago my eyes beheld the most lovely vision of
all the earth. It was Athura, star of the morning, lovelier than the
moon, shining on a darkened world. My soul went out to her. I said
that I would one day sit on the throne of the world with her and her
slightest wish should be my law, her will my will, and that together we
would rule the universe wisely. Let it be so!”
Athura restrained her indignation with great difficulty. Should she
temporize, or at once declare herself? She remained silent a
moment. When she spoke, her steady voice betrayed not her deep
agitation.
“For this, then, I have been deceived and brought hither,” she said.
“It is a very grave matter. I require time to consider it. I know there is
but one other choice. That is—death! I must choose between you
and death, unless something intervenes. Such presumption as yours
in the days of Cyrus would have merited death. But truly has the
situation changed through the wisdom of God. How many days may I
have to consider this?”
The men glanced at each other doubtfully. Then the Counselor
spoke.
“Grave events call for quick action. However, if to-morrow at this time
will suit you to answer, let it be so.”
“I shall require at least a week.”
“No, no! You must decide by to-morrow.”
“Must?”
Her tone startled the men. In it were unutterable scorn and menace.
Gaumata shrank back. As she looked now, so had he seen Cyrus
and Cambyses, the terrible. But Patatheites was unafraid and,
knowing the necessity of quick action, he was determined that her
choice should be made at once.
“Forgive the expression,” he said. “We are desperate men. So stirred
up are the people that we must act quickly. You said truly that you
must choose either to consent or to meet death. Rule the world or
die! Do you hear? But you shall consent!” He gazed into her eyes
with his flashing black eyes fixedly and extended his long, slender
fingers towards her slowly. He trusted to his great hypnotic power to
overcome the powerful will that showed in her eyes. “On the morrow
at this hour you shall say yes!” he added after a pause.
Athura smiled derisively. Her eyes showed no less will-power than
his, and, extending her hand in a repellent gesture, she said: “I say
that I will speak freely without being coerced by your devil’s power!
Dog that you are! I shall live to see your carcass thrown to the
vultures!”
The battle of wills continued in silence for a tense moment. Then the
eyes of Patatheites wavered and dropped. His hand fell at his side.
His dusky face paled to a sickly yellow.
“Princess, again I ask forgiveness,” he said humbly. “Well I know that
the spirit of the great Cyrus, living again in you, cannot be
commanded! Let us reason together. Being a woman, you can never
reign alone on the throne of Iran, or of the world. All the males of
your family are dead. The kingdom will pass to the King of Iran. If his
son were living he would make you his wife, and thus, when his
father dies, you might become his Queen but not a joint ruler with
him. But the Prince of Iran is dead. He was slain in a battle near
Susa yesterday. It remains only for you to accept our proposition and
you will become joint ruler with this Bardya and reign over the whole
world.”
The Princess made no immediate answer, but gazed in silence on
the face of the speaker, striving to read whether he lied or not in
speaking of the Prince. The cold hand of fear clutched at her heart.
Dread seized her throat and almost stifled her. But there seemed to
whisper in her ear a voice like that of the loved Bardya of old, saying:
“Believe him not, little sister. The Prince yet lives and will surely
come to your aid.” She was startled and looked around involuntarily
searching for the speaker; but no one, save her maid, was near.
Arousing herself with a great effort, the Princess again controlled her
agitation and said: “You are stating a falsehood, magician! But, even
if the Prince were dead, it would not alter my determination. What? I,
a daughter of Cyrus, mate with that slave? Begone from my sight!”
The pallid face of Gaumata flushed in anger. Thrusting aside
Patatheites, he laid one hand on a short sword at his side. “Woman!”
he cried excitedly, “birth makes not a man, but achievement! I am a
noble of Medea, of ancient lineage and royal stock. Centuries ago
my forefathers ruled the Scythians, who were once lords of Medea. I
have dared to seize the throne of the world from your tyrant brother,
and I mean to hold it! I have offered you the right to share it. Choose!
On the morrow you accept or die! The world is not large enough to
permit you and me to live therein unless we join fortunes!”
The Princess was surprised. She had deemed this man a mere
puppet. He seemed to have some qualities of a strong man. She
spoke less bitterly as she answered: “You speak somewhat kingly,
Gaumata! But you are a living lie, ruling not by your own might! You
rule only by reason of Bardya’s name. Do not deceive yourself into
the belief that the Aryans would permit you to rule an hour, did they
know the truth! No! Rather it would be better for you to release me
and place in my hands the scepter and crown. I might so far pardon
you as to permit you life and property. Think of this, my offer until to-
morrow, and I will consider yours.”
“Until to-morrow then, farewell!” said Patatheites, bowing low and
backing quickly from the room. Gaumata followed without the
formality of a bow. Athura sat a long time in silence after they had
gone, wrapped in thought, while the daughter of Gustasp stood in
silence with folded hands and bowed head at her side.
The Princess turned to her maid at length and asked: “What think
you, child? The magicians were not able to bend my will, though
strong was the power of the priest’s evil eyes. I felt my brain reel and
I became dizzy for a moment.”
“I have never seen one able to resist him before,” answered the
maid. “Truly Ahura-Mazda has sent to your aid some powerful
angel!”
The hours of that day passed very slowly for the Princess. She spent
the greater part of her time in the upper chamber looking from the
window upon the valley below. She had little hope that any aid would
arrive. She was determined to escape from the castle at all hazards
as soon as night should come, and she sent word to Gustasp that he
must arrange for her escape.
About noon two horsemen were seen riding at headlong speed from
the direction of Nicæa. They came direct to the castle. They
evidently bore exciting news. For the King and his Chief Counselor
were observed in excited conference with them, and, shortly
afterwards, the King mounted a horse and rode down into the valley,
where his cavalry immediately marched away across the plain
towards Nicæa, and several horsemen rode away in divers
directions. Later the King returned to the castle accompanied by an
officer, whose elegantly attired form and easy carriage, as he passed
across the castle-yard, seemed familiar to Athura. She sent the maid
to call Gustasp, whose duties now consisted in standing guard at the
castle-door. The captain soon appeared.
“What means this excitement?” she inquired. “Who is the officer that
came up with the King?”
Gustasp shrugged his giant shoulders. “The officer is Prexaspes,” he
answered. “He was chief man of the empire under King Cambyses.
He is in command of the Medean army which is assembling down
there in the valley. I do not know just what news the messengers
brought; but it is rumored that they reported a strong force of Persian
cavalry moving up towards Nicæa over the hill-roads from Susa. If
that be true, a battle may occur if the Medes dare to stand against
them. There are but a few veterans here and they may not risk a
battle. The Persian cavalry is terrible, especially if led by the Prince.”
Athura started up with joy, exclaiming, “By the Prince, did you say?”
“The Prince of Iran, yes,” he assented. “No one knows, but I will bet
my shield that he leads the Persians!”
“Ahura-Mazda grant that it be true! What of you if there be a battle,
Gustasp? Ought I to wait till the morrow? Or should I escape this
night and trust myself to the mountains?”
“I have requested the honor of personally guarding you so that you
may not escape,” he responded. “The King has granted my request.
I do not know how to advise. The new men who came in with
Captain Galutha are on guard. There is to be an enchantment, a
sacrifice, and soma-drinking to-night. Ahura-Mazda grant that no
spell be cast on us! Let me advise that you stay in this upper
chamber with all your maids. I shall stand here at the foot of the
stairs. We may need a barricade. That divan and the benches may
do. When darkness comes, I will bring up javelins and spears. I do
not know how to get out of the castle with you unseen.”
“What do you fear?”
“Madmen, drunken with soma! You and the maids are the only
women in the castle. Even the King himself will be drunken and
furious.”
“Bring up the arms, Gustasp! You will find in me no weeping, fainting
child. We will fight this battle together!”
“Then on the morrow we may need to defend this place until the
battle be decided down there in the valley.” And he added fervently,
“It will be a joy to fight for you, O Queen of the Earth, and even to die
for you!”
Gustasp began immediate preparations for defense and secretly
brought up a bundle of keen javelins, several heavy spears, and a
huge bronze battle-ax, which they concealed behind curtains and
furniture. He also brought a supply of bread and fruit.
From her window Athura saw that preparations were being made in
the courtyard for the sacrifice spoken of by Gustasp. First, a square
altar of stones was erected. Around this, at a distance of twenty feet,
a circle of flat stones was placed. A priest clothed in long robes then
drew geometrical figures with a sword-point on the ground within the
circle. Other priests brought out twenty tall jars of soma and placed
them at intervals touching the circle. Still others brought wood and
piled it in four heaps at the corners of a square inclosing the circle.
Many soldiers of the garrison gathered around, uneasily and fearfully
watching the preparations, but they were not allowed to come within
twenty paces of the circle.
The preparations were completed when the sun was yet half an hour
high. Then the rumble and boom of drums and the shrill scream of
trumpets announced the beginning of the services. A procession of
priests, twenty in number, headed by Patatheites and followed by
Gaumata, who led a beautiful white stallion, appeared from the
northern portion of the castle-yard. Seven times they silently
marched around on the outer side of the circle of stones. Then they
halted and a priest took station at each of the jars of soma. Every
one held a large, keen knife in one hand and a goblet in the other.
The chief priest, Patatheites, took station at the right of the altar and
raised his hand toward the setting sun in prayer. All the others
imitated his action. Their invocation was silent and lasted a full
minute. Then Patatheites placed a bundle of fagots on the altar and
again raised his hands to the sun, and his lips moved in recital of an
invocation. Instantly a spiral of smoke ascended from the fagots and
a flame burst forth. The soldiers, stricken with awe, fell on their
knees at sight of this miracle. The sun-god had answered, unless the
dexterous priest, having a knowledge of phosphorus and sulphur,
had ignited the wood as he placed it on the altar.
Gaumata now led the white stallion into the charmed circle near to
the high priest. The beautiful animal trembled and sniffed at the altar
and the blazing wood, then raised his noble head and whinnied. As
he did so, the chief priest, with a powerful slash of his sharp knife,
cut the animal’s throat so deeply across as almost to sever the head.
At the same moment, Gaumata drove his knife deep into the horse’s
chest through his proud heart. With a convulsive backward
movement, the noble beast sought to break away, but Gaumata
clung to it and its knees gave away suddenly and it fell. The chief
priest took a stone vessel and caught the blood spouting from the
severed throat. When the vessel was filled, he presented it to
Gaumata, who lifted it on high before the fire and towards the setting
sun, then poured some of the blood on the altar and some on the
earth while he muttered a prayer. The chief priest then took a bundle
of rods, known as the baresma, and, dipping it in the blood, sprinkled
the King and the twenty priests, chanting a hymn as he slowly
performed his labor. Then four of the priests attacked the carcass of
the horse with their knives and rapidly dismembered it. A portion of
flesh from the chest was taken by the King and placed on the
burning wood of the altar. The savor of it went up to heaven just as
the rim of the sun disappeared behind the western hills, while the
priests broke forth into a barbaric chant in praise of Mithra. The limbs
and body of the animal were then cut in bits and distributed by the
priests to the soldiers. The piles of wood were set on fire by coals
from the altar, and the men roasted the horseflesh at these and ate
of it. Thus far the ceremony had been conducted with some
decorum.
Then the bloody-handed priests dipped goblets into the jars and
brought them forth filled to the brim with a white, acid liquor, the
sacred juice of the soma plant. First, the chief priest drank a huge
goblet of the liquor. The King followed suit. Then the priests drank,
and as they drank they began a serpentine march, following the lines
of the geometrical figures drawn in the circle, weaving in and out and
crossing back and forth, chanting in time to their movements. The
chief priest led the weird dance. The King followed at the rear. Ever
and anon, as their movements brought them near the jars, the
priests replenished their goblets. Gradually their chant became
louder and wilder, and was addressed to the gods of the sun, of the
moon, of the stars, of the earth, and of the seas, entreating them to
be present and to give counsel and wisdom to the King.
Darkness fell upon the earth, but the fires partially dispelled the
gloom in the courtyard. The crowd of soldiers drew well back from
the enchanted circle, dreading they knew not what, and fearing the
unknown powers of earth and sky. Suddenly one of the priests
ceased marching and, with a scream, rent the clothes from his body.
Stark naked he began to dance furiously, leaping in the air, frothing
at the mouth, and uttering wild words of prophecy. Another imitated
him and still another, until a score of naked, leaping, shouting
madmen, brandishing knives and soma-pots, encircled the chief
priest, who, having drunk but little of the powerful liquor, had
remained comparatively sober, and who now took his station with
folded arms and bowed head before the altar, listening intently to the
ravings of his helpers. The King took his place on the opposite side
of the altar and sought to preserve a semblance of dignity, but he
swayed to and fro under the influence of the liquor or of excitement
while he also listened to the ravings of the prophets.
The Princess and her maids were curious observers of the
ceremonies, but their curiosity turned to horror as the last act of the
drunken priests began. Nevertheless, they watched and listened.
One of the priests, bellowing for silence, stood before the chief priest
and shouted: “I am Melchior of the Hills! Say to this King, he lacks
courage! Say to him that instead of entreating the proud woman in
yonder castle, he should take her by force, lest there come an eagle
out of the south and carry her away! Let him now act! Now! Now!
Now!”
Another shouted: “I am sent from Mithra to say, The day comes
when the Kings of the earth shall meet in death struggle! To him of
stout heart and quick mind will the victory be! Up and act!”
Others took up the burden of prophecy and warning. The chief priest
listened attentively; then, calling the King aside, he spoke rapidly and
earnestly to him, pointing up to the window from which the Princess
was looking down upon them. For a time the King hesitated, then
walked uncertainly towards the castle, followed by the howling mob
of priests, who stumbled, rolled, or hopped after him. A moment later
they were hammering at the castle-door and the King was
commanding Gustasp to open.
Gustasp, however, had not been idle. He had locked and barred the
stout doors and had reinforced them with furniture piled against
them. Now, as the King’s voice was heard commanding him to open,
he shouted back a refusal.
“Open, I command it!” shouted the King.
“I will never open it!” answered Gustasp. “No longer do I serve you,
Gaumata, the false! I serve the gracious Princess of the house of
Cyrus!”
“You will be torn in pieces! Open, I say! I will have you roasted to
death! I will afflict you with spells! Open! I command!”
“Never! I warn you that I will slay any man who attempts to harm my
sovereign lady!”
The King and Patatheites took counsel and sought to beguile the
giant guard.
“Listen!” said the priest. “We mean no harm to the Princess. But she
must marry the King now and must march with us at daybreak to
Hamadan and proclaim their union. Open, and I swear she will not
be harmed, and you shall be the first officer of the army!”
But Gustasp growled a refusal. He was not to be deluded. Then
began Patatheites to curse him and to call down the anger of all the
gods upon him. He cursed him by the sun whose beams would strike
him down; by the moon whose rays would drive him insane; by the
rivers which would drown him; by the hills which would fall on him;
and by the devils who would ever pursue him. So bitter and dreadful
were his words that stout Gustasp paled and trembled. With
uncertain steps he paced back and forth across the lower chamber
floor, fearing that from the shadows of the chamber half-lighted by an
oil lamp some specter might leap forth upon him. A soft step came
down the stairs and Gustasp drew his sword. But it was the
Princess. She came to the trembling giant and placed her hand on
his arm.
“Fear not, Gustasp!” she said reassuringly. “Good spirits are here
around us! Those curses shall not harm you. Ahura-Mazda has sent
me a messenger saying: ‘Fear not! We will help you!’ Be strong and
brave, Gustasp. See, I tremble not.”
The giant guard heaved up his broad shoulders, and a cheerful smile
passed across his rugged features.
“Have no fear that I will falter, most gracious lady,” he said. “Let them
curse. If they come within reach of my spear, their curses will stop
short!”
At length the cursing ceased. The King and the chief priest withdrew
a space to consult. Presently they ordered a company of soldiers
with a beam for a battering-ram to break down the door. The stout
planks and bars soon quivered beneath heavy blows. Gustasp,
seeing that it would presently fall, retreated up the narrow stairway to
the upper chamber and proceeded to barricade it with furniture. A
heavy divan was pressed into the narrow stair, leaving barely space
at one side through which a spear might be thrust. Tables and
benches were piled upon this. Then Gustasp, spear in hand, stood
ready. The door below presently gave way and a squad of soldiers
rushed into the room below. Finding it empty, they immediately
began to ascend the stair; but, the moment one appeared in the
narrow passage, the long blade of Gustasp’s spear flashed down
upon him and he tumbled back gasping, with a terrible wound in his
chest. A second tried the ascent and had his face slashed open. This
cooled the ardor of the assailants. They drew back to take counsel.
No one dared further attempt the deadly stair.
Then Athura heard a voice, cold, calm, and ironical, saying: “It
seems to me far beneath the dignity of a King of the World to be
leading a drunken mob in attack upon a woman! I say to you now
that I for one do not approve!”
“Have a care, Prexaspes!” replied the voice of Patatheites. “Such
words to the King are not to be spoken lightly!”
“Bah!” was the rejoinder in a loud voice that was heard by every man
in the fortress. “Who are you to threaten me? Do you desire to break
with me? If so, I will lead my Medes over to the Prince. I say to you,
stop this rioting and give your thoughts to the enemy! If I be not
greatly mistaken, we shall have the Persians upon us before noon
to-morrow. I will venture all I have that the Prince is commander of
that company approaching Nicæa! If so, his coming will be like a
whirlwind. I am going down to the camp, and I demand that the King
go with me. I demand that no further violence be attempted against
the Princess Athura. I warn you that if we injure her and lose this
battle, the Prince of Iran will flay and quarter every man in this
fortress!”
His words greatly impressed all hearers and, after further angry
altercation, Prexaspes triumphed and the drunken priests were
ordered to return to their cells while Gaumata sulkily mounted a
horse and rode with him down to the camp.
Athura praised Gustasp and presented to him a gold ring, which in
after years the guard and his descendants treasured above all other
possessions.
CHAPTER XX
THE OVERTHROW OF THE MAGI

ATHURA slept little during the remainder of the night. She insisted
on watching a part of the time, while Gustasp slept stretched out on
the floor and the maids tried to rest. She watched while the stars
paled and the gray light of the dawn grew into rosy sunrise and
cloudless day. Her eyes eagerly scanned the horizon towards
Nicæa. As soon as the light was sufficient, she saw moving bodies of
horsemen concentrating in the plain near the base of the hill on
which the castle stood. She had often seen large bodies of troops,
and she estimated that not less than thirty thousand were there.
Officers were busily riding hither and thither placing them in line with
their faces towards Nicæa.
When Gustasp awoke and observed the movements of the troopers,
he gave it as his opinion that an attack was expected. Nor was he
mistaken. For about mid-forenoon they observed two bodies of
cavalry approaching from the direction of Nicæa, one in advance
moving rapidly and the other more deliberately. The advance body
was evidently a scouting party sent out by Prexaspes, and it soon
joined his array. The pursuers came on in wide, extended order, their
masses glittering with armor and spear-points. At their head rode two
men, conspicuous on white steeds.
“Look, Gustasp!” exclaimed Athura, while the pursuers were yet far
away. “Is it not the Prince—the one at the right? Is that not Gobryas
at his left?”
Gustasp shaded his eyes and looked closely at the distant figures.
He smiled and shook his head.
“My eyes are counted good, gracious lady, but I cannot see any
difference in those men,” he answered. “If I had eyes as young as
yours, I might distinguish them. But I know those are the Persians of
the Imperial Guard. The Prince must be with them. They are not half
as numerous as the false King’s men, but they are veterans and the
best soldiers in the world. It will be a short battle.”
The Persians came on until they were within a thousand paces of
their antagonists, when they halted. The two leaders rode forward to
a slight eminence two hundred paces in advance, from which they
attentively surveyed the field. It was well suited for battle between
bodies of cavalry. While somewhat rolling and uneven, there were no
ditches or swamps. The Medean line was more extended than the
Persian and no less massive and deep. The Persian leaders soon
returned to their lines and the watchers on the hills perceived a
movement of the rear ranks to the left, where presently a body of
troops was massed three times as great in depth as the general line.
“The Prince has made a hammer of his left,” said Gustasp. “Now
look at his right! It bends back so that the Medes may not overlap
and attack the Persian rear!”
It was even so. For when the Persians moved forward again there
was a perceptible bending back of their right wing until it moved
forward en echelon to the remainder of the line.
Then came two men from the Persians who rode rapidly up to the
Medes and demanded a parley. Prexaspes and the King met them
and received a message from the Prince of Iran demanding the
surrender of the Princess Athura and of the false King, and
promising pardon to all the other Medes save Prexaspes. These
demands were refused. The heralds rode back to the Prince and
reported, who then ordered his army to advance.
The Persians came on at a smart trot until within five hundred yards.
Then the front ranks leveled their spears, bent their bodies forward,
and pressed their horses into a gallop. Prexaspes ordered his troops
forward to meet the onset. The earth shook with the thunder of
hoofs. A deep-toned roar went up from the Persians, their battle
shout which had terrified many a nation. The Medes answered with a
medley of yells. The lines came together with a terrific shock. Men
were unhorsed. Horses reared, plunged, and went down. Screams of
agony mingled with battle-shouts. The lines wavered and stood still,
it seemed, for the space of five minutes. Then was seen the power of
discipline. The Medes, while brave, were not inured to battle. After
the first shock, they became confused. They were overthrown,
ridden down, and pushed back. Struggling fruitlessly against the
terrible spears of their enemies, they receded. The Persians raised
shouts of victory and pressed their advantage. The Prince of Iran,
leading the center, rode over Prexaspes, broke through the Medean
lines, and made directly for the King. The latter turned his horse and
fled towards his castle, with the Prince and Gobryas close at his
heels. So close was the pursuit that Gaumata and his men had no
time to close the brazen gates of the castle, which were opened to
receive them, before the Prince and Gobryas with a company of
Persians pressed through and attacked the garrison fiercely.
Demoralized by the fall of Prexaspes and the flight of Gaumata, the
Medean army scattered and fled from the field.
The Prince and Gobryas, swords in hand, pressed through the
confused rabble after Gaumata. They saw him leap from his horse
and enter the castle. Dismounting they pursued him into the
chamber below that where the Princess Athura had her retreat. Here
the false King turned at bay, unable to escape. The Prince himself
attacked Gaumata, though Gobryas begged the privilege of slaying
him. The struggle was short. The Prince was an athlete and
swordsman; his opponent was neither. Gaumata’s weapon was
whirled from his hand at the first blow, and the Prince’s blade passed
through his heart, cutting short his cry for mercy.
Athura, trembling with excitement, had seen the battle and the flight
and pursuit of Gaumata, and, from behind Gustasp’s broad
shoulders on the stairs, had watched the short, sharp combat
between the Prince and the usurper. The Prince, flushed with victory
as he stood above the writhing form of Gaumata, heard her exclaim,
“Ahura-Mazda be praised!” He turned and their eyes met. He sprang
towards Gustasp with dripping sword, thinking the giant guard an
enemy in charge of the royal captive. But Athura pressed forward in
front of Gustasp, exclaiming, “He is a friend!”
The Prince dropped his sword and extended his arms, with the light
of great love in his eyes. Athura threw her arms about his mail-
covered shoulders. Gustasp and Gobryas drove back the crowd of
Persian troopers who were pressing in to aid their Prince.
But a chief commander must make an end of greetings, no matter
how entrancing. The Prince and Athura passed out into the
courtyard, now filled with shouting Persians, some of whom were
pursuing the luckless garrison and cutting them down. When the
Persians saw the radiant Athura standing by the side of their Prince,
their shouts rent the heavens. For every man who had taken part in
the battle knew that their leader was seeking to rescue his promised
wife, the daughter of the great Cyrus.
Prexaspes was among the prisoners. His horse had been killed and
had fallen upon him. The Persian cavalry had passed over him. But
save for a broken arm, he was not seriously injured. He was brought
before the Prince. His countenance showed signs of suffering, but
the usual calm, cynical smile rested upon it and he exhibited no fear.
The Prince looked upon him sternly.
“At last, Prexaspes,” he said, “you have come to a day of judgment!
What have you to say?”
“Nothing, great Prince,” he answered. “Fate has turned against me. I
am in your hands, a prisoner of war.”
“But how could you, a noble of Medea, conspire with that carrion,
Gaumata? And you even obeyed him as King!”
“I did not conspire. I was faithful to Cambyses till he died—even
though he did slay my son, as you know, in cruel jest. I did not
conspire against him. What could I do after his death? By the
command of Cambyses, I had slain Prince Bardya. For that crime I
knew that I would be slain by you. So I came and offered my sword
to the false King. He obeyed me, not I him!”
The Prince contemplated his prisoner gloomily. No man ever more
admired courage than he. Prexaspes smiled in the face of death.
What punishment should be meted out to such a man?
“For taking Bardya’s life, you have merited death,” said the Prince,
finally. “But you are a brave man. You shall die as such. Tell me,
Prexaspes, how did Bardya die?”
“I expect to die,” answered Prexaspes, and the pain and despair of
his soul snatched away the smile from his face, leaving his
handsome features haggard and drawn. “Remorse has been with
me, since by this hand the stout young Prince departed! I will tell
you. Cambyses was jealous of Bardya. His advisers, the Magian
priests, who by their wonder works had made much impression on
the King’s mind, also hated Bardya because he clung to the ancient
religion of Iran and was an enemy to their religion. They knew that
with Bardya as King they would never gain power in the state. They
hinted to the King that Bardya contemplated rebellion. They artfully
brought stories of the young man’s popularity. They advised his
death. It was then that the King laid his command upon me to slay
his brother. The Magian priests sent a body of their armed followers
to lie in wait on the road to Rhages that night when the feast in honor
of the Prince’s departure was held; and I rode with Bardya that night
until, as prearranged, they attacked us. Then, in the mêlée, I struck
the Prince with my sword and he died. Was not the Great King’s
word law? I executed his word, without malice towards the Prince.
But I am weary of life! My wife is dead. Cambyses slew my son. I
have run the full course of power and wealth. I am your prisoner,
ready to die. But know this, great Prince, I have never advised
Cambyses against your interests!”
The Prince listened attentively and believed that Prexaspes spoke
truthfully. He turned to Athura, who had listened to the recital, and
asked, “What do you advise?”
Athura shook her head sadly.
“I cannot advise,” she said. “Last night when the drunken priests and
the false King attempted to break into the castle and do me harm,
this man interfered and compelled them to cease.”
“For that, Prexaspes, I would pardon you, had I the power,” said the
Prince, turning to the prisoner. “I could order you slain now, but I
cannot slay you. Prexaspes, you have deserved my gratitude. I grant
you life for the present. I am not the King. My father is King of Iran.
There is no King of Kings; until the nobles of Bactra, Persia, and
Medea shall select one of the Achæmenian line. You shall go to
Hamadan to be judged.”
“Rather would I be slain by you now,” responded Prexaspes,
earnestly. “Let me die a soldier’s death, not the death of a dog
condemned for murder!”
The Prince was troubled. He hesitated. Sympathy for a brave man
moved him.
“I promise you this, Prexaspes,” he said after a moment of
consideration. “If you will testify before the council of nobles and to
the people, that this Gaumata was a false traitor and not Bardya and
that Bardya was slain by your hand, I promise that you may choose
the manner of your death. The King and the nobles will heed my
promise. They will not deny me. If you make this confession and
implicate the Magian priest, they will pursue you with bitter
vengeance. It is said that their death penalties are tortures such as
even fiends would not inflict. We could not save you from them. It is
the ancient law that one who lifts his hand against one of the
Achæmenian race must die. Is it not so? And this law, not even the
King may set aside.”
“It is so!” answered Prexaspes. “I will testify before the people and
the council, in order that your reign as King of Kings may not be
disturbed by other false Bardyas. I advise that you carry this
Gaumata’s head to Hamadan and exhibit it in the market that all may
see. I myself will ascend the criers’ tower and confess the death of
Bardya to the people. So be it. I will choose my own death.”
“Meanwhile,” said the Prince, “Gobryas shall be your keeper. He will
treat you as a brave soldier should treat a brave soldier unlucky
enough to be a captive. We shall rest here this night. On the morrow
we march to Hamadan.”
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookfinal.com

You might also like