Programming Visual Basic 2008 Tim Patrick download https://ebookbell.com/product/programming-visual-basic-2008-tim- patrick-4106516 Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be interested in. You can click the link to download. Programming In Visual Basic 2008 7th Edition 7th Julia Case Bradley https://ebookbell.com/product/programming-in-visual-basic-2008-7th- edition-7th-julia-case-bradley-2417356 Advanced Programming Using Visual Basic 2008 4th Edition Julia Case Bradley https://ebookbell.com/product/advanced-programming-using-visual- basic-2008-4th-edition-julia-case-bradley-1995366 An Introduction To Programming Using Visual Basic 2008 With Visual Studio Expression Edition Dvd 7th Ed Schneider https://ebookbell.com/product/an-introduction-to-programming-using- visual-basic-2008-with-visual-studio-expression-edition-dvd-7th-ed- schneider-22041544 Microsoft Visual Basic 2008 Express Programming For The Absolute Beginner 1st Edition Ford https://ebookbell.com/product/microsoft-visual-basic-2008-express- programming-for-the-absolute-beginner-1st-edition-ford-55132374
Visual Basic 2008 Programming Black Book Platinum Ed Kogent Solutions Inc https://ebookbell.com/product/visual-basic-2008-programming-black- book-platinum-ed-kogent-solutions-inc-231815772 Practical Database Programming With Visual Basicnet Ying Bai https://ebookbell.com/product/practical-database-programming-with- visual-basicnet-ying-bai-4105898 Practical Database Programming With Visual Basicnet 1st Edition Ying Bai https://ebookbell.com/product/practical-database-programming-with- visual-basicnet-1st-edition-ying-bai-1367072 Programming Microsoft Sql Server 2000 With Microsoft Visual Basic Net 1st Edition Dobson https://ebookbell.com/product/programming-microsoft-sql- server-2000-with-microsoft-visual-basic-net-1st-edition- dobson-55141988 Programming Visual Basic Net 1st Edition Dave Grundgeiger https://ebookbell.com/product/programming-visual-basic-net-1st- edition-dave-grundgeiger-43041026
Programming Visual Basic 2008 Tim Patrick Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo
Programming Visual Basic 2008 by Tim Patrick Copyright © 2008 Tim Patrick. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com. Editor: John Osborn Production Editor: Rachel Monaghan Copyeditor: Audrey Doyle Proofreader: Rachel Monaghan Indexer: Ellen Troutman Zaig Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Robert Romano Printing History: May 2008: First Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Programming Visual Basic 2008, the image of a bufflehead duck, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. This book uses RepKover™ , a durable and flexible lay-flat binding. ISBN: 978-0-596-51843-1 [M]
vii Table of Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv 1. Introducing .NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Before .NET 1 Back to Introducing .NET 2 The .NET Object 3 The Parts of the .NET Framework 7 From Source Code to EXE 16 What About Visual Studio and Visual Basic? 17 Visual Studio 2008 18 Summary 22 Project 23 2. Introducing Visual Basic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 The History of the Visual Basic Revolution 30 Visual Basic from the Inside Out 32 The Basics of Logic and Data 32 Data Types and Variables 35 Intermission 44 Comments 44 Option Statements 45 Basic Operators 47 Using Functions and Subroutines 49 Conditions 50 Loops 54 Creating Your Own Procedures 57 Other Flow Control Features 61
viii | Table of Contents Events and Event Handlers 64 Namespaces 66 The My Namespace 69 Summary 70 Project 70 3. Introducing the Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 The Library Project 76 The Needs of the Users 79 The Life of a Project 83 Summary 90 Project 90 4. Designing the Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 Relational Databases 95 SQL Server 2005 98 SQL 100 Using Databases in Visual Basic 107 Documenting the Database 108 Summary 109 Project 109 5. .NET Assemblies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 What Is an Assembly? 126 What’s Inside an Assembly? 128 Assemblies and Applications 131 The My Namespace and Assemblies 132 Directives and Assemblies 134 Summary 136 Project 137 6. Data and Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 The Nature of Computer Data 151 Data in .NET 153 Visual Basic Data Types 158 Literals 159 Constants 160
Table of Contents | ix Enumerations 161 Variables 162 Variable and Constant Naming Conventions 165 Local Type Inference 166 Operators 167 Static Variables 172 Arrays 172 Nullable Types 175 Common Visual Basic Functions 176 Summary 181 Project 182 7. Windows Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 Inside a Windows Application 187 Windows in .NET 191 Making Forms Useful 210 Summary 212 Project 212 8. Classes and Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 Object-Oriented Programming Concepts 219 OOP in Visual Basic and .NET 224 Related Issues 241 Summary 244 Project 244 9. Functional Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 Lambda Expressions 253 Object Initializers 259 Error Handling in Visual Basic 260 The Nature of Errors in Visual Basic 260 Unstructured Error Handling 263 Structured Error Handling 265 Unhandled Errors 267 Managing Errors 269 Summary 273 Project 274
x | Table of Contents 10. ADO.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 What Is ADO.NET? 278 Overview of ADO.NET 279 Data Sets Versus No Data Sets 282 Connecting to SQL Server with Visual Studio 284 Interacting with SQL Server in Code 289 Database Transactions 292 ADO.NET Entity Framework 293 Summary 294 Project 294 11. Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 Security Features in .NET 304 Cryptography and Encryption 304 Encryption in .NET 306 Other Security Features 311 Summary 312 Project 312 12. Overloads and Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 What Is Operator Overloading? 330 What Can You Overload? 332 Other Operator Overloading Issues 338 Extension Methods 340 Summary 342 Project 342 13. XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361 What Is XML? 361 The XML Rule 364 XML Content 365 Using XML in .NET: The Old Way 371 Using XML in .NET: The New Way 375 Summary 378 Project 379
Table of Contents | xi 14. Application Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392 A Short History of Settings 392 Settings in Visual Basic 2008 394 Summary 400 Project 401 15. Files and Directories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416 Traditional Visual Basic File Management 417 Manipulating Files Through Streams 418 File Management with the My Namespace 424 Summary 427 Project 428 16. Generics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433 What Are Generics? 433 Variations of Generic Declaration 436 Summary 442 Project 442 17. LINQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448 What Is LINQ? 448 Anonymous Types 450 LINQ to Objects 451 Basic Query Expressions 453 Converting Results to Other Forms 459 Aggregate Queries 459 Advanced Query Expressions 460 LINQ to XML 461 LINQ for ADO.NET-Related Data 463 Deferred Execution 468 Summary 469 Project 470 18. User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486 Overview of GDI+ 487 Selecting a Canvas 488 Choosing Pens and Brushes 490
xii | Table of Contents Flowing Text from the Font 493 Imagining Images 497 Exposing Your True Artist 499 Paths: Drawings on Macro-Vision 501 Keeping It Regional 502 Twisting and Turning with Transformations 503 Enhancing Controls Through Owner Draw 505 Windows Presentation Foundation 507 Enhancing Classes with Attributes 510 Summary 511 Project 511 19. Localization and Globalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526 Defining Globalization and Localization 526 Resource Files 527 The My.Resources Object 529 Localizing Forms Within Visual Studio 531 Adding Resources Outside Visual Studio 534 Manually Compiling Resources 535 Other Localization Features 537 Summary 538 Project 539 20. Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552 Printing in Windows 553 Printing in .NET 554 Printing a Document 557 Print Preview 559 Counting and Numbering Pages 561 Printing in “Raw” Mode 563 Summary 564 Project 564 21. Reporting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581 Report Options in .NET 581 Using Reporting Controls in .NET 584 Summary 597 Project 597
Table of Contents | xiii 22. Licensing Your Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611 Software Licensing Options 611 License Agreements 615 Obfuscation 616 The Library Licensing System 618 Summary 621 Project 622 23. Web Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642 How the Internet Works 642 Programming the Internet 644 ASP.NET Features 645 Trying Out ASP.NET 646 More About Events 653 State and View State 654 Data Validation 655 Database Integration 657 Windows Communication Foundation 658 Summary 663 Project 663 24. Adding Online Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 672 Windows Online Help Options 672 Designing HTML Help 674 Accessing HTML Help 680 Summary 683 Project 683 25. Deployment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689 What’s Involved in Deployment? 689 Deployment Methods Within Visual Studio 690 Summary 700 Project 700 26. Project Complete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 711 The Library Project 711 Visual Basic Flexibility 714 The Programming Mindset 716 Summary 717
xiv | Table of Contents A. Installing the Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 719 B. Software License Agreement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 722 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 725
xv Preface1 Welcome to Programming Visual Basic 2008! I know you’re going to enjoy it; I’ve read it five times already. You’re probably anxious to get to Chapter 1, but I recom- mend you read this preface to make sure you paid for the right book. Who Is Reading This Book? Writing a book is a lot like writing a Visual Basic application. Well, except for the part about finding a publisher, and working with an editor. And then there’s that pesky rule about correct spelling. Come to think of it, they’re really quite different. But in one way, books and programs are similar: both are written to meet the needs of the user. When writing software applications, the user’s needs drive the organiza- tion and features of the final program. When writing a book, like the one you’re looking at now, the needs of the user—that’s you, the reader—drive the organiza- tion and features of the final text. So it was with you in mind that I set out to write this book. Oh, there’s the fame and the prestige, but it’s really about you. You, the person who seeks to understand Visual Basic and the .NET Framework on which it is built. When I thought about you and your needs, I came up with these ideas: You might know how to program, but maybe not In the programming world, there are four types of people: (1) those who already program joyfully; (2) those who don’t program, but will learn it and love it; (3) those who don’t program, but will learn it and struggle with it; and (4) those who should return this book immediately to the bookstore. If you are in one of the first three groups, this book is definitely for you. I believe that anyone who can break down a task into its basic step-by-step instructions can successfully program in Visual Basic. If you are unsure about your ability to quantify tasks in this way, you might want to start out with a book on basic programming concepts.
xvi | Preface You might know how to program in Visual Basic or .NET, but maybe not And that’s OK, because this book will teach you. Most of the chapters introduce important topics in Visual Basic and .NET development, such as object-oriented programming concepts, or using the different types of variables available to you, or interacting with a database. If you already know how to use Visual Basic 6 or earlier, that’s great, but it’s not a prerequisite. You want to write programs Most programming books teach you to write code in 10-line increments. At least that’s what’s scattered throughout their pages. I’ve put some of those “code snippets” in this book. But I spend my days writing real programs, not 10-line sample programs. If you want to write whole programs, you should learn using whole programs. That’s why I also put a program in my book—a whole pro- gram. Over the next several hundred pages, I will develop a real program—a database for a small library—and you will write it with me. I put all of these ideas into 26 easy-to-read chapters, and had O’Reilly Media glue the pages together for your convenience. When you reach the index, you will have learned how to write complete programs in Visual Basic and .NET. It will be a pro- gramming adventure, so let’s get started! What’s in This Book? Since we are going to be spending a lot of time together, you probably want to know something about me. Well, my name is Tim Patrick, and for many years I lived just up the street from the big Microsoft campus. I’ve been writing programs for 25 years, and these days I write custom database-oriented Visual Basic applications for small to medium-size businesses. And I’m not alone. Most Visual Basic developers write business-level software. If that’s what you do, or plan to do, you’re in great company. As you move through the pages of this book, you will read about the major .NET and Visual Basic activities that drive the development of business-level and general con- sumer applications. If you plan to do some other type of programming, such as game development, this book will be somewhat helpful, but I don’t talk about advanced or specialized features such as interactive 3D models or geometric transformations. Each chapter discusses a major programming topic, and then follows it up with a practical implementation of that topic: the creation of the Library database program. I don’t show every line of code in the book; if I did, the book would weigh 53 pounds and cost $254.38, plus tax. To get every line of source code, you’ll have to download the accompanying source code from the book’s web site. The code and the book’s text are united in one purpose: to train you in the skilled use of Visual Basic on the .NET platform so that you can develop the highest-quality applications possible. The text and the source code both include valuable resources that you can use every day in your programming life.
Preface | xvii What’s in the Software Download? You’re going to like the download. It contains all the source code for the Library database project. What’s cool is that when you install the source code examples, they become part of Visual Studio. Once they are installed, you can create a new chapter-specific project right from the File ➝ New Project menu in Visual Studio. Appendix A has all of the download and installation details. I wrote the project code using Visual Basic 2008 Professional Edition. Some portions may not be compatible with earlier .NET versions of the language. None of it is com- patible with Visual Basic 6.0 or earlier, so don’t even bother trying. The source code will work with any edition of Visual Basic 2008, including the Express Edition. The source code also uses SQL Server 2005 for its database storage. You can use any edition of SQL Server 2005, including the Express Edition. Chapter 4 intro- duces databases and SQL Server 2005. If you will be using the database in an IT department-controlled network environment, you may need to talk with your IT department representative about installing the sample database. The SQL code I use is pretty vanilla, so it should work on previous versions of SQL Server, and you could easily adjust it to work with Oracle, DB2, Microsoft Access, or other common data- base engines. You can also use the upcoming SQL Server 2008 if you have it available. You can use the downloadable source code for your own projects, but please give credit where credit is due. There is a license agreement associated with the code (see Appendix B), so please don’t go selling the software as your own work. Just to be on the safe side, I’ve added a few hard-to-find bugs. Just kidding! (No, I’m not!) Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, filenames, and file extensions. Constant width Indicates computer coding in a broad sense. This includes all Visual Basic source code, HTML content, XML content, commands, options, source code from other languages, and content generated by Visual Studio tools. Constant width bold Indicates commands or other text that the user should type literally. Also used to highlight a particular section of code. Constant width italics Indicates text that should be replaced with user-supplied values or values deter- mined by context.
xviii | Preface This icon signifies a tip, suggestion, or general note. This icon indicates a warning or caution. Using Code Examples This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact the publisher or me for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting exam- ple code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation requires that you abide by the terms of the software license agreement found in Appendix B. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Programming Visual Basic 2008, by Tim Patrick. Copyright 2008 Tim Patrick, 978-0-596-51843-1.” If you feel your use of code examples falls outside fair use or the permission given here, feel free to contact us as permissions@oreilly.com. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any addi- tional information. You can access this page at: http://www.oreilly.com/catalog/9780596518431 To comment or ask technical questions about this book, send email to: bookquestions@oreilly.com
Preface | xix For more information about our books, conferences, Resource Centers, and the O’Reilly Network, see our web site at: http://www.oreilly.com/ Safari® Books Online When you see a Safari® Books Online icon on the cover of your favorite technology book, that means the book is available online through the O’Reilly Network Safari Bookshelf. Safari offers a solution that’s better than e-books. It’s a virtual library that lets you easily search thousands of top tech books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current informa- tion. Try it for free at http://safari.oreilly.com. Acknowledgments The development of Programming Visual Basic 2008 has been a labor of love for me, and I am blessed to have had so many others go through the labor with me. Joan Murray from Addison-Wesley was my editor on the first edition of the book. John Osborn at O’Reilly Media took up the task of guiding the second edition. I have been fortunate to have worked with John on three different book projects, and their suc- cess was possible thanks to his gallant efforts. Several other authors and programmers took time out of their day jobs to review each chapter of the book and point out its deficiencies, which were numerous before their arrival. I especially wish to thank Glenn Berry, Alex Bierhaus, Harry Chen, Ken Getz, Lowell Mauer, and Dan Sullivan for their superb comments. When it came time to focus on Visual Basic’s 2008 release, I also received fantastic input from Chris Williams, Daniel Seara, Ron Petrusha, and Sander Gerz. Many thanks to Joe Binder, Jay Roxe, Prasadi de Silva, and Eric Knox, all members of the Visual Basic team at Microsoft. Each of them fielded a relentless onslaught of questions about esoteric Visual Basic and .NET features, and provided answers filled with knowledge, patience, and grace. My agent, Claudette Moore, always deserves her own paragraph in any computer book I write. In fact, she would be a great subject for one of those literary-agent- focused biographies that the public is always clamoring for. Not only does she do a great job at all of the normal agenty things, but she also shares personally in the joys and sorrows of the authors under her charge. Thank you for another fun year in books.
xx | Preface To Maki, my wife, and to Spencer, my son, I give a special wave of thanks. If you’ve ever spent time with authors, you know how cranky they can get. But Maki and Spencer combat crankiness with care and love, and it works. The words thank you seem so inadequate when I owe both of them so much. Thanks be to God because He provided such a tremendous family to me.
1 Chapter 1 CHAPTER 1 Introducing .NET1 Welcome to .NET! I might as well have said, “Welcome to the universe,” because like the universe, .NET is huge. And it’s complex. And it’s filled with black holes and other things that don’t always make sense. Yet it (.NET, not the universe) turns out to be a fantastic system in which to develop software applications. The .NET Framework was not developed in a vacuum (unlike the universe); Microsoft designed it and its related development languages—especially C# and Visual Basic—to address various issues that plagued Windows software developers and users. To fully understand why .NET was necessary, we need to take a short trip down computer memory lane. Before .NET Practical, general-purpose computers have been around since the mid-20th century. However, they were inaccessible to most people because (a) they cost millions of dol- lars; (b) they consumed gobs of electricity; (c) maintenance and programming could be done only by highly trained specialists; and (d) they tended to clash with the liv- ing room furniture. Fast-forward about 30 years. IBM comes out with the “personal” computer. These “desktop” computers represented a great advance in technology, but only a minority of people ever used them. They continued to be expensive (thousands of dollars), and maintenance and programming still required significant investments in training. IBM PCs also looked hideous around the living room furniture. Then came the Apple Macintosh. With its sleek design and its user-friendly function- ality, it introduced the joy of computing to the masses. And while programming it was not always straightforward, it did give nice results. It’s no wonder that Microsoft decided to copy—oops, I mean improve upon—its functionality.
2 | Chapter 1: Introducing .NET Microsoft Windows 1.0 brought a greater level of usability to the IBM/Intel comput- ing platform. But it wasn’t a free ride for programmers. MS-DOS development was hard enough without the addition of the “message pumps” and the hundreds of Application Programming Interface (API) calls needed by Windows programs. Visual Basic 1.0, introduced in 1991, greatly simplified the development process, but with the advent of 32-bit systems, ActiveX and COM components, and the Web, even VB programmers soon felt overwhelmed. Throughout the 1990s, the situation only seemed to worsen. Microsoft saw increased competition in the form of the Java™ language and the Linux operating system. Hackers were exploiting buffer overruns and other security issues present in the Windows platform. Users experienced myriad computer problems stemming from conflicting standards, competing data integration technologies, registry bloat, and “DLL hell.” In frustration, an Excel user’s group set fire to the entire Microsoft cam- pus in Redmond. Well, it didn’t get that bad. But Microsoft did see that it needed to address the over- all software development and usability issues on its beloved Windows platform. Its solution came in the form of the .NET Framework. Back to Introducing .NET When Microsoft announced its plans for .NET, it surprised many developers, espe- cially Visual Basic developers, who saw it as a giant step backward for “Rapid Appli- cation Development.” But the release of the .NET Framework version 1.0 in 2002 did bring many needed benefits: .NET introduced a unified programming environment All .NET-enabled languages compile to “Microsoft Intermediate Language” before being assembled into platform-specific machine code. Visual Basic, C#, and other .NET languages are wrappers around this common .NET “language.” Since all .NET-enabled compilers speak the same underlying language, they no longer suffer from the many data and language conflicts inherent in other cross- language component-based systems such as COM. The .NET version of Visual Studio also unified the standard user interface that lets programmers craft source code. .NET committed developers to object-oriented technologies Not only does .NET fully embrace the object-oriented programming paradigm, but everything in .NET is contained in an object: all data values, all source code blocks, and the plumbing for all user-initiated events. Everything appears in the context of an object.
The .NET Object | 3 .NET simplified Windows programming Programming in Visual Basic before .NET was easy enough, until it came time to interact with one of the API libraries, something that happened a lot in profes- sional programming. With .NET, most of the regularly used APIs are replaced with a hierarchy of objects providing access to many commonly needed Win- dows features. Since the hierarchy is extensible, other vendors can add new func- tionality without disrupting the existing framework. .NET enhanced security Users and administrators can now establish security rules for different .NET fea- tures, to limit malicious programs from doing their damage. .NET’s “managed” environment also resolves buffer overrun issues and memory leaks through fea- tures such as strong data typing and garbage collection. .NET enhanced developer productivity through standards The .NET Framework is built upon and uses many new and existing standards, such as XML and SOAP. This enhances data interchange not only on the Win- dows platform, but also in interactions with other platforms and systems. .NET enhanced web-based development Until .NET, a lot of web-based development was done using scripting languages. .NET brings the power of compiled, desktop development to the Internet. .NET simplified the deployment of applications If .NET is installed on a system, releasing a program can be as simple as copying its EXE file to the target system (although an install program is much more user- friendly). Features such as side-by-side deployment, ClickOnce deployment, and an end to file version conflicts and “DLL hell” (the presence of multiple versions of the same DLL on a system, or the inability to remove a version of a DLL) make desktop and web-based deployments a snap. If you didn’t understand some of the terms used in this section, that’s all right. You will encounter them again, with explanations, in later chapters. The .NET Object To fully understand software development in .NET, you must understand what an object is. (If you are familiar with object-oriented programming—OOP—you can probably skip down to the next section, although you will miss some really great content.) While some of this section’s information will also appear in Chapter 8, it is so important to the discussion of .NET that a portion appears here as well.
4 | Chapter 1: Introducing .NET Objects and Data From a programming standpoint, a computer performs four basic tasks: • It stores data in the computer’s memory area. • It supports processing of this data through basic operations, including addition and subtraction, Boolean algebra, and text string manipulation. • It allows the user to interact with the data stored in memory. • It provides a way to bring the data in and out of memory, through input and out- put devices such as keyboards and printers, and through long-term storage media such as hard drives. The core of these four activities is data. Computers exist to manipulate data. Operat- ing systems provide the basic foundation for these activities, but it is software appli- cations that make these features—the ability to manipulate data—real and meaningful to the user. High-level programming languages are the primary tools used to develop these applications, each of which uses some general methods to make data manipulation features available to the programmer. Back in the good old days of assembly language development, if you knew the memory address of a piece of data, you could access and manipulate it directly. In early flavors of BASIC and in most other “procedural” languages, data was accessed through variables. As languages grew in complexity and purpose, so did their view of data. In the LISP (short for “List Processing” or “Lots of Irritating Silly Parentheses”) language, any data value exists within a larger list or set of data. But in .NET languages, data is viewed through the object. Objects are collections of data values and associated source code. While in older BASIC dialects, each data element was more or less independent through its named variable, related data values in OOP languages can be grouped into objects. Object implementations often include source code designed to manipulate the data values of that object. Objects generally represent some thing, often a thing that has a real-world counter- part, whether physical or conceptual. For instance, your code may include a House object that has data fields or properties for the address, the exterior paint color, and the number of people living in the house. Associated source code could manage that data; a Paint method could alter the color value used for the exterior paint. The data and code elements within an object are called members. Some members are hidden inside the object and can be accessed only by the object’s source code. Other members are more public; any code in your application can use them, not just that subset of application code found inside the object. Consider a television as an object (see Figure 1-1).
The .NET Object | 5 The public members of a TV are generally easy to use: the power button, channel selector, volume control, and so on. They are the conduits through which the user controls the data values of the TV (its video and audio output). There are also hid- den members inside the TV; you could use these members to impact the picture and sound quality, although this would be a bad idea for most users. You don’t want me messing with the internal members of your TV set, trust me. In the same way, an object doesn’t want code outside the object to mess with its internal members except through the public members. I don’t care how a TV works internally, as long as I can get pictures and sound out of it by using the controls that are exposed (power, channel, volume). Objects and Interfaces The public members of an object represent its interface. If code outside the object wants to manipulate the data belonging to that object, it uses the members of the interface. It doesn’t have to figure out the hidden members or how they work, and that’s good. It’s especially good if those internal members ever change for any reason, which happens more often than you think. Consider how the internals of TVs have changed just in the past 30 years. Here’s a drawing of the TV my family had when I was a kid. Compare it to modern flat-panel TVs available today (see Figure 1-2). My family’s TV was cool. It had an AM/FM stereophonic hi-fi radio, a turntable that could play 33 1/3, 45, and 78 rpm records, and a large 19-inch screen with a vivid, black-and-white, crystal-clear display. Two kids could hide behind it when playing hide-and-seek. And my friend who had the same model said that you could draw these really cool permanent lines on the screen with a magnet. Who cares that the speaker panels looked like vertical shag carpet? Who cares that the unit took up 30% of the floor space in the room? Who cares that you could cook sausages on top of it from the heat generated by the vacuum tubes? It was more than a TV; it was an entertainment center. Figure 1-1. A TV: it’s an object, not just objectionable Outside view Inside view
6 | Chapter 1: Introducing .NET Now compare it to the wimpy little flat-panel job on its right. If you look closely, you find that the interface to the TV hasn’t really changed much in three decades. There are still controls for power, volume, and channel selection (although Horizontal Hold and Vertical Hold are gone, sniff). What has changed is the internal configura- tion. Gone are the humming vacuum tubes, all replaced with efficient transistors and solid-state components. But it doesn’t really make much difference to the TV viewer, since the public interface remains the same. Objects in OOP development work in the same way. As long as the public interface remains the same, the object’s actual code and internal data storage system—also known as the object’s implementation—can change with no impact to the overall application. Objects and Instances The interface and implementation of an object really represent only its design; these are the parts the programmer creates through the source code. They exist even before the program is compiled and installed on the user’s computer. In fact, at this level, objects really aren’t even known as objects. In most languages (including Visual Basic), the word class indicates the implementation of an object’s interface. Once your application is installed on a computer and starts up, the code creates instances of the class to store actual data in memory. These instances are the true objects of OOP development. Depending on how your code is written, a single class implementation might be used to create one or even hundreds of objects in memory at the same time. Figure 1-2. Are those really TVs? TheTV of my childhood A newfangled thing
The Parts of the .NET Framework | 7 In .NET, all of your code and data values appear inside objects. Pretty much every- thing you see in a running program is an object: a Windows form is an object; a list- box control on that form is an object; and a single item in that listbox is an object. The Parts of the .NET Framework So, now you know all about objects, and you are probably thinking it’s time to toss this book into the pile and start programming. But there are a few more parts of the .NET Framework still to discuss. These parts show up ad nauseam in the .NET doc- umentation, and they each have a three-letter acronym (TLA), or thereabouts. The Common Language Runtime At the center of the .NET Framework is the Common Language Runtime (CLR), so named not because it is common or ordinary, but because all .NET-enabled lan- guages share it in common. Everything you do in a .NET program is managed by the CLR. When you create a variable, thank the CLR and its data management system. When you say goodbye to a piece of data, thank the CLR and how it manages the release of data through its garbage collection system. Did you notice how the word manage keeps showing up in those sentences? My editor sure did. But “manage” is the mot juste, since that is what the CLR does. In fact, software written for the .NET Framework is called managed code. Any code that falls outside the CLR’s control, including COM (ActiveX) components used by your .NET application, is known as unmanaged code. The CLR is a lot like Los Angeles International Airport. If you have ever been to LAX, you know that there is a whole lot of activity going on. Airplanes arrive and depart each minute. Cars by the thousands enter and leave the two-level roadway and the central parking structures. People and pickpockets move constantly among the eight main terminals and the massive international terminal. There’s a lot happening, but so much of it is managed. Planes cannot take off or land without approval from the control tower. Access points and gates manage the roadways and parking garages. Friendly, courteous TSA agents manage the flow of passengers and pickpockets into and out of the secure areas of the terminals. The control and management structures in place at LAX ensure an orderly and secure flow of people between their planes and the city of Los Angeles. The control and management structures of the CLR ensure an orderly and secure flow of data between .NET code and the rest of the computer or connected network. You’d probably like to know the secret of how the CLR is able to process programs written in any .NET language, including Visual Basic, C#, and FORTRAN. So would Microsoft’s competitors. Actually, they do know, because there is no secret.
8 | Chapter 1: Introducing .NET All .NET-enabled languages convert (i.e., “compile”) your source code into Microsoft Intermediate Language (or MSIL, pronounced “missile,” and more commonly abbre- viated as just IL). For those of you familiar with assembly language, it looks a lot like that. For those of you not familiar with assembly language, it looks a lot like gibber- ish. For example, here is some Visual Basic source code for a console application (a non-Windows text-based program, like the old MS-DOS programs) that simply out- puts “Hello, World!” from a code procedure called Main: Module Module1 Sub Main( ) Console.WriteLine("Hello, World!") End Sub End Module That’s the whole .NET program. When the Visual Basic compiler converts it to MSIL, the Main procedure looks like this (slightly modified to fit on this page): .method public static void Main( ) cil managed { .entrypoint .custom instance void [mscorlib]System. STAThreadAttribute::.ctor( ) = ( 01 00 00 00 ) // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Hello, World!" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Module1::Main Yes, it is gibberish. But that’s OK, because it fulfills the International Computer Book Association’s requirement that every Chapter 1 include a “Hello, World” code sample. Also, the CLR understands it, and that’s what really counts in .NET. As long as you can get your code into IL, .NET will process it. The Visual Basic compiler just happens to generate IL for you. Other .NET language compilers, including C#, tar- get IL as well. You can even write your own IL code, but you’re probably reading the wrong book for that. Just to put your mind at ease, this will be the last bit of IL you will see in this book. The Common Language Specification Languages that claim to support .NET cannot just say so for any old reason. They truly have to be compatible with .NET and its workings. This is done through the Common Language Specification (CLS). The CLS defines a minimum set of features that a language must implement before it is considered to be .NET-compliant, or more accurately, CLS-compliant. A language can go beyond that minimum if it wants, and .NET includes many addi- tional features upon which language-specific features may be built. A language that
The Parts of the .NET Framework | 9 implements only the minimum CLS-specified features may not be able to fully inter- act with components from languages that exceed the minimum specification. Visual Basic is, of course, CLS-compliant, and in fact it goes way beyond that minimum. The Common Type System Since the CLR is controlling your source code anyway, Microsoft thought it would be good to have it control the source code’s data as well. The .NET Framework does this through its Common Type System (CTS), which defines all of the core data types and data mechanisms used in .NET programs. This includes all numeric, string, and Boolean value types. It also defines the object, the core data storage unit in .NET. The CTS divides all objects into two buckets. The first bucket, called value types, stores actual data right in the bucket. If you have a 32-bit integer value, it gets put right in the value type bucket, ready for your immediate use. The other bucket con- tains reference types. When you look in this bucket, you see a map that tells you where to find the actual data somewhere else in the computer’s memory. It seems like value types are easier to use, and they are, but they come with a few restrictions not imposed on reference types. Programs and components written using the CTS standard can exchange data with one another without any hindrances or limitations. (A few .NET data types fall out- side the “core” CTS types, but you need to avoid them only when you want to specif- ically interact with components that can use only the core CTS types.) When you write your applications in Visual Basic, most of your code will appear in classes. Classes are reference types that include both data values and associated code. The data values included in a class are most often the core CTS data types, but they can also contain objects that you design elsewhere in your application. Visual Basic also includes structures, the weaker yet quicker younger brother of classes. Struc- tures implement value types, and also include both data and code. Classes and structures are just two of the data/code types available in Visual Basic. Interfaces are class and structure skeletons; they include design details of what should appear in a related class or structure, but don’t include any actual implemen- tation or working code. Delegates define a procedure “signature” sans implementa- tion, and are used to support events, those actions (initiated by the user, by the operating system, or by your code) that tell your code, “Get to work now!” Sea otters are aquatic mammals that are curiously related to the weasel, and like to eat sea urchins. Modules are blocks of code and data, but unlike classes and structures, you can’t create independent objects from them. Enumerations group a set of related inte- ger values, generally for use as a list of choices. In .NET parlance, all of these terms (class, structure, interface, delegate, module, and enumeration, but not sea otter) are known collectively as types. You probably already knew that .NET had some confusing elements in it; you wouldn’t have bought a
10 | Chapter 1: Introducing .NET book about it if it were easy. But despite all the complex technology, it is this simple word, type, which causes the most confusion. You will likely experience some angst throughout this book each time you read it. The problem: it’s too general. Not only does it refer to these core elements of the CTS, but it is also used when talking about just the Visual Basic-specific value types (more often called the Visual Basic “data types”). The nickname for structures is “user-defined types,” yet another confusing use of “type.” Programmers who used Visual Basic before its .NET incarnation also remember “Type” as the language statement used to create user-defined types. Arrrgh! Microsoft should have used some word other than type for the world of classes, interfaces, enumerations, and so on. “Banana” would have been a better choice since it is only sometimes used to discuss software. But “type” is the word, so you better get used to seeing it. I will try to include as much context as possible when using the word throughout this volume. The members of a type usually consist of simple data fields and code procedures, but you can also include other types as members. That is, a class can include a nested class if it needs to. Only certain types support nesting—see Chapter 8 for details. I also talk about access levels in that chapter. Each member has an access level that says what code can use that member. There are five access levels, ranging from pub- lic (anybody and their brother can use the member) to private (you have to be inside the type to even know it’s there). Chapter 6 discusses the .NET type system in greater detail, including the informa- tion you crave on classes, structures, and other bananas. .NET Class Libraries Computers are actually quite stupid. Whereas I can count all the way to 17, a com- puter tops out at 1; it only knows the digits 0 and 1. The CPU includes a set of sim- ple operators used to manipulate the digits 0 and 1, and a few more operators that compare 1s and 0s in complex ways. The computer’s last great trick is its ability to move 0s and 1s into and out of memory, but whoop-de-doo. Sure it does these things at nearly the speed of light, but can it calculate π to 3 million decimal places? Well, actually it can. Computers don’t know anything about the letters of the alpha- bet, and they really can handle only the digits 0 and 1, yet here I am using a com- puter to write an award-winning book. It is the ability to combine the simple 1-bit data values and operators into increasingly complex libraries of functionality that makes useful computers possible.* The .NET Framework is built upon decades of increasingly complex functionality. When you install the .NET Framework, the CLR and its associated type system * If you want to read a truly fascinating book on how complex software and hardware operations are formed from the most basic uses of 0 and 1, read Charles Petzold’s Code: The Hidden Language of Computer Hard- ware and Software (Microsoft Press).
The Parts of the .NET Framework | 11 represent the core of the framework. By itself, the framework includes all the basic functionality needed to let you add 2 and 2 together and correctly get 4. And as a business application developer, you spend a lot of time doing just that. But what if you want to do something more complex, something that you know some other pro- grammer has already done, like sorting a list of names or drawing a colored circle on a form? To get that answer, go to the class libraries, the .NET Class Libraries. These libraries, installed with the framework, include a lot of prewritten (increasingly com- plex) functionality that you don’t have to write from scratch. There are two class libraries in .NET: the Base Class Library (BCL) and the Frame- work Class Library (FCL). The BCL is smaller, and contains the most essential fea- tures that a program just couldn’t do without. It includes only those classes that are an absolute must for supporting applications on the framework if Microsoft were to, say, port the framework to Linux. The FCL is larger, and includes everything else Microsoft thought you would want to have in your programs, but was not absolutely essential to have in the BCL. Don’t even ask how many classes there are in the FCL; you don’t want to know. I bet that Microsoft doesn’t even really know the full number. I am convinced that those wacky pranksters at Microsoft have included “gag” classes in the FCL, but they are so deeply buried that few programmers ever encounter them. With thousands (yes, thousands!) of classes, enumerations, interfaces, and other types included in the BCL and FCL, you would think that it would be hard to find just the class you need. But it’s not that difficult, at least not overwhelmingly diffi- cult. The .NET Framework includes a feature called namespaces. All types in .NET appear in a hierarchy—a tree-like structure—with just a few minimal entries at the root. Each node in the hierarchy is a namespace. You uniquely identify any class or other type in the libraries by naming all the namespaces, from the root down to the local namespace that contains the class, separating each node with a period (.). Unlike most hierarchies that have all branches starting from a single root node, the .NET namespace hierarchy has multiple root nodes. The largest root namespace is named System. It includes many classes, but it also includes several next-tier hierar- chy nodes (namespaces). Since the framework includes features for both Windows- based and web-based application development, there are namespaces that contain the Windows-specific and web-specific development features. These namespaces appear just within the System namespace, and are called Windows and Web. All code related to on-screen forms in the Windows namespace appears in the Forms namespace, and within this namespace is the actual class that implements a form, named Form. Figure 1-3 presents an image of this namespace subset. In Visual Basic, you identify a class by qualifying it with all its namespaces, starting from its root namespace. The Form class has the following fully qualified name: System.Windows.Forms.Form
12 | Chapter 1: Introducing .NET All classes and types exist somewhere in the hierarchy, although not every class descends from System. Many of the supporting features specific to Visual Basic appear in the Microsoft.VisualBasic namespace, which has “Microsoft” as its root node instead of “System.” When you create new projects in Visual Basic, the name of the project is, by default, a new top-level node in the hierarchy. If you create a new Windows application named WindowsApplication1, the default “Form1” form has the following fully qualified name: WindowsApplication1.Form1 This new application’s namespace is not just a second-class appendage hanging off the System namespace. It is fully integrated into the full .NET namespace hierarchy; the WindowsApplication1 namespace is a root node, just like the System and Microsoft root nodes. Visual Basic includes features that let you alter the default namespace for your application, or place one of the application’s classes in a specific namespace. You can even place your application’s classes in the System namespace branch. Changing WindowsApplication1 to System.MySuperApp moves Form1 to: System.MySuperApp.Form1 If your application is actually a component or library destined for use in programs, your app’s classes will appear in the namespace you specify when the other program loads your component into its application area. Your code will look like it is part of the Microsoft-supplied namespaces. Is that cool or what? Although you can add your classes to the System namespace, you will incur the wrath of other .NET programmers. The System namespace is supposed to be for “system” (read: Microsoft-supplied) features, and that’s it. Also, there’s a chance that two ven- dors might use the same namespace path. So, to avoid potential namespace conflicts and dirty looks from other programmers, you should name your application’s classes as: CompanyName.ApplicationName.ClassName A single class or other type cannot be split across multiple namespaces, even within the same hierarchy branch. However, two classes or types may share a common name in different namespaces, even within the same branch. Figure 1-3. A hierarchy of namespaces and classes System Web Windows Forms Form = Namespace = Class
The Parts of the .NET Framework | 13 All classes of the BCL and FCL appear intermingled throughout the entire namespace hierarchy. This means that you cannot necessarily tell whether a particu- lar class is from the BCL or the FCL. Frankly, it doesn’t really matter; your code won’t care which library a class comes from, as long as it is available for use on the user’s workstation. Just before the release of Visual Studio 2008, Microsoft announced that it would make the source code for much of the Framework Class Library version 3.5 available for developers to review. This means that programmers who want to know how Microsoft sorts a list of names in memory or draws a colored circle on a form will get at least a partial glimpse of how it is done. Assemblies and Manifests An assembly is a “unit of deployment” for the parts of a .NET application or library. In 99.9% of cases, an assembly is simply a .NET executable file (an .exe file) or a .NET library of classes and other types (a .dll file). It is possible to split an assembly among multiple files, but usually it is one file for one assembly. What makes an ordinary .exe or .dll file an assembly is the presence of a manifest. For single-file assemblies, the manifest appears right in the file; it can also appear in a file of its own. The manifest is a chunk of data that lists important details about the assembly, including its name, version information, default culture, information on referencing external assemblies and types, and a list of all the files contained in the assembly. The CLR will not recognize an assembly without its manifest, so don’t lose it. Assemblies can include an optional strong name. This helps to ensure the integrity and authenticity of an assembly through a digital signature attached to the manifest. The strong name uses public key cryptography to guarantee that the assembly is unique and has not been tampered with. Visual Studio and the .NET Framework include tools that let you add a strong name to an assembly. When you deploy your application, you will normally place all assembly files, config- uration files, and any related files specific to your application into the application’s install directory, just like in the old Jurassic days before .NET. Shared assemblies designed to be used by more than one application on a single machine can be stored in the Global Assembly Cache (GAC). All assemblies placed in the GAC must have strong names. Some systems may allow only the system administrator to add assem- blies to the GAC. Metadata and Attributes Assemblies are brought to you by the letter m. In addition to manifests and type members, assemblies also contain metadata. The application code and data elements stored in an assembly parallel the code and data items found in the related Visual
14 | Chapter 1: Introducing .NET Basic source code; for each type and member in your source code, there is associated executable code in the deployed assembly. This makes sense, and is not much of a change from pre-.NET deployments. What is different is that the Visual Basic com- piler now attaches additional information—metadata—to each type and member in the assembly. This metadata documents the name of the associated content, infor- mation about required data types, information on class inheritance for the element, and security permissions required before the element can be used by the user or other software. Your Visual Basic source code can enhance the metadata for any element of your assembly through attributes. The metadata generated by an attribute is more than just some ID number. Attributes implement full .NET classes, with their own data values and associated logic. Any .NET code that knows how to process attributes can examine the attributes for a type or member and take action as needed. This includes Visual Studio, the Visual Basic compiler, and your own custom applications. How’s this for a mundane example: the .NET Framework includes an attribute named ObsoleteAttribute. This attribute lets you mark types or members of your assembly as obsolete or no longer supported. (Visual Studio uses this attribute to dis- play a warning whenever you attempt to use an out-of-date BCL or FCL feature.) To use the attribute, add it to a member of your application using angle brackets: Class MyClassWithOldMembers <ObsoleteAttribute> Sub DoSomeWork( ) End Sub End Class This code defines a single class (MyClassWithOldMembers) with a single member proce- dure (DoSomeWork), a procedure that clearly does some work. The procedure is tagged with the ObsoleteAttribute attribute. By custom, all attribute names end in the word Attribute. You can leave off this portion of the word if you wish, as long as the result- ant word does not conflict with any Visual Basic language keyword: Class MyClassWithOldMembers <Obsolete> Sub DoSomeWork( ) End Sub End Class When you compile the class and store it in an assembly, the <ObsoleteAttribute> attribute is stored as part of DoSomeWork’s definition. You can now write a separate Visual Basic application that scans an assembly and outputs the name and status of every type and member it finds. When that analysis program encounters the obso- lete member, it will detect ObsoleteAttribute in the metadata, and output the status: DoSomeWork Procedure: Obsolete, don't use it! Most attributes are designed with a specific purpose in mind. Some attributes instruct Visual Studio to display the members of a class in specific ways. You’ve probably already played with the form-editing features of Visual Studio to design a
The Parts of the .NET Framework | 15 simple Windows desktop application. When you add a control (such as a button or a listbox) to a form and select that control, Visual Studio lets you edit details of that control through the Properties panel area (see Figure 1-4). The Button control is implemented as a class, and many of its class members appear in the Properties panel, but not all of them. When the Button class was designed, attributes were added to its members that tell Visual Studio which members should appear in the Properties panel, and which should not. Visual Studio dutifully exam- ines these attributes, and displays only the requested properties. Versioning Like yours, my applications are perfect from their initial release, and I never have a reason to modify them or add features. But there are software development organiza- tions—including one large company that, so as not to cause embarrassment, I will refer to only by its initial letter of M—that feel the need to “one-up” their competi- tion by coming out with “improved” versions of their previously released software offerings. Let’s say that “M” happened to have a popular word processor that includes version 1.0 of a spellcheck component. “M” also happens to sell an email tool that depends specifically on version 1.0 of that same shared component. If, in a show of competitive machismo, “M” releases an update to the word processor and the spellcheck component (now version 2.0), what happens to the email tool’s spellchecking ability? Figure 1-4. The Properties panel in Visual Studio I'm talking about this Properties area
16 | Chapter 1: Introducing .NET Not that this ever happens in real life. But if it did, the replacement of a vital shared component with a newer but somewhat incompatible version could cause real prob- lems. A related problem is the deployment of multiple versions of a single component on the same workstation, all in different directories. Can any of them be safely deleted? .NET solves these problems through versioning. All assemblies that use shared com- ponents identify exactly which versions of the shared components they require. Although an application can be reconfigured to use a later version, it will use only the originally specified version of a shared component by default. Multiple versions of a single shared component can be added to the GAC, a feature called side-by-side deployment. The CLR ensures that the right application links up with the right component. You can even run applications simultaneously that use different versions of the same component. From Source Code to EXE Now you know pretty much everything there is to know about .NET except for that pesky programming thing. Before delving into some actual code, let’s take a little snack break and examine the lifetime of an application, from start to finish (see Figure 1-5). So, here’s what happens, step by step: 1. You, as the programmer, are responsible for preparing the basic ingredients (a) of the application. For Visual Basic programs, this means creating one or more source code files with a .vb extension. Your ingredients may also include other support files, such as resource files (text and graphics files, often used for multi- language support). Figure 1-5. The real Visual Basic development process (a) (b) (c) (e) (d)
What About Visual Studio and Visual Basic? | 17 2. Your application is cooked by the Visual Basic compiler (b). The result is an assembly, complete with a manifest and metadata. The output is actually semi- compiled MSIL and includes ready-to-execute versions of the original source code’s types and members, including all member and type names. All this con- tent can be “decompiled” (returned back to full MSIL, although not to full Visual Basic) using a tool named ildasm.exe (the Microsoft Intermediate Lan- guage Disassembler), which is included with the .NET Framework. Since you probably don’t want just anyone disassembling your application and looking at the code, Microsoft (and other third parties) also supplies an obfuscator, which sufficiently scrambles the content of your code to make it just difficult enough to discourage prying eyes. 3. The assembly (c) is deployed to the user’s workstation. A few different methods are used to deploy the application, including (1) generating a standard Windows Installer setup package; (2) generating a ClickOnce deployment; or (3) performing an xcopy install, which involves nothing more than copying the EXE assembly itself to the destination machine. No matter which deployment method you choose, the .NET runtime (d) must also be installed on the user’s workstation. 4. The user eats—I mean runs—the program (e). The CLR does a final just-in-time (JIT) compile of the MSIL assembly, to prepare it for use on the local platform. It then presents the application to the user, and manages all aspects of the applica- tion while it runs. The user experiences a level of joy and satisfaction rarely encountered when using other software applications. As with the preparation of a Thanksgiving meal, the actual development process is somewhat more involved than just reading a paragraph (or a recipe book) about it. But it’s not so difficult that it can’t be put in a book like this one. What About Visual Studio and Visual Basic? Wait a minute, what about Visual Studio? That last section didn’t even mention it. And it didn’t need to, since you do not need to use Visual Studio to develop, compile, deploy, or run Visual Basic applications. The entire .NET Framework—including the Visual Basic compiler—is available for free from Microsoft’s web site; download it and use it to develop and deploy applications that are every bit as powerful and com- plex as, well, Visual Studio. The July 1983 issue of Datamation magazine includes an article from manly reader Ed Post, titled “Real Programmers Don’t Use Pascal.”* I highly recommend that you read this article, as it will help you quickly separate the real programmers from the “quiche eaters.” And when you do, run away as fast as you can from the real programmers. * Datamation 29 (7): July 1983, pp. 263–265. I also found the text of the article on the Internet by doing a search on the title. A similar version of the text, with only minor editorial changes, also exists under the title “Real Programmers Don’t Write Pascal.”
18 | Chapter 1: Introducing .NET Oh, sure, they can reconstruct your source code from the obfuscated .NET assembly, but they will be useless on a team project using Visual Studio. A “real programmer” could code any .NET application using Notepad, and it would run. Actually, real programmers would use Emacs or vi instead of Notepad (since Windows does not include a keypunch interface), but the results would be the same. They would growl as you blissfully type away in Visual Studio’s elegant, well- designed, and fully customizable and extensible user interface. They would gripe and bare their cheese-cracker-with-peanut-butter-encrusted teeth at you while you use the IntelliSense and AutoCompletion features built into the Visual Studio code edi- tor. They would consume another slice of quiche-shaped cold pizza while you drag- and-drop both Windows and web-based user interfaces. Yes, the real programmer could generate full applications with just a text (or hex) editor and a .NET compiler, but you would get the glory, since you would be done in a fraction of the time it would take the FORTRAN lover to eek out his code. Visual Studio 2008 Since this is a book on Visual Basic development and not on Visual Studio usage, I won’t be delving too much into Visual Studio’s features or its user interface ele- ments. It is a great application, and its tight integration with the .NET Framework makes it the best tool for developing applications with .NET. But as the real pro- grammer would tell you, it is really just a glorified text editor. Visual Studio hides a lot of the complexity of .NET code, and its automatic generation of the code needed to build your application’s user interface is a must-have. Most of its features exist to simplify the process of adding code to your application. Although I will not be including a 20-page review of Visual Studio right here, you will find images of Visual Studio throughout the text, placed so as to advance your understanding of the topics under discussion in each chapter. When you start up Visual Studio for the first time, it displays the Start Page. (See Figure 1-6. The screen- shots in this book are taken from the Professional Edition of Visual Studio 2008.) Visual Studio 2008 is the fourth major release of the product since .NET’s initial introduction in 2002. Each release (in 2002, 2003, 2005, and 2008) corresponds to a related release of the .NET Framework (versions 1.0, 1.1, 2.0, and 3.5, respectively) and of the .NET implementation of Visual Basic. The 2008 release of Visual Studio is major. It is packed with new usability features, and comes in four delicious flavors: Visual Studio 2008 Express Edition This entry-level product is geared toward the home hobbyist or weekend pro- grammer who wants to learn .NET and one of its core programming languages, but won’t be snuggling up to it on a daily basis. Visual Studio 2008 Express Edi- tion is actually multiple Express Edition language products promoted together, including Visual Basic 2008 Express Edition. Microsoft’s goal is to introduce as
Visual Studio 2008 | 19 many people as possible to the joys of .NET programming, so it offers the Express Edition products at no cost. This edition includes a simplified Visual Studio-like user interface, but it does impose a few restrictions on your program- crafting ability. You can still edit the source code directly and craft applications of any complexity, but the Express UI won’t always assist you with this. For instance, you cannot develop web applications with the Visual Basic Express product unless you install the separate Visual Web Developer 2008 product. Also, Express doesn’t include much support for deployment; applications designed with the Express Edition are generally expected to be used on your own workstation only. Visual Studio 2008 Standard Edition Visual Studio’s Standard Edition is just like the Express Edition, with a few extras thrown in, such as multiple-language support, web development tools, and deployment support through both ClickOnce and Windows Installer meth- ods. SQL Server 2005 Express Edition is included. Visual Studio 2008 Professional Edition This is the minimum level required by programmers who will develop applica- tions on a daily basis for money. It’s the version that I use, and it includes all the “power” features needed by a single programmer for both desktop and web- based development. The straightjacketed Express user interface is out, replaced Figure 1-6. The Visual Studio Start Page
20 | Chapter 1: Introducing .NET by the full Visual Studio “mighty” Integrated Development Environment (IDE) and all documentation. Also included are special tools that help you develop applications for Microsoft Office, and for mobile devices. But wait, there’s more. You also get SQL Server 2005 Developer Edition. All instructions in this book that relate to using the development environment refer to the Professional Edi- tion. But if you are following along using the Express or Standard Edition, you will be just fine since the interfaces are quite similar. Visual Studio Team System 2008 The crème de la crème of the Visual Studio product line is Team System. It includes features needed by development teams that work on projects together, features such as project management tools and source code control. Visual Studio Team System 2008 Team Foundation Server, a separate product, can be installed on a shared server, and enhances the features of the Team System package. SQL Server 2008, the latest edition of Microsoft’s flagship database product, was officially launched on the same day as Visual Studio 2008. Unfortunately, “launch” had two different meanings depending on which of the products you were talking about. For Visual Studio 2008, “launch” meant you could download the product from Microsoft’s web site several months before the launch event. For SQL Server, a mirror was used to allow access to the product a few months after the event. That difference was enough to prevent SQL Server 2008 from being the database version bundled with Visual Studio. But you do get SQL Server 2005 in your Visual Studio goodie bag, and you can always upgrade if needed. Beyond the database support, Visual Studio 2008 has been endowed with several new usability and feature enhancements: LINQ-specific features We’ll discuss the new LINQ feature in Chapter 17. Beyond the code changes added to .NET to support LINQ, Visual Studio includes special designers that assist you in programming with LINQ. Support for Windows Presentation Foundation projects Windows Presentation Foundation, formerly code-named Avalon, is a new XML-based user interface system supported by Windows for both desktop and web-based applications. Visual Studio 2008 lets you create WPF-based applica- tion or control projects. This book discusses Windows Presentation Foundation briefly in Chapter 18. Improved HTML (web page) editor The new HTML editor improves on the previous editions found in earlier releases of Visual Studio. The 2008 release includes a “split view” editor show- ing HTML and WYSIWYG views simultaneously (see Figure 1-7). Cascading Style Sheets (CSS) finally get their due with a new CSS style editor and IntelliSense sup- port for CSS content.
Visual Studio 2008 | 21 Targeted library support Earlier releases of Visual Studio were closely tied to the related release of .NET. Visual Studio 2008 continues that tradition through its association with version 3.5 of the .NET Framework. However, you can now target earlier versions of .NET (back through version 2.0) in Visual Studio 2008 with just the click of the mouse. Enhanced debugging support Visual Studio 2008 includes better support for remote debugging, especially on Windows Vista. But the most amazing of the new debugging features is the abil- ity to step into the source code for the .NET Framework libraries, with Visual Studio dynamically obtaining the right version of the source code based on your project type and framework version. Transparent IntelliSense IntelliSense is a productivity tool that helps speed you along in your code-crafting frenzy. But sometimes the IntelliSense windows that popped up would obscure your source code. Visual Studio 2008 now lets you look through the IntelliSense list window just by holding down the Ctrl key (see Figure 1-8). JavaScript IntelliSense and debugging support Although Visual Studio once claimed amnesia concerning Java and JavaScript, it now fully embraces the latter. This enhanced JavaScript environment simplifies the creation of new Ajax applications. While not specifically needed for Visual Basic, this new support is a big plus for those who develop web-based applications. Figure 1-7. Have it both ways: HTML markup and display
22 | Chapter 1: Introducing .NET Despite all these great new features, Microsoft still refuses to implement the most requested Visual Studio feature, Procedure AutoCompletion, in which Visual Studio would create the entire content of a source code procedure based on your entry of its name and the use of the Ctrl-Space bar key combination. Instead, Microsoft frit- ters away its time on other so-called productivity features. With Procedure Auto- Completion, you could write entire applications in minutes. Until that feature becomes available, you and I will have to continue writing software, crafting the quality code that users have come to expect from our fingers. Summary Nearly two decades ago, Visual Basic transformed the Windows development land- scape with its drag-and-drop programming model and its glitzy event-driven devel- opment structure. But Windows has changed a lot since those days of Windows 3.x. As Windows has changed, Visual Basic has changed right along with it. Visual Basic 2008, through its association with the .NET Framework, provides access to the pro- gramming tools needed to develop quality applications for the Windows desktop, the Internet, and the next generation of mobile devices. And Microsoft is not halting this progress with the 2008 release. The next version of Visual Basic, code-named both VBx and Hawaii, promises to include even more advanced features. That release will be built on top of Microsoft’s Dynamic Lan- guage Runtime (DLR), allowing it to freely interact with libraries from languages such as Ruby and Python. Figure 1-8. Seeing right through Visual Studio’s tricks
Project | 23 Project Welcome to the “Project” section, the part of each chapter where you have an oppor- tunity to get “hands-on” with Visual Studio 2008 and Visual Basic. Development of the Library Project, the main project focus of this book, formally begins in Chapter 3, but there’s still project work to do in the meantime. In this chapter, I’ll introduce you to the sample source code provided with this book, and we’ll take a stab at using it. Since most “Project” sections, including this one, will involve Visual Studio, make sure you have it installed and ready to use. Also, since each “Project” section is designed for you to use interactively with the supplied source code, I will assume that you have downloaded and installed the source code (see Appendix A for instruc- tions), and are viewing the source code with one eye while you read this section with the other. I will print sections of the source code in the book, but with tens of thou- sands of source code lines in the Library Project, I will not be able to print every line here. You will certainly get a lot out of each “Project” section by simply reading it, but you will get even more if you have access to the full source code. In this chapter’s project, we’ll load a sample program into Visual Studio and run it. There are two ways to do this. The first way is just to open the existing project directly from the installation directory. Browse to the directory where you installed this book’s source code, open the Chapter 1 subdirectory, and double-click the Chapter1.vbproj file. This will open the project directly in Visual Studio, ready to use. The second way is to use the chapter-specific project templates to create new projects in Visual Studio. The Setup program for this book’s source code modifies your installation of Visual Studio, adding new entries in the New Project dialog win- dow. Each of these new “project templates” can be used as the starting point for a new Visual Basic project. To load the Chapter 1 sample program using the template, start Visual Studio. The Start Page will appear, as shown way back in Figure 1-6. From the File menu, select New Project to display the New Project dialog window (see Figure 1-9). Your New Project dialog window may differ slightly depending on the features you chose to install with Visual Studio. The available projects are grouped by the descrip- tion in the “Project types” field. For instance, Figure 1-9 shows the various default project types you can create in Visual Basic, including Windows Forms Application (a standard desktop application for the Windows platform), Class Library (a DLL of class- defined features), and Console Application (command-line, text-based applications). To create a new application, first select the project type, select the template to use, and finally enter the name of the new project in the Name field. Clicking the OK but- ton creates a new project.
24 | Chapter 1: Introducing .NET To use the sample Chapter 1 project, select the Programming Visual Basic 2008 entry within the Visual Basic project type, and then select Chapter 1 Sample from the Tem- plates field (see Figure 1-10). Finally, click OK to create the new sample project. Once the project loads, access the program’s main form by double-clicking on the Form1.vb file in the Solution Explorer (see Figure 1-11). This default presentation of Visual Studio Professional Edition includes three editing components: (1) the main editing area, where the view of “Form1” appears; (2) the Solution Explorer panel, which provides access to all files included in the project; and (3) the Properties panel, which lets you edit various aspects of the currently selected item in the main editor area or elsewhere in the user interface. The sample project is pretty basic. It includes one form with a single action button. Clicking this button in the running application displays a simple message. Run the project by pressing the F5 key. When the main form appears, clicking on the “Go Ahead, Click Me!” button displays the message in Figure 1-12 (goal, sweet goal). Figure 1-9. The New Project dialog window: so many choices Figure 1-10. Selecting the Chapter 1 Sample project
Project | 25 So, what about all that complex code I had to write to develop this multifaceted application? It’s all there for the viewing. From the Solution Explorer panel, right- click on the Form1.vb entry and select View Code from the shortcut menu. (As with most source code samples presented in this book, I have had to slightly adjust the code so that it displays properly on the printed page. Generally, this involves split- ting a long logical line into two or more shorter ones.) Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click MsgBox("Hello, World!") End Sub End Class Figure 1-11. The main form of the sample application Figure 1-12. Hello again, world!
26 | Chapter 1: Introducing .NET We’ll get into the intricacies of such code in later chapters, but here is the gist: • The main form, Form1, is represented in code by a class, named “Form1.” • The form includes a command button named Button1 that exposes a Click event. This event is handled by the Button1_Click procedure, a member of the Form1 class. • The “event handler,” Button1_Click, includes a single statement, a MsgBox state- ment. This statement does the heavy lifting by presenting the ever-friendly mes- sage box to the world. That’s all the code that I wrote for Form1.vb. It sure seems pretty short for all the work it does. There has to be more code hiding somewhere. And sure enough, a half dozen or so additional files are included in the project. Visual Studio hides these by default, since it manages some or all of the content in these files on your behalf. To view the files, click on the Show All Files button (the second toolbar button from the left in the Solution Explorer panel). Look at all those files! To see the additional files associated with Form1, expand it by clicking on the plus sign (+) to its left (see Figure 1-13). Double-click on the Form1.Designer.vb entry to see the code that Visual Studio auto- matically wrote for this form. (Dramatic pause.) Wow! Look at all that scary code. Actually, it’s not that bad. By the end of this book, you will have a firm grasp on all of it. Here in Chapter 1, it’s not really necessary to comprehend it all, but there are a few interesting lines to note. I’m including line numbers to make it easier to find the matching code in Visual Studio. If you want to view line numbers in Visual Studio (Professional Edition instructions listed here): Figure 1-13. Viewing hidden files through the Solution Explorer Click here Then here
Project | 27 1. Select the Tools ➝ Options menu item to display Visual Studio’s options. 2. Select Text Editor ➝ Basic ➝ Editor from the tree view to the left. If the “Show all settings” field is checked, the last component you click in the tree view will be General, not Editor. 3. Select (check) the Line Numbers field on the right. 4. Click OK to apply the changes. If you’re new to Visual Basic or .NET programming, don’t worry now if this code doesn’t make sense; it will all become clear as you pass through the pages of this book. 01 <Global.Microsoft.VisualBasic.CompilerServices. _ DesignerGenerated( )> _ 02 Partial Public Class Form1 20 <System.Diagnostics.DebuggerNonUserCode( )> _ 21 Protected Overloads Overrides Sub Dispose _ (ByVal disposing As Boolean) These lines show attributes in action. These two attributes (DesignerGenerated and DebuggerNonUserCode) are somewhat like the Obsolete attribute discussed earlier, in that they provide some informational identity to the related code. DesignerGenerated modifies the entire section of Form1’s code, whereas DebuggerNonUserCode modifies only the Dispose member. For clarity, both attributes include their full namespace paths. The Global keyword at the beginning of the DesignerGenerated attribute is actually a Visual Basic keyword that says, “Start at the very tippy-top of the namespace hierarchy; this is not a relative path.” 02 Partial Public Class Form1 Did you see the word Partial right there on line 02? I know I did. Hey, wait a minute; “Public Class Form1” also appeared in the Form1.vb file, but without the Partial keyword. Visual Basic 2008 includes a feature that lets you divide a single class (Form1 in this case) among multiple source code files by including the Partial key- word with at least one of the parts. Pretty cool, eh? It allows Visual Studio to add complex initialization code for your form (as found in this Form1.Designer.vb file) without it bothering your main source code file (Form1.vb). 03 Inherits System.Windows.Forms.Form The Inherits keyword defines the inheritance relationship between this new Form1 class and the previously written System.Windows.Forms.Form class. Form is the “base” class and Form1 is the “derived” class; Form1 inherits all the functionality of the Form class, including its initial look and feel. I’ll discuss these class relationships in more detail in Chapter 8. 44 Friend WithEvents Button1 As System.Windows.Forms.Button
28 | Chapter 1: Introducing .NET Line 44 defines the “Go Ahead, Click Me!” button that appears in the center of the form. All controls that appear on your form are separate instances of classes. (Friend is a declaration statement described in Chapter 6.) The WithEvents keyword indi- cates that this instance of the Button class will respond to events, such as a user click- ing on it with the mouse. This line doesn’t actually create an instance of the Button class; that happens back on line 22. 22 Me.Button1 = New System.Windows.Forms.Button The New keyword creates new instances of classes. In this case, that new instance is assigned to the Button1 class member defined on line 44. At this moment, Button1 is a default instance of the Button class; it doesn’t have any of its custom settings, such as its size and position, or the “Go Ahead, Click Me!” display text. All of that is set in lines 27 to 31: 27 Me.Button1.Location = New System.Drawing.Point(64, 104) 28 Me.Button1.Name = "Button1" 29 Me.Button1.Size = New System.Drawing.Size(152, 23) 30 Me.Button1.TabIndex = 0 31 Me.Button1.Text = "Go Ahead, Click Me!" Finally, the button is “glued” onto the form on line 38: 38 Me.Controls.Add(Me.Button1) This adds the Button1 instance to the list of Controls managed by Form1. The Me key- word used throughout this code refers to the Form1 class itself, so Me.Button1 refers to the Button1 class member specifically in the current Form1 class. Most of the code in this file appears in the InitializeComponent member procedure: 21 Private Sub InitializeComponent( ) ... 43 End Sub When Visual Basic creates an instance of Form1 to display on the screen, it calls the InitializeComponent procedure to do the work of adding the controls to the form. Actually, Visual Basic calls the form’s constructor, which in turn calls InitializeComponent. Constructors are special class members that perform any needed initialization on a class instance. They are called automatically by .NET each time a class instance is created. In Visual Basic, all constructors use the name New, as with the following code: Friend Class ClassWithConstructor Public Sub New( ) ' ----- All initialization code goes here. End Sub End Class I’ll talk much more about constructors in Chapter 8, but for now, locate the con- structor in the code for Form1. (Very long pause.) What? There is no constructor? So, if there isn’t a constructor, how is the InitializeComponent member ever called?
Project | 29 That’s what I’d like to know. Actually, when the Visual Basic compiler generates the MSIL code for Form1, it adds a constructor silently, a constructor that calls InitializeComponent. How about that! Why didn’t Microsoft simply include the con- structor’s code right in the source code? It’s a simplicity-for-the-programmer thing. Microsoft needed to have a default constructor that would call InitializeComponent, but it didn’t want a conflict to arise if you added your own default constructor in the non-Designer file. So it hid all the code until it came time to actually compile the form. Clearly, it’s all rather hush-hush, so let’s move on. Well, that’s pretty much the entire code, at least the part that matters to us now. Although we will rarely, if ever, examine the Visual Studio-generated code for the forms in the Library Project, it’s good to see what’s going on behind the scenes. If you were a Visual Basic 6 programmer, you probably looked at the source code for your forms through Notepad at one time or another. If you did, you noticed that the form and all its controls were defined with a hierarchy of special commands, and not with actual Visual Basic code. In .NET, that’s all changed; the form and all its con- trols are created with ordinary Visual Basic code, so you can access it all and see what is really going on. Now, turn to Chapter 2, where I delve into the Visual Basic language itself.
30 Chapter 2 CHAPTER 2 Introducing Visual Basic 2 It was a dark and stormy night. Hector gazed wearily through his bloodshot eyes, through the black-rimmed corrective lenses, and through the haze of the fluorescent overhead lights at the phosphor-enriched display. Had it really been four months since he started the six-month project? Did his boss really threaten to fire him after seeing his progress? It seemed like all of those MS-DOS programs he had written for the company over the years meant nothing. Why did he promise to port the com- pany’s main internal system to Windows? In a moment of despair, tears streamed down his cheeks, diluting his last remaining can of Jolt Cola. It’s 8:00 a.m. A loud thump on Hector’s desk brings him suddenly out of his slum- ber, the drool still trickling from the corner of his mouth. What’s that? What’s that box on his desk? “V-i-s-u-a-l B-a-s-i-c?” A note on the box says to rewrite his code in “this.” Desperate to try anything, Hector installs the three floppy disks on his ’386 powerhouse. Six weeks later, Hector has completed the project, ahead of schedule, feature-complete, and with the accolades of his boss and department. And it’s all due to Visual Basic. But VB didn’t just improve his programming life. Overall, he’s happier, has kicked the caffeine habit, is able to bench-press 300 pounds, no longer walks with a limp, has increased libido, and has whiter teeth. “Thank you, Visual Basic 1.0!” The History of the Visual Basic Revolution It’s possible that I got a few of the details wrong in Hector’s life. But for many busi- ness developers, Visual Basic 1.0 was a breath of fresh air. It’s not that they could do more with Visual Basic; programs written in C were more powerful and had greater flexibility. But business programmers didn’t always need that flexibility back in the transition from MS-DOS. They just wanted to manage data, and they didn’t want to worry about how to present every little pixel on the screen. Visual Basic provided the tools to write applications quickly and with much less effort than that required by other Windows development tools and languages.
The History of the Visual Basic Revolution | 31 Visual Basic’s simplicity was embraced by developers everywhere, but the honey- moon quickly wore off. Given the speed at which programs of reasonable quality could be cranked out with Visual Basic, programmers and businesses began demand- ing more. And Microsoft responded. Visual Basic 2.0 and 3.0 were released in quick succession in 1992 and 1993, providing enhanced database integration and addi- tional visual development features. Version 4.0, released in 1996, introduced 32-bit programming to the language, and support for the already-popular Windows 95 platform. Two more quick releases—Visual Basic 5.0 in 1997 and Visual Basic 6.0 in 1998—added even more features and complexity to the otherwise “basic” language, features supporting some but not all object-oriented programming (OOP) tech- niques, ActiveX control development, and web-based logic coding. Microsoft had even integrated the core Visual Basic engine—christened Visual Basic for Applications, or VBA—into its suite of Office products, proclaiming it as the new official macro lan- guage and making the engine available to any third party that wanted to do the same. Seven years after its initial introduction, Visual Basic had taken the programming world by storm. Millions of developers were using the language, including in-house developers at Fortune 500 companies, writing applications that supported core busi- ness functions. VB still retained some of the flavor of the original BASIC language—a “beginner’s” programming language developed by John Kemeny and Thomas Kurtz at Dartmouth College back in 1963. This caused no end of snickering from C and C++ developers and other cola addicts. But VB programmers could see a powerful future for their language of choice. Then the unthinkable happened. Microsoft announced that it would no longer enhance the core Visual Basic engine. Instead, it would rewrite and reimplement Visual Basic using its soon-to-be-released .NET development platform. Yes, Visual Basic would be endowed with all the power promised for Microsoft’s new C- and Java-like language, C#. But for many hardcore VB developers, it was wrong, just wrong. Words were exchanged. Petitions were crafted. Letters to the editor sounded the call to the Visual Basic faithful, urging them to never write a single line of Visual Basic .NET code, ever. In frustration, a Visual Basic user’s group set fire to the entire Microsoft campus in Redmond. Well, that didn’t happen. In fact, nothing bad happened at all. Visual Basic .NET turned out to be a software wunderkind, providing power and features that far sur- passed anything available in Visual Basic 6.0. Its initial release in 2002 was proof that. Visual Basic .NET 2002 was powerful, but it was also a little hard to use, at least compared with version 6.0, and especially when compared with the original 1.0 product. Visual Basic .NET 2003, released just a year later (obviously), was a rela- tively minor update with not much in the way of new or easier functionality. Visual Basic 2005 marked a return to the simpler days of Visual Basic development, days of harmony and peace between “newbies” and their general-purpose program- ming language. Not only did Microsoft remove the term “.NET” from the product
32 | Chapter 2: Introducing Visual Basic name, but it also removed some of the barriers that kept entry-level programmers from approaching the language. Pre-.NET features, such as Edit and Continue and the display of forms through the simple use of the form’s name, once again found their way into the language and into the hearts of software engineers. Visual Basic still retained all the power it gained with .NET, but with true improvements in usability. It was like when they add a label to your toothpaste that says, “New pack- age, same great regular flavor!” Except that Visual Basic’s flavor was improved, too. Visual Basic was once again accessible to first-time developers. Since the 2005 release, Microsoft hasn’t just been sitting on its laurels, as painful as that would be. It dug into its bag of tricks with both hands and came out with Visual Basic 2008, the latest VB offering. Formerly code-named Orcas, Visual Basic 2008 brings additional power and simplicity—yes, both of those—to the language. The biggest new feature, LINQ, makes data access easier by letting you tell the system what data you want instead of detailing how to obtain that data. The language also pro- vides more direct access to new technologies such as Ajax and the Windows Presenta- tion Foundation (WPF). But enough fawning. Let’s start learning about the language. Visual Basic from the Inside Out As a general-purpose development language, Visual Basic includes gobs of features that allow you to develop just about any type of application supported by the Microsoft Windows platform. As such, all of its features could never be covered in a concise, 20- or 30-page chapter, and I won’t try. What I will do in this chapter is to introduce you to the basics of the language, and its core features. Features not cov- ered in this chapter are discussed throughout the rest of the book. It has to be that way, since I don’t want you to finish this chapter and then say to yourself, “That Tim Patrick is so amazing. I learned all I needed to know about Visual Basic in one chap- ter; I didn’t even have to read the rest of the book.” My publisher would not be amused. In the remainder of this chapter, I will take the “from the inside out” approach, start- ing the discussion with the core concepts of logic and data, and adding layer after layer of Visual Basic functionality as you turn the pages. The Basics of Logic and Data Lest you forget it, let me remind you again: computers are not really very smart. They know how to do only the simplest of tasks. If you want them to do anything remotely complex, you have to give precise, step-by-step instructions down to moving individual bits of data—only 1s and 0s, remember—around in memory.
The Basics of Logic and Data | 33 Fortunately, most of the code you would ever need at that low level has already been written for you, and incorporated into the Windows operating system and the .NET Framework. Microsoft- and third-party-supplied code libraries give you a lot of pre- written functionality that’s available for use in your own programs. And that’s good, because you would rather be hurtled into space on a giant bungee cord than have to write business applications at the machine code level all day long. Even though you have all this great prewritten code in your arsenal, you still have to tell the computer precisely what you want it to do, in fine detail, or it won’t do it. And that’s where high-level languages like Visual Basic come in. They provide the grammar you need to communicate with the computer. For any given tasks that the computer needs to perform, your job as a programmer is to determine the individual steps to accomplish that task—the logic—and translate those steps into computer- ese using the programming language. As an example, let’s say you receive a request from the sales department for a pro- gram that will reverse all the letters in any chunk of text provided to the program. “Our customers are clamoring for this; we need it by Tuesday,” they say. OK, so first you figure out the logic, and then you implement it in Visual Basic. Using pseudocode, an artificial programming language that you make up yourself to help you write programs, you can sketch out the basics of this task (with leading line numbers): 01 Obtain the original text (or string) from the user. 02 If the user didn't supply any content, then quit now. 03 Prepare a destination for the reversed string, empty for now. 04 Repeat the following until the original string is empty: 05 Copy the last character from the remaining original string. 06 Put that character onto the end of the destination string. 07 Shorten the original string, dropping the last character. 08 [End of repeat section] 09 Show the user the destination string. You could write this logic in many ways; this is just one example. You can now con- vert this pseudocode into your language of choice; in this case, Visual Basic (don’t worry about the syntax details for now): 01 originalText = InputBox("Enter text to reverse.") 02 If (Len(originalText) = 0) Then Return 03 finalText = "" 04 Do While (originalText <> "") 05 oneCharacter = Right(originalText, 1) 06 finalText &= oneCharacter 07 originalText = Left(originalText, _ Len(originalText) - 1) 08 Loop 09 MsgBox("The reverse is: " & finalText)
34 | Chapter 2: Introducing Visual Basic This source code is now ready to be used in a Visual Basic program. And it also dem- onstrates several essential aspects of coding: • The individual steps of the step-by-step instructions are called statements. In Visual Basic, each statement appears on a line by itself. You can break long state- ments into multiple lines by connecting the lines with a space-underscore pair, as shown in line 07 of the code. When a single statement is spread across multi- ple lines in this manner, the entire statement is sometimes called a logical line. Since a single logical line often includes only a single primary Visual Basic action (such as the If or Do action, or the various assignment actions using the equals sign [=]), these actions are also referred to as statements. • The statements of the code are processed one at a time, from top to bottom. However, certain statements alter the normal top-to-bottom flow of the pro- gram, as is done with the Do While...Loop block on lines 04 and 08 of the sam- ple code. Such statements are called flow control statements, and include loops (repeating a block of code), conditions (optionally processing a block of code based on a comparison or calculated result), and jumps (moving immediately to some other section of the code). • Data can be stored in variables, which are named containers for data values. The sample code block includes three variables: originalText, oneCharacter, and finalText, all of which store text (string) data. The .NET Common Type System (CTS) allows you to create variables for four primary types of basic data values: text (both single characters and longer strings), numbers (both integer and deci- mal values), dates (and times), and Booleans (true or false values). You can also build more complex types of data by grouping the basic types. • Data is stored in a variable through an assignment. Generally, this involves plac- ing a variable name on the left side of an = assignment operator, and putting the data or calculation to store in that variable on the right side of that same equals sign. The statement finalText = "" on line 03 stores an empty string ("") in the variable finalText. The &= assignment statement on line 06 shows a slightly dif- ferent assignment syntax. • Statements can include function calls, blocks of prewritten functionality, all squished down into a single name. Function calls do a bunch of work, and then return a final result, a data value. Function names are followed by a set of paren- theses, which may include zero or more arguments, additional data values sup- plied by the calling code that the function uses to generate its result. The sample code includes many examples of function calls, including the Right function on line 05. This function returns a copy of the rightmost characters from another text string. It accepts two parameters: the original string from which to extract the rightmost characters, and an integer value indicating the number of characters to return. The code Right(originalText, 1) returns a copy of the rightmost single character (1) from originalText.
Another Random Scribd Document with Unrelated Content
according to his deeds; for he cast his spear against this holy thing, and now the gods have slain him.” Then all cried out together that the Horse of wood must be drawn to the citadel. Whereupon they opened the Scæan Gate, and pulled down the wall that was thereby, and put rollers under the feet of the Horse, and joined ropes thereto. So, in much joy, they drew it into the city, youths and maidens singing about it the while, and laying their hands to the ropes with great gladness. And yet there wanted not signs and tokens of evil to come. Four times it halted on the threshold of the gate, and men might have heard a clashing of arms within. Cassandra also opened her mouth, prophesying evil: but no man heeded her, for that was ever the doom upon her, not to be believed speaking truth. So the men of Troy drew the Horse into the city. And that night they kept a feast to all the gods with great joy, not knowing that the last day of the great city had come. But when night was now fully come, and the men of Troy lay asleep, lo! from the ship of King Agamemnon there rose up a flame for a signal to the Greeks; and these straightway manned their ships, and made across the sea from Tenedos, there being a great calm, and the moon also giving them light. Sinon likewise opened a secret door that was in the great Horse, and the chiefs issued forth therefrom, and opened the gates of the city, slaying those that kept watch. Meanwhile there came a vision to Æneas, who now, Hector being dead, was the chief hope and stay of the men of Troy. It was Hector’s self that he seemed to see, but not such as he had seen him coming back rejoicing with the arms of Achilles, or setting fire to the ships, but even as he lay after that Achilles dragged him at his chariot wheels, covered with dust and blood, his feet swollen and pierced through with thongs. To him said Æneas, not knowing what he said, “Why hast thou tarried so long? Much have we suffered waiting for thee! And what grief hath marked thy face? and whence these wounds?”
But to this the spirit answered nothing, but said, groaning the while, “Fly, son of Venus, fly, and save thee from these flames. The enemy is in the walls, and Troy hath utterly perished. If any hand could have saved our city, this hand had done so. Thou art now the hope of Troy. Take then her gods, and flee with them for company, seeking the city that thou shalt one day build across the sea.” And now the alarm of battle came nearer and nearer, and Æneas, waking from sleep, climbed upon the roof, and looked on the city. As a shepherd stands, and sees a fierce flame sweeping before the south wind over the cornfields or a flood rushing down from the mountains, so he stood. And as he looked, the great palace of Deïphobus sank down in the fire, and the house of Ucalegon, that was hard by, blazed forth, till the sea by Sigeüm shone with the light. Then, scarce knowing what he sought, he girded on his armor, thinking, perchance, that he might yet win some place of vantage, or, at the least, might avenge himself on the enemy, or find honor in his death. But as he passed from out of his house there met him Panthus, the priest of Apollo that was on the citadel, who cried to him, “O Æneas, the glory is departed from Troy, and the Greeks have the mastery in the city; for armed men are coming forth from the great Horse of wood, and thousands also swarm in at the gates, which Sinon hath treacherously opened.” And as he spake others came up under the light of the moon, as Hypanis, and Dymas, and young Corœbus, who had but newly come to Troy, seeking Cassandra to be his wife. To whom Æneas spake: “If ye are minded, my brethren, to follow me to the death, come on. For how things fare this night ye see. The gods who were the stay of this city have departed from it; nor is aught remaining to which we may bring succor. Yet can we die as brave men in battle. And haply he that counts his life to be lost may yet save it.” Then, even as ravening wolves hasten through the mist seeking for prey, so they went through the city, doing dreadful deeds. And for a while the men of Greece fled before them.
First of all there met them Androgeos with a great company following him, who, thinking them to be friends, said, “Haste, comrades, why are ye so late? We are spoiling this city of Troy, and ye are but newly come from the ships.” But forthwith, for they answered him not as he had looked for, he knew that he had fallen among enemies. Then even as one who treads upon a snake unawares among thorns, and flies from it when it rises angrily against him with swelling neck, so Androgeos would have fled. But the men of Troy rushed on, and seeing that they knew all the place, and that great fear was upon the Greeks, slew many men. Then said Corœbus, “We have good luck in this matter, my friends. Come now, let us change our shields, and put upon us the armor of these Greeks. For whether we deal with our enemy by craft or by force, who will ask?” Then he took to himself the helmet and shield of Androgeos, and also girded the sword upon him. In like manner did the others, and thus going disguised among the Greeks slew many, so that some again fled to the ships and some were fain to climb into the Horse of wood. But lo! men came dragging by the hair from the temple of Minerva the virgin Cassandra, whom when Corœbus beheld, and how she lifted up her eyes to heaven (but as for her hands, they were bound with iron), he endured not the sight, but threw himself upon those that dragged her, the others following him. Then did a grievous mischance befall them, for the men of Troy that stood upon the roof of the temple cast spears against them, judging them to be enemies. The Greeks also, being wroth that the virgin should be taken from them, fought the more fiercely, and many who had before been put to flight in the city came against them, and prevailed, being indeed many against few. Then first of all fell Corœbus, being slain by Peneleus the Bœotian, and Rhipeus also, the most righteous of all the sons of Troy. But the gods dealt not with him after his righteousness. Hypanis also was slain and Dymas, and Panthus escaped not for all that more than other men he feared the gods and was also the priest of Apollo. Then was Æneas severed from the rest, having with him two only, Iphitus and Pelias, Iphitus being an old man and Pelias sorely
wounded by Ulysses. And these, hearing a great shouting, hastened to the palace of King Priam, where the battle was fiercer than in any place beside. For some of the Greeks were seeking to climb the walls, laying ladders thereto, whereon they stood, holding forth their shields with their left hands, and with their right grasping the roofs. And the men of Troy, on the other hand, being in the last extremity, tore down the battlements and the gilded beams wherewith the men of old had adorned the palace. Then Æneas, knowing of a secret door whereby the unhappy Andromaché in past days had been wont to enter, bringing her son Astyanax to his grandfather, climbed on to the roof, and joined himself to those that fought therefrom. Now upon this roof there was a tower, whence all Troy could be seen and the camp of the Greeks and the ships. This the men of Troy loosened from its foundations with bars of iron, and thrust it over, so that it fell upon the enemy, slaying many of them. But not the less did others press forward, casting the while stones and javelins and all that came to their hands. Meanwhile others sought to break down the gates of the palace, Pyrrhus, son of Achilles, being foremost among them, clad in shining armor of bronze. Like to a serpent was he, which sleeps indeed during the winter, but in the spring comes forth into the light, full fed on evil herbs, and, having cast his skin and renewed his youth, lifts his head into the light of the sun and hisses with forked tongue. And with Pyrrhus were tall Periphas, and Automedon, who had been armor-bearer to his father Achilles, and following them the youth of Scyros, which was the kingdom of his grandfather Lycomedes. With a great battle-axe he hewed through the doors, breaking down also the door-posts, though they were plated with bronze, making, as it were, a great window, through which a man might see the palace within, the hall of King Priam and of the kings who had reigned aforetime in Troy. But when they that were within perceived it, there arose a great cry of women wailing aloud and clinging to the doors and kissing them. But ever Pyrrhus pressed on, fierce and strong as ever was his father Achilles, nor could aught stand against him, either the doors or they that guarded them. Then, as a river bursts
its banks and overflows the plain, so did the sons of Greece rush into the palace. But old Priam, when he saw the enemy in his hall, girded on him his armor, which now by reason of old age he had long laid aside, and took a spear in his hand, and would have gone against the adversary, only Queen Hecuba called to him from where she sat. For she and her daughters had fled to the great altar of the household gods, and sat crowded about it like unto doves that are driven by a storm. Now the altar stood in an open court that was in the midst of the palace, with a great bay-tree above it. So when she saw Priam, how he had girded himself with armor as a youth, she cried to him and said, “What hath bewitched thee, that thou girdest thyself with armor? It is not the sword that shall help us this day; no, not though my own Hector were here, but rather the gods and their altars. Come hither to us, for here thou wilt be safe, or at the least wilt die with us.” So she made the old man sit down in the midst. But lo! there came flying through the palace, Polites, his son, wounded to death by the spear of Pyrrhus, and Pyrrhus close behind him. And he, even as he came into the sight of his father and his mother, fell dead upon the ground. But when King Priam saw it he contained not himself, but cried aloud, “Now may the gods, if there be any justice in heaven, recompense thee for this wickedness, seeing that thou hast not spared to slay the son before his father’s eyes. Great Achilles, whom thou falsely callest thy sire, did not thus to Priam, though he was an enemy, but reverenced right and truth, and gave the body of Hector for burial, and sent me back to my city.” And as he spake the old man cast a spear, but aimless and without force, and that pierced not even the boss of the shield. Then said the son of Achilles, “Go thou and tell my father of his unworthy son and all these evil deeds. And that thou mayest tell him, die!” And as he spake he caught in his left hand the old man’s white hair, and dragged him, slipping the while in the blood of his own son, to the altar, and then, lifting his sword high for a blow, drave it to the
hilt in the old man’s side. So King Priam, who had ruled mightily over many peoples and countries in the land of Asia, was slain that night, having first seen Troy burning about him, and his citadel laid even with the ground. So was his carcase cast out upon the earth, headless, and without a name.
CHAPTER VIII. THE ADVENTURES OF ULYSSES. When the great city of Troy was taken, all the chiefs who had fought against it set sail for their homes. But there was wrath in heaven against them, for indeed they had borne themselves haughtily and cruelly in the day of their victory. Therefore they did not all find a safe and happy return. For one was shipwrecked, and another was shamefully slain by his false wife in his palace, and others found all things at home troubled and changed, and were driven to seek new dwellings elsewhere. And some, whose wives and friends and people had been still true to them through those ten long years of absence, were driven far and wide about the world before they saw their native land again. And of all, the wise Ulysses was he who wandered farthest and suffered most. He was well-nigh the last to sail, for he had tarried many days to do pleasure to Agamemnon, lord of all the Greeks. Twelve ships he had with him—twelve he had brought to Troy—and in each there were some fifty men, being scarce half of those that had sailed in them in the old days, so many valiant heroes slept the last sleep by Simoïs and Scamander, and in the plain on the sea-shore, slain in battle or by the shafts of Apollo. First they sailed north-west to the Thracian coast, where the Ciconians dwelt, who had helped the men of Troy. Their city they took, and in it much plunder, slaves and oxen, and jars of fragrant wine, and might have escaped unhurt, but that they stayed to hold
revel on the shore. For the Ciconians gathered their neighbors, being men of the same blood, and did battle with the invaders, and drove them to their ship. And when Ulysses numbered his men, he found that he had lost six out of each ship. Scarce had he set out again when the wind began to blow fiercely; so, seeing a smooth sandy beach, they drave the ships ashore and dragged them out of reach of the waves, and waited till the storm should abate. And the third morning being fair, they sailed again, and journeyed prosperously till they came to the very end of the great Peloponnesian land, where Cape Malea looks out upon the southern sea. But contrary currents baffled them, so that they could not round it, and the north wind blew so strongly that they must fain drive before it. And on the tenth day they came to the land where the lotus grows—a wondrous fruit, of which whosoever eats cares not to see country or wife or children again. Now the Lotus-eaters, for so they called the people of the land, were a kindly folk, and gave of the fruit to some of the sailors, not meaning them any harm, but thinking it to be the best that they had to give. These, when they had eaten, said that they would not sail any more over the sea; which, when the wise Ulysses heard, he bade their comrades bind them and carry them, sadly complaining, to the ships. Then, the wind having abated, they took to their oars, and rowed for many days till they came to the country where the Cyclopes dwell. Now, a mile or so from the shore there was an island, very fair and fertile, but no man dwells there or tills the soil, and in the island a harbor where a ship may be safe from all winds, and at the head of the harbor a stream falling from a rock, and whispering alders all about it. Into this the ships passed safely, and were hauled up on the beach, and the crews slept by them, waiting for the morning. And the next day they hunted the wild goats, of which there was great store on the island, and feasted right merrily on what they caught, with draughts of red wine which they had carried off from the town of the Ciconians.
But on the morrow, Ulysses, for he was ever fond of adventure, and would know of every land to which he came what manner of men they were that dwelt there, took one of his twelve ships and bade row to the land. There was a great hill sloping to the shore, and there rose up here and there a smoke from the caves where the Cyclopes dwelt apart, holding no converse with each other, for they were a rude and savage folk, but ruled each his own household, not caring for others. Now very close to the shore was one of these caves, very huge and deep, with laurels round about the mouth, and in front a fold with walls built of rough stone, and shaded by tall oaks and pines. So Ulysses chose out of the crew the twelve bravest, and bade the rest guard the ship, and went to see what manner of dwelling this was, and who abode there. He had his sword by his side, and on his shoulder a mighty skin of wine, sweet-smelling and strong, with which he might win the heart of some fierce savage, should he chance to meet with such, as indeed his prudent heart forecasted that he might. So they entered the cave, and judged that it was the dwelling of some rich and skilful shepherd. For within there were pens for the young of the sheep and of the goats, divided all according to their age, and there were baskets full of cheeses, and full milkpails ranged along the wall. But the Cyclops himself was away in the pastures. Then the companions of Ulysses besought him that he would depart, taking with him, if he would, a store of cheeses and sundry of the lambs and of the kids. But he would not, for he wished to see, after his wont, what manner of host this strange shepherd might be. And truly he saw it to his cost! It was evening when the Cyclops came home, a mighty giant, twenty feet in height, or more. On his shoulder he bore a vast bundle of pine logs for his fire, and threw them down outside the cave with a great crash, and drove the flocks within, and closed the entrance with a huge rock, which twenty wagons and more could not bear. Then he milked the ewes and all the she-goats, and half of the milk he curdled for cheese, and half he set ready for himself, when he should sup. Next he kindled a fire with the pine logs, and
the flame lighted up all the cave, showing him Ulysses and his comrades. “Who are ye?” cried Polyphemus, for that was the giant’s name. “Are ye traders, or, haply, pirates?” For in those days it was not counted shame to be called a pirate. Ulysses shuddered at the dreadful voice and shape, but bore him bravely, and answered, “We are no pirates, mighty sir, but Greeks, sailing back from Troy, and subjects of the great King Agamemnon, whose fame is spread from one end of heaven to the other. And we are come to beg hospitality of thee in the name of Zeus, who rewards or punishes hosts and guests according as they be faithful the one to the other, or no.” “Nay,” said the giant, “it is but idle talk to tell me of Zeus and the other gods. We Cyclopes take no account of gods, holding ourselves to be much better and stronger than they. But come, tell me where have you left your ship?” But Ulysses saw his thought when he asked about the ship, how he was minded to break it, and take from them all hope of flight. Therefore he answered him craftily,— “Ship have we none, for that which was ours King Poseidon brake, driving it on a jutting rock on this coast, and we whom thou seest are all that are escaped from the waves.” Polyphemus answered nothing, but without more ado caught up two of the men, as a man might catch up the whelps of a dog, and dashed them on the ground, and tore them limb from limb, and devoured them, with huge draughts of milk between, leaving not a morsel, not even the very bones. But the others, when they saw the dreadful deed, could only weep and pray to Zeus for help. And when the giant had ended his foul meal, he lay down among his sheep and slept. Then Ulysses questioned much in his heart whether he should slay the monster as he slept, for he doubted not that his good sword
would pierce to the giant’s heart, mighty as he was. But, being very wise, he remembered that, should he slay him, he and his comrades would yet perish miserably. For who should move away the great rock that lay against the door of the cave? So they waited till the morning. And the monster woke, and milked his flocks, and afterwards, seizing two men, devoured them for his meal. Then he went to the pastures, but put the great rock on the mouth of the cave, just as a man puts down the lid upon his quiver. All that day the wise Ulysses was thinking what he might best do to save himself and his companions, and the end of his thinking was this: there was a mighty pole in the cave, green wood of an olive tree, big as a ship’s mast, which Polyphemus purposed to use, when the smoke should have dried it, as a walking staff. Of this he cut off a fathom’s length, and his comrades sharpened it and hardened it in the fire, and then hid it away. At evening the giant came back, and drove his sheep into the cave, nor left the rams outside, as he had been wont to do before, but shut them in. And having duly done his shepherd’s work, he made his cruel feast as before. Then Ulysses came forward with the wine-skin in his hand, and said,— “Drink, Cyclops, now that thou hast feasted. Drink and see what precious things we had in our ship. But no one hereafter will come to thee with such like, if thou dealest with strangers as cruelly as thou hast dealt with us.” Then the Cyclops drank, and was mightily pleased, and said, “Give me again to drink, and tell me thy name, stranger, and I will give thee a gift such as a host should give. In good truth this is a rare liquor. We, too, have vines, but they bear not wine like this, which indeed must be such as the gods drink in heaven.” Then Ulysses gave him the cup again, and he drank. Thrice he gave it to him, and thrice he drank, not knowing what it was, and how it would work within his brain. Then Ulysses spake to him. “Thou didst ask my name, Cyclops. Lo! my name is No Man. And now that thou knowest my name, thou
shouldst give me thy gift.” And he said, “My gift shall be that I will eat thee last of all thy company.” And as he spoke he fell back in a drunken sleep. Then Ulysses bade his comrades be of good courage, for the time was come when they should be delivered. And they thrust the stake of olive wood into the fire till it was ready, green as it was, to burst into flame, and they thrust it into the monster’s eye; for he had but one eye, and that in the midst of his forehead, with the eyebrow below it. And Ulysses leant with all his force upon the stake, and thrust it in with might and main. And the burning wood hissed in the eye, just as the red-hot iron hisses in the water when a man seeks to temper steel for a sword. Then the giant leapt up, and tore away the stake, and cried aloud, so that all the Cyclopes who dwelt on the mountain side heard him and came about his cave, asking him, “What aileth thee, Polyphemus, that thou makest this uproar in the peaceful night, driving away sleep? Is any one robbing thee of thy sheep, or seeking to slay thee by craft or force?” And the giant answered, “No Man slays me by craft.” “Nay, but,” they said, “if no man does thee wrong, we cannot help thee. The sickness which great Zeus may send, who can avoid? Pray to our father, Poseidon, for help.” Then they departed; and Ulysses was glad at heart for the good success of his device, when he said that he was No Man. But the Cyclops rolled away the great stone from the door of the cave, and sat in the midst, stretching out his hands to feel whether perchance the men within the cave would seek to go out among the sheep. Long did Ulysses think how he and his comrades should best escape. At last he lighted upon a good device, and much he thanked Zeus for that this once the giant had driven the rams with the other
sheep into the cave. For, these being great and strong, he fastened his comrades under the bellies of the beasts, tying them with osier twigs, of which the giant made his bed. One ram he took, and fastened a man beneath it, and two others he set, one on either side. So he did with the six, for but six were left out of the twelve who had ventured with him from the ship. And there was one mighty ram, far larger than all the others, and to this Ulysses clung, grasping the fleece tight with both his hands. So they waited for the morning. And when the morning came, the rams rushed forth to the pasture; but the giant sat in the door and felt the back of each as it went by, nor thought to try what might be underneath. Last of all went the great ram. And the Cyclops knew him as he passed, and said,— “How is this, thou, who art the leader of the flock? Thou art not wont thus to lag behind. Thou hast always been the first to run to the pastures and streams in the morning, and the first to come back to the fold when evening fell; and now thou art last of all. Perhaps thou art troubled about thy master’s eye, which some wretch—No Man, they call him—has destroyed, having first mastered me with wine. He has not escaped, I ween. I would that thou couldst speak, and tell me where he is lurking. Of a truth I would dash out his brains upon the ground, and avenge me of this No Man.” So speaking, he let him pass out of the cave. But when they were out of reach of the giant, Ulysses loosed his hold of the ram, and then unbound his comrades. And they hastened to their ship, not forgetting to drive before them a good store of the Cyclops’ fat sheep. Right glad were those that had abode by the ship to see them. Nor did they lament for those that had died, though they were fain to do so, for Ulysses forbade, fearing lest the noise of their weeping should betray them to the giant, where they were. Then they all climbed into the ship, and sitting well in order on the benches, smote the sea with their oars, laying-to right lustily, that they might the sooner get away from the accursed land. And when they had rowed a hundred yards or so, so that a man’s voice could
yet be heard by one who stood upon the shore, Ulysses stood up in the ship and shouted,— “He was no coward, O Cyclops, whose comrades thou didst so foully slay in thy den. Justly art thou punished, monster, that devourest thy guests in thy dwelling. May the gods make thee suffer yet worse things than these!” Then the Cyclops, in his wrath, broke off the top of a great hill, a mighty rock, and hurled it where he had heard the voice. Right in front of the ship’s bow it fell, and a great wave rose as it sank, and washed the ship back to the shore. But Ulysses seized a long pole with both hands and pushed the ship from the land, and bade his comrades ply their oars, nodding with his head, for he was too wise to speak, lest the Cyclops should know where they were. Then they rowed with all their might and main. And when they had gotten twice as far as before, Ulysses made as if he would speak again; but his comrades sought to hinder him, saying, “Nay, my lord, anger not the giant any more. Surely we thought before we were lost, when he threw the great rock, and washed our ship back to the shore. And if he hear thee now, he may crush our ship and us, for the man throws a mighty bolt, and throws it far.” But Ulysses would not be persuaded, but stood up and said, “Hear, Cyclops! If any man ask who blinded thee, say that it was the warrior Ulysses, son of Laertes, dwelling in Ithaca.” And the Cyclops answered with a groan, “Of a truth, the old oracles are fulfilled, for long ago there came to this land one Telemus, a prophet, and dwelt among us even to old age. This man foretold to me that one Ulysses would rob me of my sight. But I looked for a great man and a strong, who should subdue me by force, and now a weakling has done the deed, having cheated me with wine. But come thou hither, Ulysses, and I will be a host indeed to thee. Or, at least, may Poseidon give thee such a voyage to thy
home as I would wish thee to have. For know that Poseidon is my sire. May be that he may heal me of my grievous wound.” And Ulysses said, “Would to God I could send thee down to the abode of the dead, where thou wouldst be past all healing, even from Poseidon’s self.” Then Cyclops lifted up his hands to Poseidon and prayed,— “Hear me, Poseidon, if I am indeed thy son and thou my father. May this Ulysses never reach his home! or, if the Fates have ordered that he should reach it, may he come alone, all his comrades lost, and come to find sore trouble in his house!” And as he ended he hurled another mighty rock, which almost lighted on the rudder’s end, yet missed it as by a hair’s breadth. So Ulysses and his comrades escaped, and came to the island of the wild goats, where they found their comrades, who indeed had waited long for them, in sore fear lest they had perished. Then Ulysses divided amongst his company all the sheep which they had taken from the Cyclops. And all, with one consent, gave him for his share the great ram which had carried him out of the cave, and he sacrificed it to Zeus. And all that day they feasted right merrily on the flesh of sheep and on sweet wine, and when the night was come, they lay down upon the shore and slept. After sailing awhile, they came to the island of Æolus, who is the king of the winds, and who dwelt there with his children, six sons and six daughters. Right well did Æolus entertain them, feasting them royally for a whole month, while he heard from Ulysses the story of all that had been done at Troy. And when Ulysses prayed him that he would help him on his way homewards, Æolus hearkened to him, and gave him the skin of an ox in which he had bound all contrary winds, so that they should not hinder him. But he let a gentle west wind blow, that it might carry him and his comrades to their home. For nine days it blew and now they were near to Ithaca, their country, so that they saw lights burning in it, it being night-time. But now, by an ill chance, Ulysses fell asleep, being
wholly wearied out, for he had held the helm for nine days, nor trusted it to any of his comrades. And while he slept his comrades, who had cast eyes of envy on the great ox-hide, said one to another,— “Strange it is how men love and honor this Ulysses whithersoever he goes. And now he comes back from Troy with much spoil, but we with empty hands. Let us see what it is that Æolus hath given, for doubtless in this ox-hide is much silver and gold.” So they loosed the great bag of ox-hide, and lo! all the winds rushed out, and carried them far away from their country. But Ulysses, waking with the tumult, doubted much whether he should not throw himself into the sea and so die. But he endured, thinking it better to live. Only he veiled his face and so sat, while the ships drave before the winds, till they came once more to the island of Æolus. Then Ulysses went to the palace of the king, and found him feasting with his wife and children, and sat him down on the threshold. Much did they wonder to see him, saying, “What evil power has hindered thee, that thou didst not reach thy country and home?” Then he answered, “Blame not me, but the evil counsels of my comrades, and sleep, which mastered me to my hurt. But do ye help me again.” But they said, “Begone; we may not help him whom the gods hate; and hated of them thou surely art.” So Æolus sent him away. Then again they launched their ships and set forth, toiling wearily at the oars, and sad at heart. Six days they rowed, nor rested at night, and on the seventh they came to Lamos, which was a city of the Læstrygons, in whose land the night is as the day, so that a man might earn double wage, if only he wanted not sleep—shepherd by day and herdsman by night. There was a fair haven with cliffs about it, and a narrow
mouth with great rocks on either side. And within are no waves, but always calm. Now Ulysses made fast his ship to the rocks, but the others entered the haven. Then he sent two men and a herald with them, and these came upon a smooth road by which waggons brought down wood from the mountain to the city. Here they met a maiden, the stalwart daughter of Antiphates, king of the land, and asked of her who was lord of that country. Whereupon she showed them her father’s lofty palace. And they, entering this, saw the maiden’s mother, big as a mountain, horrible to behold, who straightway called to Antiphates, her husband. The messengers, indeed, fled to the ships; but he made a great shout, and the Læstrygons came flocking about him, giants, not men. And these broke off great stones from the cliffs, each stone as much as a man could carry, and cast them at the ships, so that they were broken. And the men they speared, as if they were fishes, and devoured them. So it happened to all the ships in the haven. Ulysses only escaped, for he cut the hawser with his sword, and bade his men ply their oars, which indeed they did right willingly. After a while they came to the island of Ææa, where Circé dwelt, who was the daughter of the Sun. Two days and nights they lay upon the shore in great trouble and sorrow. On the third, Ulysses took his spear and sword and climbed a hill that there was, for he wished to see to what manner of land they had come. And having climbed it, he saw the smoke rising from the palace of Circé, where it stood in the midst of a wood. Then he thought awhile: should he go straightway to the palace that he saw, or first return to his comrades on the shore? And this last seemed better; and it chanced that as he went he saw a great stag which was going down to the river to drink, for indeed the sun was now hot, and casting his spear at it he pierced it through. Then he fastened together the feet with green withes and a fathom’s length of rope, and slinging the beast round his neck, so carried it to the ship, leaning on his spear; for indeed it was heavy to bear, nor could any man have carried it on the shoulder with one hand. And when he was come to the ship, he
cast down his burden. Now the men were sitting with their faces muffled, so sad were they. But when he bade them be of good cheer, they looked up and marvelled at the great stag. And all that day they feasted on deer’s flesh and sweet wine, and at night lay down to sleep on the shore. But when morning was come, Ulysses called them all together and spake,— “I know not, friends, where we are. Only I know, having seen smoke yesterday from the hill, that there is a dwelling in this island.” It troubled the men much to hear this, for they thought of the Cyclops and of the Læstrygons; and they wailed aloud, but there was no counsel in them. Wherefore Ulysses divided them into two companies, setting Eurylochus over the one and himself over the other, and shook lots in a helmet who should go and search out the island, and the lot of Eurylochus leapt out. So he went, and comrades twenty and two with him. And in an open space in the wood they found the palace of Circé. All about were wolves and lions; yet these harmed not the men, but stood up on their hind legs, fawning upon them, as dogs fawn upon their master when he comes from his meal. And the men were afraid. And they stood in the porch and heard the voice of Circé as she sang with a lovely voice and plied the loom. Then said Polites, who was dearest of all his comrades to Ulysses,— “Some one within plies a great loom, and sings with a loud voice. Some goddess is she, or woman. Let us make haste and call.” So they called to her, and she came out and beckoned to them that they should follow. So they went, in their folly. And she bade them sit, and mixed for them a mess, red wine, and in it barley-meal and cheese and honey, and mighty drugs withal, of which, if a man drank, he forgot all that he loved. And when they had drunk she smote them with her wand. And lo! they had of a sudden the heads and the voices and the bristles of swine, but the heart of a man was in them still. And Circé shut them in sties, and gave them mast and acorns and cornel to eat.
But Eurylochus fled back to the ship. And for a while he could not speak, so full was his heart of grief, but at the last he told the tale of what had befallen. Then Ulysses took his silver-studded sword and his bow, and bade Eurylochus guide him by the way that he had gone. Nor would he hearken when Eurylochus would have hindered him, but said, “Stay here by the ship, eating and drinking, if it be thy will, but I must go, for necessity constrains me.” And when he had come to the house, there met him Hermes of the golden wand, in the shape of a fair youth, who said to him,— “Art thou come to rescue thy comrades that are now swine in Circé’s house? Nay, but thou shalt never go back thyself. Yet, stay; I will give thee such a drug as shall give thee power to resist all her charms. For when she shall have mixed thee a mess, and smitten thee with her wand, then do thou rush upon her with thy sword, making as if thou wouldst slay her. And when she shall pray for peace, do thou make her swear by the great oath that binds the gods that she will not harm thee.” Then Hermes showed Ulysses a certain herb, whose root was black, but the flower white as milk. “Moly,” the gods call it, and very hard it is for mortal man to find. Then Ulysses went into the house, and all befell as Hermes had told him. For Circé would have changed him as she had changed his comrades. Then he rushed at her with his sword, and made her swear the great oath which binds the gods that she would not harm him. But afterwards, when they sat at meat together, the goddess perceived that he was silent and ate not. Wherefore she said, “Why dost thou sit, Ulysses, as though thou wert dumb? Fearest thou any craft of mine? Nay, but that may not be, for have I not sworn the great oath that binds the gods?” And Ulysses said, “Nay, but who could think of meat and drink when such things had befallen his companions?”
Then Circé led the way, holding her wand in her hand, and opened the doors of the sties, and drove out the swine that had been men. Then she rubbed on each another mighty drug, and the bristles fell from their bodies and they became men, only younger and fairer than before. And when they saw Ulysses they clung to him and wept for joy, and Circé herself was moved with pity. Then said she, “Go, Ulysses, to thy ship, and put away all the goods and tackling in the caves that are on the shore, but come again hither thyself, and bring thy comrades with thee.” Then Ulysses went. Right glad were they who had stayed to see him, glad as are the calves who have been penned in the fold-yard when their mothers come back in the evening. And when he told them what had been, and would have them follow him, they were all willing, save only Eurylochus, who said,— “O ye fools, whither are we going? To the dwelling of Circé, who will change us all into swine, or wolves, or lions, and keep us in prison, even as the Cyclops did! For was it not this same foolhardy Ulysses that lost our comrades there?” Then was Ulysses very wroth, and would have slain Eurylochus, though near of kin to him. But his comrades hindered him, saying, “Let him abide here and keep the ship, if he will. But we will go with thee to the dwelling of Circé.” Then Ulysses forbore. Nor did Eurylochus stay behind, but followed with the rest. So they went to the dwelling of Circé, who feasted them royally, so that they remained with her for a whole year, well content. But when the year was out they said to Ulysses, “It were well to remember thy country, if it is indeed the will of the gods that thou shouldst return thither.” Then Ulysses besought Circé that she would send him on his way homewards, as indeed she had promised to do. And she answered,—
“I would not have you abide in my house unwillingly. Yet must thou first go another journey, even to the dwellings of the dead, there to speak with the seer Tiresias.” But Ulysses was sore troubled to hear such things, and wept aloud, saying, “Who shall guide us in this journey?—for never yet did ship make such a voyage as this.” Then said Circé, “Seek no guide; only raise the mast of thy ship and spread the white sails, and sit in peace. So shall the north wind bear thee to the place on the ocean shore where are the groves of Persephoné, tall poplars and willows. There must thou beach thy ship. And after that thou must go alone.” Then she told him all that he must do if he would hold converse with the dead seer Tiresias, and hear what should befall him. So the next morning he roused his companions, telling them that they should now return. But it chanced that one of them, Elpenor by name, was sleeping on the roof, for the coolness, being heavy with wine. And when he heard the stir of his comrades, he rose up, nor thought of the ladder, but fell from the roof and brake his neck. And the rest being assembled, Ulysses told them how they must take another journey first, even to the dwellings of the dead. This they were much troubled to hear, yet they made ready the ship and departed. So they came to the place of which Circé had told them. And when all things had been rightly done, Ulysses saw spirits of the dead. First of all came Elpenor, and he marvelled much to see him, saying,— “How camest thou hither?—on foot or in the ship?” Then he answered, telling how he had died; and he said, “Now, as thou wilt go back, I know, to the island of Circé, suffer me not to remain unburied, but make above me a mound of earth, for men in aftertimes to see, and put upon it my oar, with which I was wont to row while I yet lived.”
These things Ulysses promised that he would do. Afterwards came the spirit of Tiresias, holding a sceptre of gold in his hand. And when Ulysses asked him of his return, he said,— “Thy return shall be difficult, because of the anger of Poseidon, whose son thou madest blind. Yet, when thou comest to the island of the Three Capes, where feed the oxen of the Sun, if thou leave these unhurt, thou and thy comrades shall return to Ithaca. But otherwise they shall perish, and thou shalt return, after long time, in a ship not thine own, and shalt find in thy palace, devouring thy goods, men of violence, suitors of thy wife. These shalt thou slay, openly or by craft. Nor yet shalt thou rest, but shalt go to a land where men know not the sea, nor eat their meat with salt; and thou shalt carry thy oar on thy shoulder. And this shall be a sign to thee, when another wayfarer, meeting thee, shall ask whether it be a winnowing fan that thou bearest on thy shoulder; then shalt thou fix thy oar in the earth, and make a sacrifice to Poseidon, and so return. So shalt thou die at last in peace.” Then Tiresias departed. After this he saw his mother, and asked how it fared with his home in Ithaca, and she told him all. And many others he saw, wives and daughters of the heroes of old time. Also there came King Agamemnon, who told him how Ægisthus, with Clytemnestra, his wicked wife, had slain him in his own palace, being newly returned from Troy. Fain would the King have heard how it fared with Orestes, his son, but of this Ulysses could tell him nothing. Then came the spirit of Achilles, and him Ulysses comforted, telling him how bravely and wisely his son Neoptolemus had borne himself in Troy. Also he saw the spirit of Ajax, son of Telamon; but Ajax spake not to him, having great wrath in his heart, because of the arms of Achilles. For the two, Ajax and Ulysses, had contended for them, Achilles being dead, before the assembly of the Greeks, and the Greeks had given them to Ulysses, whereupon Ajax, being very wroth, had laid hands upon himself.
Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com

Programming Visual Basic 2008 Tim Patrick

  • 1.
    Programming Visual Basic2008 Tim Patrick download https://ebookbell.com/product/programming-visual-basic-2008-tim- patrick-4106516 Explore and download more ebooks at ebookbell.com
  • 2.
    Here are somerecommended products that we believe you will be interested in. You can click the link to download. Programming In Visual Basic 2008 7th Edition 7th Julia Case Bradley https://ebookbell.com/product/programming-in-visual-basic-2008-7th- edition-7th-julia-case-bradley-2417356 Advanced Programming Using Visual Basic 2008 4th Edition Julia Case Bradley https://ebookbell.com/product/advanced-programming-using-visual- basic-2008-4th-edition-julia-case-bradley-1995366 An Introduction To Programming Using Visual Basic 2008 With Visual Studio Expression Edition Dvd 7th Ed Schneider https://ebookbell.com/product/an-introduction-to-programming-using- visual-basic-2008-with-visual-studio-expression-edition-dvd-7th-ed- schneider-22041544 Microsoft Visual Basic 2008 Express Programming For The Absolute Beginner 1st Edition Ford https://ebookbell.com/product/microsoft-visual-basic-2008-express- programming-for-the-absolute-beginner-1st-edition-ford-55132374
  • 3.
    Visual Basic 2008Programming Black Book Platinum Ed Kogent Solutions Inc https://ebookbell.com/product/visual-basic-2008-programming-black- book-platinum-ed-kogent-solutions-inc-231815772 Practical Database Programming With Visual Basicnet Ying Bai https://ebookbell.com/product/practical-database-programming-with- visual-basicnet-ying-bai-4105898 Practical Database Programming With Visual Basicnet 1st Edition Ying Bai https://ebookbell.com/product/practical-database-programming-with- visual-basicnet-1st-edition-ying-bai-1367072 Programming Microsoft Sql Server 2000 With Microsoft Visual Basic Net 1st Edition Dobson https://ebookbell.com/product/programming-microsoft-sql- server-2000-with-microsoft-visual-basic-net-1st-edition- dobson-55141988 Programming Visual Basic Net 1st Edition Dave Grundgeiger https://ebookbell.com/product/programming-visual-basic-net-1st- edition-dave-grundgeiger-43041026
  • 5.
    Programming Visual Basic 2008 TimPatrick Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo
  • 6.
    Programming Visual Basic2008 by Tim Patrick Copyright © 2008 Tim Patrick. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com. Editor: John Osborn Production Editor: Rachel Monaghan Copyeditor: Audrey Doyle Proofreader: Rachel Monaghan Indexer: Ellen Troutman Zaig Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Robert Romano Printing History: May 2008: First Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Programming Visual Basic 2008, the image of a bufflehead duck, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. This book uses RepKover™ , a durable and flexible lay-flat binding. ISBN: 978-0-596-51843-1 [M]
  • 7.
    vii Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv 1. Introducing .NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Before .NET 1 Back to Introducing .NET 2 The .NET Object 3 The Parts of the .NET Framework 7 From Source Code to EXE 16 What About Visual Studio and Visual Basic? 17 Visual Studio 2008 18 Summary 22 Project 23 2. Introducing Visual Basic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 The History of the Visual Basic Revolution 30 Visual Basic from the Inside Out 32 The Basics of Logic and Data 32 Data Types and Variables 35 Intermission 44 Comments 44 Option Statements 45 Basic Operators 47 Using Functions and Subroutines 49 Conditions 50 Loops 54 Creating Your Own Procedures 57 Other Flow Control Features 61
  • 8.
    viii | Tableof Contents Events and Event Handlers 64 Namespaces 66 The My Namespace 69 Summary 70 Project 70 3. Introducing the Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 The Library Project 76 The Needs of the Users 79 The Life of a Project 83 Summary 90 Project 90 4. Designing the Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 Relational Databases 95 SQL Server 2005 98 SQL 100 Using Databases in Visual Basic 107 Documenting the Database 108 Summary 109 Project 109 5. .NET Assemblies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 What Is an Assembly? 126 What’s Inside an Assembly? 128 Assemblies and Applications 131 The My Namespace and Assemblies 132 Directives and Assemblies 134 Summary 136 Project 137 6. Data and Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 The Nature of Computer Data 151 Data in .NET 153 Visual Basic Data Types 158 Literals 159 Constants 160
  • 9.
    Table of Contents| ix Enumerations 161 Variables 162 Variable and Constant Naming Conventions 165 Local Type Inference 166 Operators 167 Static Variables 172 Arrays 172 Nullable Types 175 Common Visual Basic Functions 176 Summary 181 Project 182 7. Windows Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 Inside a Windows Application 187 Windows in .NET 191 Making Forms Useful 210 Summary 212 Project 212 8. Classes and Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 Object-Oriented Programming Concepts 219 OOP in Visual Basic and .NET 224 Related Issues 241 Summary 244 Project 244 9. Functional Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 Lambda Expressions 253 Object Initializers 259 Error Handling in Visual Basic 260 The Nature of Errors in Visual Basic 260 Unstructured Error Handling 263 Structured Error Handling 265 Unhandled Errors 267 Managing Errors 269 Summary 273 Project 274
  • 10.
    x | Tableof Contents 10. ADO.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 What Is ADO.NET? 278 Overview of ADO.NET 279 Data Sets Versus No Data Sets 282 Connecting to SQL Server with Visual Studio 284 Interacting with SQL Server in Code 289 Database Transactions 292 ADO.NET Entity Framework 293 Summary 294 Project 294 11. Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 Security Features in .NET 304 Cryptography and Encryption 304 Encryption in .NET 306 Other Security Features 311 Summary 312 Project 312 12. Overloads and Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 What Is Operator Overloading? 330 What Can You Overload? 332 Other Operator Overloading Issues 338 Extension Methods 340 Summary 342 Project 342 13. XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361 What Is XML? 361 The XML Rule 364 XML Content 365 Using XML in .NET: The Old Way 371 Using XML in .NET: The New Way 375 Summary 378 Project 379
  • 11.
    Table of Contents| xi 14. Application Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392 A Short History of Settings 392 Settings in Visual Basic 2008 394 Summary 400 Project 401 15. Files and Directories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416 Traditional Visual Basic File Management 417 Manipulating Files Through Streams 418 File Management with the My Namespace 424 Summary 427 Project 428 16. Generics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433 What Are Generics? 433 Variations of Generic Declaration 436 Summary 442 Project 442 17. LINQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448 What Is LINQ? 448 Anonymous Types 450 LINQ to Objects 451 Basic Query Expressions 453 Converting Results to Other Forms 459 Aggregate Queries 459 Advanced Query Expressions 460 LINQ to XML 461 LINQ for ADO.NET-Related Data 463 Deferred Execution 468 Summary 469 Project 470 18. User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486 Overview of GDI+ 487 Selecting a Canvas 488 Choosing Pens and Brushes 490
  • 12.
    xii | Tableof Contents Flowing Text from the Font 493 Imagining Images 497 Exposing Your True Artist 499 Paths: Drawings on Macro-Vision 501 Keeping It Regional 502 Twisting and Turning with Transformations 503 Enhancing Controls Through Owner Draw 505 Windows Presentation Foundation 507 Enhancing Classes with Attributes 510 Summary 511 Project 511 19. Localization and Globalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526 Defining Globalization and Localization 526 Resource Files 527 The My.Resources Object 529 Localizing Forms Within Visual Studio 531 Adding Resources Outside Visual Studio 534 Manually Compiling Resources 535 Other Localization Features 537 Summary 538 Project 539 20. Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552 Printing in Windows 553 Printing in .NET 554 Printing a Document 557 Print Preview 559 Counting and Numbering Pages 561 Printing in “Raw” Mode 563 Summary 564 Project 564 21. Reporting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581 Report Options in .NET 581 Using Reporting Controls in .NET 584 Summary 597 Project 597
  • 13.
    Table of Contents| xiii 22. Licensing Your Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611 Software Licensing Options 611 License Agreements 615 Obfuscation 616 The Library Licensing System 618 Summary 621 Project 622 23. Web Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642 How the Internet Works 642 Programming the Internet 644 ASP.NET Features 645 Trying Out ASP.NET 646 More About Events 653 State and View State 654 Data Validation 655 Database Integration 657 Windows Communication Foundation 658 Summary 663 Project 663 24. Adding Online Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 672 Windows Online Help Options 672 Designing HTML Help 674 Accessing HTML Help 680 Summary 683 Project 683 25. Deployment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689 What’s Involved in Deployment? 689 Deployment Methods Within Visual Studio 690 Summary 700 Project 700 26. Project Complete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 711 The Library Project 711 Visual Basic Flexibility 714 The Programming Mindset 716 Summary 717
  • 14.
    xiv | Tableof Contents A. Installing the Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 719 B. Software License Agreement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 722 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 725
  • 15.
    xv Preface1 Welcome to ProgrammingVisual Basic 2008! I know you’re going to enjoy it; I’ve read it five times already. You’re probably anxious to get to Chapter 1, but I recom- mend you read this preface to make sure you paid for the right book. Who Is Reading This Book? Writing a book is a lot like writing a Visual Basic application. Well, except for the part about finding a publisher, and working with an editor. And then there’s that pesky rule about correct spelling. Come to think of it, they’re really quite different. But in one way, books and programs are similar: both are written to meet the needs of the user. When writing software applications, the user’s needs drive the organiza- tion and features of the final program. When writing a book, like the one you’re looking at now, the needs of the user—that’s you, the reader—drive the organiza- tion and features of the final text. So it was with you in mind that I set out to write this book. Oh, there’s the fame and the prestige, but it’s really about you. You, the person who seeks to understand Visual Basic and the .NET Framework on which it is built. When I thought about you and your needs, I came up with these ideas: You might know how to program, but maybe not In the programming world, there are four types of people: (1) those who already program joyfully; (2) those who don’t program, but will learn it and love it; (3) those who don’t program, but will learn it and struggle with it; and (4) those who should return this book immediately to the bookstore. If you are in one of the first three groups, this book is definitely for you. I believe that anyone who can break down a task into its basic step-by-step instructions can successfully program in Visual Basic. If you are unsure about your ability to quantify tasks in this way, you might want to start out with a book on basic programming concepts.
  • 16.
    xvi | Preface Youmight know how to program in Visual Basic or .NET, but maybe not And that’s OK, because this book will teach you. Most of the chapters introduce important topics in Visual Basic and .NET development, such as object-oriented programming concepts, or using the different types of variables available to you, or interacting with a database. If you already know how to use Visual Basic 6 or earlier, that’s great, but it’s not a prerequisite. You want to write programs Most programming books teach you to write code in 10-line increments. At least that’s what’s scattered throughout their pages. I’ve put some of those “code snippets” in this book. But I spend my days writing real programs, not 10-line sample programs. If you want to write whole programs, you should learn using whole programs. That’s why I also put a program in my book—a whole pro- gram. Over the next several hundred pages, I will develop a real program—a database for a small library—and you will write it with me. I put all of these ideas into 26 easy-to-read chapters, and had O’Reilly Media glue the pages together for your convenience. When you reach the index, you will have learned how to write complete programs in Visual Basic and .NET. It will be a pro- gramming adventure, so let’s get started! What’s in This Book? Since we are going to be spending a lot of time together, you probably want to know something about me. Well, my name is Tim Patrick, and for many years I lived just up the street from the big Microsoft campus. I’ve been writing programs for 25 years, and these days I write custom database-oriented Visual Basic applications for small to medium-size businesses. And I’m not alone. Most Visual Basic developers write business-level software. If that’s what you do, or plan to do, you’re in great company. As you move through the pages of this book, you will read about the major .NET and Visual Basic activities that drive the development of business-level and general con- sumer applications. If you plan to do some other type of programming, such as game development, this book will be somewhat helpful, but I don’t talk about advanced or specialized features such as interactive 3D models or geometric transformations. Each chapter discusses a major programming topic, and then follows it up with a practical implementation of that topic: the creation of the Library database program. I don’t show every line of code in the book; if I did, the book would weigh 53 pounds and cost $254.38, plus tax. To get every line of source code, you’ll have to download the accompanying source code from the book’s web site. The code and the book’s text are united in one purpose: to train you in the skilled use of Visual Basic on the .NET platform so that you can develop the highest-quality applications possible. The text and the source code both include valuable resources that you can use every day in your programming life.
  • 17.
    Preface | xvii What’sin the Software Download? You’re going to like the download. It contains all the source code for the Library database project. What’s cool is that when you install the source code examples, they become part of Visual Studio. Once they are installed, you can create a new chapter-specific project right from the File ➝ New Project menu in Visual Studio. Appendix A has all of the download and installation details. I wrote the project code using Visual Basic 2008 Professional Edition. Some portions may not be compatible with earlier .NET versions of the language. None of it is com- patible with Visual Basic 6.0 or earlier, so don’t even bother trying. The source code will work with any edition of Visual Basic 2008, including the Express Edition. The source code also uses SQL Server 2005 for its database storage. You can use any edition of SQL Server 2005, including the Express Edition. Chapter 4 intro- duces databases and SQL Server 2005. If you will be using the database in an IT department-controlled network environment, you may need to talk with your IT department representative about installing the sample database. The SQL code I use is pretty vanilla, so it should work on previous versions of SQL Server, and you could easily adjust it to work with Oracle, DB2, Microsoft Access, or other common data- base engines. You can also use the upcoming SQL Server 2008 if you have it available. You can use the downloadable source code for your own projects, but please give credit where credit is due. There is a license agreement associated with the code (see Appendix B), so please don’t go selling the software as your own work. Just to be on the safe side, I’ve added a few hard-to-find bugs. Just kidding! (No, I’m not!) Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, filenames, and file extensions. Constant width Indicates computer coding in a broad sense. This includes all Visual Basic source code, HTML content, XML content, commands, options, source code from other languages, and content generated by Visual Studio tools. Constant width bold Indicates commands or other text that the user should type literally. Also used to highlight a particular section of code. Constant width italics Indicates text that should be replaced with user-supplied values or values deter- mined by context.
  • 18.
    xviii | Preface Thisicon signifies a tip, suggestion, or general note. This icon indicates a warning or caution. Using Code Examples This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact the publisher or me for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting exam- ple code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation requires that you abide by the terms of the software license agreement found in Appendix B. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Programming Visual Basic 2008, by Tim Patrick. Copyright 2008 Tim Patrick, 978-0-596-51843-1.” If you feel your use of code examples falls outside fair use or the permission given here, feel free to contact us as permissions@oreilly.com. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any addi- tional information. You can access this page at: http://www.oreilly.com/catalog/9780596518431 To comment or ask technical questions about this book, send email to: bookquestions@oreilly.com
  • 19.
    Preface | xix Formore information about our books, conferences, Resource Centers, and the O’Reilly Network, see our web site at: http://www.oreilly.com/ Safari® Books Online When you see a Safari® Books Online icon on the cover of your favorite technology book, that means the book is available online through the O’Reilly Network Safari Bookshelf. Safari offers a solution that’s better than e-books. It’s a virtual library that lets you easily search thousands of top tech books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current informa- tion. Try it for free at http://safari.oreilly.com. Acknowledgments The development of Programming Visual Basic 2008 has been a labor of love for me, and I am blessed to have had so many others go through the labor with me. Joan Murray from Addison-Wesley was my editor on the first edition of the book. John Osborn at O’Reilly Media took up the task of guiding the second edition. I have been fortunate to have worked with John on three different book projects, and their suc- cess was possible thanks to his gallant efforts. Several other authors and programmers took time out of their day jobs to review each chapter of the book and point out its deficiencies, which were numerous before their arrival. I especially wish to thank Glenn Berry, Alex Bierhaus, Harry Chen, Ken Getz, Lowell Mauer, and Dan Sullivan for their superb comments. When it came time to focus on Visual Basic’s 2008 release, I also received fantastic input from Chris Williams, Daniel Seara, Ron Petrusha, and Sander Gerz. Many thanks to Joe Binder, Jay Roxe, Prasadi de Silva, and Eric Knox, all members of the Visual Basic team at Microsoft. Each of them fielded a relentless onslaught of questions about esoteric Visual Basic and .NET features, and provided answers filled with knowledge, patience, and grace. My agent, Claudette Moore, always deserves her own paragraph in any computer book I write. In fact, she would be a great subject for one of those literary-agent- focused biographies that the public is always clamoring for. Not only does she do a great job at all of the normal agenty things, but she also shares personally in the joys and sorrows of the authors under her charge. Thank you for another fun year in books.
  • 20.
    xx | Preface ToMaki, my wife, and to Spencer, my son, I give a special wave of thanks. If you’ve ever spent time with authors, you know how cranky they can get. But Maki and Spencer combat crankiness with care and love, and it works. The words thank you seem so inadequate when I owe both of them so much. Thanks be to God because He provided such a tremendous family to me.
  • 21.
    1 Chapter 1 CHAPTER1 Introducing .NET1 Welcome to .NET! I might as well have said, “Welcome to the universe,” because like the universe, .NET is huge. And it’s complex. And it’s filled with black holes and other things that don’t always make sense. Yet it (.NET, not the universe) turns out to be a fantastic system in which to develop software applications. The .NET Framework was not developed in a vacuum (unlike the universe); Microsoft designed it and its related development languages—especially C# and Visual Basic—to address various issues that plagued Windows software developers and users. To fully understand why .NET was necessary, we need to take a short trip down computer memory lane. Before .NET Practical, general-purpose computers have been around since the mid-20th century. However, they were inaccessible to most people because (a) they cost millions of dol- lars; (b) they consumed gobs of electricity; (c) maintenance and programming could be done only by highly trained specialists; and (d) they tended to clash with the liv- ing room furniture. Fast-forward about 30 years. IBM comes out with the “personal” computer. These “desktop” computers represented a great advance in technology, but only a minority of people ever used them. They continued to be expensive (thousands of dollars), and maintenance and programming still required significant investments in training. IBM PCs also looked hideous around the living room furniture. Then came the Apple Macintosh. With its sleek design and its user-friendly function- ality, it introduced the joy of computing to the masses. And while programming it was not always straightforward, it did give nice results. It’s no wonder that Microsoft decided to copy—oops, I mean improve upon—its functionality.
  • 22.
    2 | Chapter1: Introducing .NET Microsoft Windows 1.0 brought a greater level of usability to the IBM/Intel comput- ing platform. But it wasn’t a free ride for programmers. MS-DOS development was hard enough without the addition of the “message pumps” and the hundreds of Application Programming Interface (API) calls needed by Windows programs. Visual Basic 1.0, introduced in 1991, greatly simplified the development process, but with the advent of 32-bit systems, ActiveX and COM components, and the Web, even VB programmers soon felt overwhelmed. Throughout the 1990s, the situation only seemed to worsen. Microsoft saw increased competition in the form of the Java™ language and the Linux operating system. Hackers were exploiting buffer overruns and other security issues present in the Windows platform. Users experienced myriad computer problems stemming from conflicting standards, competing data integration technologies, registry bloat, and “DLL hell.” In frustration, an Excel user’s group set fire to the entire Microsoft cam- pus in Redmond. Well, it didn’t get that bad. But Microsoft did see that it needed to address the over- all software development and usability issues on its beloved Windows platform. Its solution came in the form of the .NET Framework. Back to Introducing .NET When Microsoft announced its plans for .NET, it surprised many developers, espe- cially Visual Basic developers, who saw it as a giant step backward for “Rapid Appli- cation Development.” But the release of the .NET Framework version 1.0 in 2002 did bring many needed benefits: .NET introduced a unified programming environment All .NET-enabled languages compile to “Microsoft Intermediate Language” before being assembled into platform-specific machine code. Visual Basic, C#, and other .NET languages are wrappers around this common .NET “language.” Since all .NET-enabled compilers speak the same underlying language, they no longer suffer from the many data and language conflicts inherent in other cross- language component-based systems such as COM. The .NET version of Visual Studio also unified the standard user interface that lets programmers craft source code. .NET committed developers to object-oriented technologies Not only does .NET fully embrace the object-oriented programming paradigm, but everything in .NET is contained in an object: all data values, all source code blocks, and the plumbing for all user-initiated events. Everything appears in the context of an object.
  • 23.
    The .NET Object| 3 .NET simplified Windows programming Programming in Visual Basic before .NET was easy enough, until it came time to interact with one of the API libraries, something that happened a lot in profes- sional programming. With .NET, most of the regularly used APIs are replaced with a hierarchy of objects providing access to many commonly needed Win- dows features. Since the hierarchy is extensible, other vendors can add new func- tionality without disrupting the existing framework. .NET enhanced security Users and administrators can now establish security rules for different .NET fea- tures, to limit malicious programs from doing their damage. .NET’s “managed” environment also resolves buffer overrun issues and memory leaks through fea- tures such as strong data typing and garbage collection. .NET enhanced developer productivity through standards The .NET Framework is built upon and uses many new and existing standards, such as XML and SOAP. This enhances data interchange not only on the Win- dows platform, but also in interactions with other platforms and systems. .NET enhanced web-based development Until .NET, a lot of web-based development was done using scripting languages. .NET brings the power of compiled, desktop development to the Internet. .NET simplified the deployment of applications If .NET is installed on a system, releasing a program can be as simple as copying its EXE file to the target system (although an install program is much more user- friendly). Features such as side-by-side deployment, ClickOnce deployment, and an end to file version conflicts and “DLL hell” (the presence of multiple versions of the same DLL on a system, or the inability to remove a version of a DLL) make desktop and web-based deployments a snap. If you didn’t understand some of the terms used in this section, that’s all right. You will encounter them again, with explanations, in later chapters. The .NET Object To fully understand software development in .NET, you must understand what an object is. (If you are familiar with object-oriented programming—OOP—you can probably skip down to the next section, although you will miss some really great content.) While some of this section’s information will also appear in Chapter 8, it is so important to the discussion of .NET that a portion appears here as well.
  • 24.
    4 | Chapter1: Introducing .NET Objects and Data From a programming standpoint, a computer performs four basic tasks: • It stores data in the computer’s memory area. • It supports processing of this data through basic operations, including addition and subtraction, Boolean algebra, and text string manipulation. • It allows the user to interact with the data stored in memory. • It provides a way to bring the data in and out of memory, through input and out- put devices such as keyboards and printers, and through long-term storage media such as hard drives. The core of these four activities is data. Computers exist to manipulate data. Operat- ing systems provide the basic foundation for these activities, but it is software appli- cations that make these features—the ability to manipulate data—real and meaningful to the user. High-level programming languages are the primary tools used to develop these applications, each of which uses some general methods to make data manipulation features available to the programmer. Back in the good old days of assembly language development, if you knew the memory address of a piece of data, you could access and manipulate it directly. In early flavors of BASIC and in most other “procedural” languages, data was accessed through variables. As languages grew in complexity and purpose, so did their view of data. In the LISP (short for “List Processing” or “Lots of Irritating Silly Parentheses”) language, any data value exists within a larger list or set of data. But in .NET languages, data is viewed through the object. Objects are collections of data values and associated source code. While in older BASIC dialects, each data element was more or less independent through its named variable, related data values in OOP languages can be grouped into objects. Object implementations often include source code designed to manipulate the data values of that object. Objects generally represent some thing, often a thing that has a real-world counter- part, whether physical or conceptual. For instance, your code may include a House object that has data fields or properties for the address, the exterior paint color, and the number of people living in the house. Associated source code could manage that data; a Paint method could alter the color value used for the exterior paint. The data and code elements within an object are called members. Some members are hidden inside the object and can be accessed only by the object’s source code. Other members are more public; any code in your application can use them, not just that subset of application code found inside the object. Consider a television as an object (see Figure 1-1).
  • 25.
    The .NET Object| 5 The public members of a TV are generally easy to use: the power button, channel selector, volume control, and so on. They are the conduits through which the user controls the data values of the TV (its video and audio output). There are also hid- den members inside the TV; you could use these members to impact the picture and sound quality, although this would be a bad idea for most users. You don’t want me messing with the internal members of your TV set, trust me. In the same way, an object doesn’t want code outside the object to mess with its internal members except through the public members. I don’t care how a TV works internally, as long as I can get pictures and sound out of it by using the controls that are exposed (power, channel, volume). Objects and Interfaces The public members of an object represent its interface. If code outside the object wants to manipulate the data belonging to that object, it uses the members of the interface. It doesn’t have to figure out the hidden members or how they work, and that’s good. It’s especially good if those internal members ever change for any reason, which happens more often than you think. Consider how the internals of TVs have changed just in the past 30 years. Here’s a drawing of the TV my family had when I was a kid. Compare it to modern flat-panel TVs available today (see Figure 1-2). My family’s TV was cool. It had an AM/FM stereophonic hi-fi radio, a turntable that could play 33 1/3, 45, and 78 rpm records, and a large 19-inch screen with a vivid, black-and-white, crystal-clear display. Two kids could hide behind it when playing hide-and-seek. And my friend who had the same model said that you could draw these really cool permanent lines on the screen with a magnet. Who cares that the speaker panels looked like vertical shag carpet? Who cares that the unit took up 30% of the floor space in the room? Who cares that you could cook sausages on top of it from the heat generated by the vacuum tubes? It was more than a TV; it was an entertainment center. Figure 1-1. A TV: it’s an object, not just objectionable Outside view Inside view
  • 26.
    6 | Chapter1: Introducing .NET Now compare it to the wimpy little flat-panel job on its right. If you look closely, you find that the interface to the TV hasn’t really changed much in three decades. There are still controls for power, volume, and channel selection (although Horizontal Hold and Vertical Hold are gone, sniff). What has changed is the internal configura- tion. Gone are the humming vacuum tubes, all replaced with efficient transistors and solid-state components. But it doesn’t really make much difference to the TV viewer, since the public interface remains the same. Objects in OOP development work in the same way. As long as the public interface remains the same, the object’s actual code and internal data storage system—also known as the object’s implementation—can change with no impact to the overall application. Objects and Instances The interface and implementation of an object really represent only its design; these are the parts the programmer creates through the source code. They exist even before the program is compiled and installed on the user’s computer. In fact, at this level, objects really aren’t even known as objects. In most languages (including Visual Basic), the word class indicates the implementation of an object’s interface. Once your application is installed on a computer and starts up, the code creates instances of the class to store actual data in memory. These instances are the true objects of OOP development. Depending on how your code is written, a single class implementation might be used to create one or even hundreds of objects in memory at the same time. Figure 1-2. Are those really TVs? TheTV of my childhood A newfangled thing
  • 27.
    The Parts ofthe .NET Framework | 7 In .NET, all of your code and data values appear inside objects. Pretty much every- thing you see in a running program is an object: a Windows form is an object; a list- box control on that form is an object; and a single item in that listbox is an object. The Parts of the .NET Framework So, now you know all about objects, and you are probably thinking it’s time to toss this book into the pile and start programming. But there are a few more parts of the .NET Framework still to discuss. These parts show up ad nauseam in the .NET doc- umentation, and they each have a three-letter acronym (TLA), or thereabouts. The Common Language Runtime At the center of the .NET Framework is the Common Language Runtime (CLR), so named not because it is common or ordinary, but because all .NET-enabled lan- guages share it in common. Everything you do in a .NET program is managed by the CLR. When you create a variable, thank the CLR and its data management system. When you say goodbye to a piece of data, thank the CLR and how it manages the release of data through its garbage collection system. Did you notice how the word manage keeps showing up in those sentences? My editor sure did. But “manage” is the mot juste, since that is what the CLR does. In fact, software written for the .NET Framework is called managed code. Any code that falls outside the CLR’s control, including COM (ActiveX) components used by your .NET application, is known as unmanaged code. The CLR is a lot like Los Angeles International Airport. If you have ever been to LAX, you know that there is a whole lot of activity going on. Airplanes arrive and depart each minute. Cars by the thousands enter and leave the two-level roadway and the central parking structures. People and pickpockets move constantly among the eight main terminals and the massive international terminal. There’s a lot happening, but so much of it is managed. Planes cannot take off or land without approval from the control tower. Access points and gates manage the roadways and parking garages. Friendly, courteous TSA agents manage the flow of passengers and pickpockets into and out of the secure areas of the terminals. The control and management structures in place at LAX ensure an orderly and secure flow of people between their planes and the city of Los Angeles. The control and management structures of the CLR ensure an orderly and secure flow of data between .NET code and the rest of the computer or connected network. You’d probably like to know the secret of how the CLR is able to process programs written in any .NET language, including Visual Basic, C#, and FORTRAN. So would Microsoft’s competitors. Actually, they do know, because there is no secret.
  • 28.
    8 | Chapter1: Introducing .NET All .NET-enabled languages convert (i.e., “compile”) your source code into Microsoft Intermediate Language (or MSIL, pronounced “missile,” and more commonly abbre- viated as just IL). For those of you familiar with assembly language, it looks a lot like that. For those of you not familiar with assembly language, it looks a lot like gibber- ish. For example, here is some Visual Basic source code for a console application (a non-Windows text-based program, like the old MS-DOS programs) that simply out- puts “Hello, World!” from a code procedure called Main: Module Module1 Sub Main( ) Console.WriteLine("Hello, World!") End Sub End Module That’s the whole .NET program. When the Visual Basic compiler converts it to MSIL, the Main procedure looks like this (slightly modified to fit on this page): .method public static void Main( ) cil managed { .entrypoint .custom instance void [mscorlib]System. STAThreadAttribute::.ctor( ) = ( 01 00 00 00 ) // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Hello, World!" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Module1::Main Yes, it is gibberish. But that’s OK, because it fulfills the International Computer Book Association’s requirement that every Chapter 1 include a “Hello, World” code sample. Also, the CLR understands it, and that’s what really counts in .NET. As long as you can get your code into IL, .NET will process it. The Visual Basic compiler just happens to generate IL for you. Other .NET language compilers, including C#, tar- get IL as well. You can even write your own IL code, but you’re probably reading the wrong book for that. Just to put your mind at ease, this will be the last bit of IL you will see in this book. The Common Language Specification Languages that claim to support .NET cannot just say so for any old reason. They truly have to be compatible with .NET and its workings. This is done through the Common Language Specification (CLS). The CLS defines a minimum set of features that a language must implement before it is considered to be .NET-compliant, or more accurately, CLS-compliant. A language can go beyond that minimum if it wants, and .NET includes many addi- tional features upon which language-specific features may be built. A language that
  • 29.
    The Parts ofthe .NET Framework | 9 implements only the minimum CLS-specified features may not be able to fully inter- act with components from languages that exceed the minimum specification. Visual Basic is, of course, CLS-compliant, and in fact it goes way beyond that minimum. The Common Type System Since the CLR is controlling your source code anyway, Microsoft thought it would be good to have it control the source code’s data as well. The .NET Framework does this through its Common Type System (CTS), which defines all of the core data types and data mechanisms used in .NET programs. This includes all numeric, string, and Boolean value types. It also defines the object, the core data storage unit in .NET. The CTS divides all objects into two buckets. The first bucket, called value types, stores actual data right in the bucket. If you have a 32-bit integer value, it gets put right in the value type bucket, ready for your immediate use. The other bucket con- tains reference types. When you look in this bucket, you see a map that tells you where to find the actual data somewhere else in the computer’s memory. It seems like value types are easier to use, and they are, but they come with a few restrictions not imposed on reference types. Programs and components written using the CTS standard can exchange data with one another without any hindrances or limitations. (A few .NET data types fall out- side the “core” CTS types, but you need to avoid them only when you want to specif- ically interact with components that can use only the core CTS types.) When you write your applications in Visual Basic, most of your code will appear in classes. Classes are reference types that include both data values and associated code. The data values included in a class are most often the core CTS data types, but they can also contain objects that you design elsewhere in your application. Visual Basic also includes structures, the weaker yet quicker younger brother of classes. Struc- tures implement value types, and also include both data and code. Classes and structures are just two of the data/code types available in Visual Basic. Interfaces are class and structure skeletons; they include design details of what should appear in a related class or structure, but don’t include any actual implemen- tation or working code. Delegates define a procedure “signature” sans implementa- tion, and are used to support events, those actions (initiated by the user, by the operating system, or by your code) that tell your code, “Get to work now!” Sea otters are aquatic mammals that are curiously related to the weasel, and like to eat sea urchins. Modules are blocks of code and data, but unlike classes and structures, you can’t create independent objects from them. Enumerations group a set of related inte- ger values, generally for use as a list of choices. In .NET parlance, all of these terms (class, structure, interface, delegate, module, and enumeration, but not sea otter) are known collectively as types. You probably already knew that .NET had some confusing elements in it; you wouldn’t have bought a
  • 30.
    10 | Chapter1: Introducing .NET book about it if it were easy. But despite all the complex technology, it is this simple word, type, which causes the most confusion. You will likely experience some angst throughout this book each time you read it. The problem: it’s too general. Not only does it refer to these core elements of the CTS, but it is also used when talking about just the Visual Basic-specific value types (more often called the Visual Basic “data types”). The nickname for structures is “user-defined types,” yet another confusing use of “type.” Programmers who used Visual Basic before its .NET incarnation also remember “Type” as the language statement used to create user-defined types. Arrrgh! Microsoft should have used some word other than type for the world of classes, interfaces, enumerations, and so on. “Banana” would have been a better choice since it is only sometimes used to discuss software. But “type” is the word, so you better get used to seeing it. I will try to include as much context as possible when using the word throughout this volume. The members of a type usually consist of simple data fields and code procedures, but you can also include other types as members. That is, a class can include a nested class if it needs to. Only certain types support nesting—see Chapter 8 for details. I also talk about access levels in that chapter. Each member has an access level that says what code can use that member. There are five access levels, ranging from pub- lic (anybody and their brother can use the member) to private (you have to be inside the type to even know it’s there). Chapter 6 discusses the .NET type system in greater detail, including the informa- tion you crave on classes, structures, and other bananas. .NET Class Libraries Computers are actually quite stupid. Whereas I can count all the way to 17, a com- puter tops out at 1; it only knows the digits 0 and 1. The CPU includes a set of sim- ple operators used to manipulate the digits 0 and 1, and a few more operators that compare 1s and 0s in complex ways. The computer’s last great trick is its ability to move 0s and 1s into and out of memory, but whoop-de-doo. Sure it does these things at nearly the speed of light, but can it calculate π to 3 million decimal places? Well, actually it can. Computers don’t know anything about the letters of the alpha- bet, and they really can handle only the digits 0 and 1, yet here I am using a com- puter to write an award-winning book. It is the ability to combine the simple 1-bit data values and operators into increasingly complex libraries of functionality that makes useful computers possible.* The .NET Framework is built upon decades of increasingly complex functionality. When you install the .NET Framework, the CLR and its associated type system * If you want to read a truly fascinating book on how complex software and hardware operations are formed from the most basic uses of 0 and 1, read Charles Petzold’s Code: The Hidden Language of Computer Hard- ware and Software (Microsoft Press).
  • 31.
    The Parts ofthe .NET Framework | 11 represent the core of the framework. By itself, the framework includes all the basic functionality needed to let you add 2 and 2 together and correctly get 4. And as a business application developer, you spend a lot of time doing just that. But what if you want to do something more complex, something that you know some other pro- grammer has already done, like sorting a list of names or drawing a colored circle on a form? To get that answer, go to the class libraries, the .NET Class Libraries. These libraries, installed with the framework, include a lot of prewritten (increasingly com- plex) functionality that you don’t have to write from scratch. There are two class libraries in .NET: the Base Class Library (BCL) and the Frame- work Class Library (FCL). The BCL is smaller, and contains the most essential fea- tures that a program just couldn’t do without. It includes only those classes that are an absolute must for supporting applications on the framework if Microsoft were to, say, port the framework to Linux. The FCL is larger, and includes everything else Microsoft thought you would want to have in your programs, but was not absolutely essential to have in the BCL. Don’t even ask how many classes there are in the FCL; you don’t want to know. I bet that Microsoft doesn’t even really know the full number. I am convinced that those wacky pranksters at Microsoft have included “gag” classes in the FCL, but they are so deeply buried that few programmers ever encounter them. With thousands (yes, thousands!) of classes, enumerations, interfaces, and other types included in the BCL and FCL, you would think that it would be hard to find just the class you need. But it’s not that difficult, at least not overwhelmingly diffi- cult. The .NET Framework includes a feature called namespaces. All types in .NET appear in a hierarchy—a tree-like structure—with just a few minimal entries at the root. Each node in the hierarchy is a namespace. You uniquely identify any class or other type in the libraries by naming all the namespaces, from the root down to the local namespace that contains the class, separating each node with a period (.). Unlike most hierarchies that have all branches starting from a single root node, the .NET namespace hierarchy has multiple root nodes. The largest root namespace is named System. It includes many classes, but it also includes several next-tier hierar- chy nodes (namespaces). Since the framework includes features for both Windows- based and web-based application development, there are namespaces that contain the Windows-specific and web-specific development features. These namespaces appear just within the System namespace, and are called Windows and Web. All code related to on-screen forms in the Windows namespace appears in the Forms namespace, and within this namespace is the actual class that implements a form, named Form. Figure 1-3 presents an image of this namespace subset. In Visual Basic, you identify a class by qualifying it with all its namespaces, starting from its root namespace. The Form class has the following fully qualified name: System.Windows.Forms.Form
  • 32.
    12 | Chapter1: Introducing .NET All classes and types exist somewhere in the hierarchy, although not every class descends from System. Many of the supporting features specific to Visual Basic appear in the Microsoft.VisualBasic namespace, which has “Microsoft” as its root node instead of “System.” When you create new projects in Visual Basic, the name of the project is, by default, a new top-level node in the hierarchy. If you create a new Windows application named WindowsApplication1, the default “Form1” form has the following fully qualified name: WindowsApplication1.Form1 This new application’s namespace is not just a second-class appendage hanging off the System namespace. It is fully integrated into the full .NET namespace hierarchy; the WindowsApplication1 namespace is a root node, just like the System and Microsoft root nodes. Visual Basic includes features that let you alter the default namespace for your application, or place one of the application’s classes in a specific namespace. You can even place your application’s classes in the System namespace branch. Changing WindowsApplication1 to System.MySuperApp moves Form1 to: System.MySuperApp.Form1 If your application is actually a component or library destined for use in programs, your app’s classes will appear in the namespace you specify when the other program loads your component into its application area. Your code will look like it is part of the Microsoft-supplied namespaces. Is that cool or what? Although you can add your classes to the System namespace, you will incur the wrath of other .NET programmers. The System namespace is supposed to be for “system” (read: Microsoft-supplied) features, and that’s it. Also, there’s a chance that two ven- dors might use the same namespace path. So, to avoid potential namespace conflicts and dirty looks from other programmers, you should name your application’s classes as: CompanyName.ApplicationName.ClassName A single class or other type cannot be split across multiple namespaces, even within the same hierarchy branch. However, two classes or types may share a common name in different namespaces, even within the same branch. Figure 1-3. A hierarchy of namespaces and classes System Web Windows Forms Form = Namespace = Class
  • 33.
    The Parts ofthe .NET Framework | 13 All classes of the BCL and FCL appear intermingled throughout the entire namespace hierarchy. This means that you cannot necessarily tell whether a particu- lar class is from the BCL or the FCL. Frankly, it doesn’t really matter; your code won’t care which library a class comes from, as long as it is available for use on the user’s workstation. Just before the release of Visual Studio 2008, Microsoft announced that it would make the source code for much of the Framework Class Library version 3.5 available for developers to review. This means that programmers who want to know how Microsoft sorts a list of names in memory or draws a colored circle on a form will get at least a partial glimpse of how it is done. Assemblies and Manifests An assembly is a “unit of deployment” for the parts of a .NET application or library. In 99.9% of cases, an assembly is simply a .NET executable file (an .exe file) or a .NET library of classes and other types (a .dll file). It is possible to split an assembly among multiple files, but usually it is one file for one assembly. What makes an ordinary .exe or .dll file an assembly is the presence of a manifest. For single-file assemblies, the manifest appears right in the file; it can also appear in a file of its own. The manifest is a chunk of data that lists important details about the assembly, including its name, version information, default culture, information on referencing external assemblies and types, and a list of all the files contained in the assembly. The CLR will not recognize an assembly without its manifest, so don’t lose it. Assemblies can include an optional strong name. This helps to ensure the integrity and authenticity of an assembly through a digital signature attached to the manifest. The strong name uses public key cryptography to guarantee that the assembly is unique and has not been tampered with. Visual Studio and the .NET Framework include tools that let you add a strong name to an assembly. When you deploy your application, you will normally place all assembly files, config- uration files, and any related files specific to your application into the application’s install directory, just like in the old Jurassic days before .NET. Shared assemblies designed to be used by more than one application on a single machine can be stored in the Global Assembly Cache (GAC). All assemblies placed in the GAC must have strong names. Some systems may allow only the system administrator to add assem- blies to the GAC. Metadata and Attributes Assemblies are brought to you by the letter m. In addition to manifests and type members, assemblies also contain metadata. The application code and data elements stored in an assembly parallel the code and data items found in the related Visual
  • 34.
    14 | Chapter1: Introducing .NET Basic source code; for each type and member in your source code, there is associated executable code in the deployed assembly. This makes sense, and is not much of a change from pre-.NET deployments. What is different is that the Visual Basic com- piler now attaches additional information—metadata—to each type and member in the assembly. This metadata documents the name of the associated content, infor- mation about required data types, information on class inheritance for the element, and security permissions required before the element can be used by the user or other software. Your Visual Basic source code can enhance the metadata for any element of your assembly through attributes. The metadata generated by an attribute is more than just some ID number. Attributes implement full .NET classes, with their own data values and associated logic. Any .NET code that knows how to process attributes can examine the attributes for a type or member and take action as needed. This includes Visual Studio, the Visual Basic compiler, and your own custom applications. How’s this for a mundane example: the .NET Framework includes an attribute named ObsoleteAttribute. This attribute lets you mark types or members of your assembly as obsolete or no longer supported. (Visual Studio uses this attribute to dis- play a warning whenever you attempt to use an out-of-date BCL or FCL feature.) To use the attribute, add it to a member of your application using angle brackets: Class MyClassWithOldMembers <ObsoleteAttribute> Sub DoSomeWork( ) End Sub End Class This code defines a single class (MyClassWithOldMembers) with a single member proce- dure (DoSomeWork), a procedure that clearly does some work. The procedure is tagged with the ObsoleteAttribute attribute. By custom, all attribute names end in the word Attribute. You can leave off this portion of the word if you wish, as long as the result- ant word does not conflict with any Visual Basic language keyword: Class MyClassWithOldMembers <Obsolete> Sub DoSomeWork( ) End Sub End Class When you compile the class and store it in an assembly, the <ObsoleteAttribute> attribute is stored as part of DoSomeWork’s definition. You can now write a separate Visual Basic application that scans an assembly and outputs the name and status of every type and member it finds. When that analysis program encounters the obso- lete member, it will detect ObsoleteAttribute in the metadata, and output the status: DoSomeWork Procedure: Obsolete, don't use it! Most attributes are designed with a specific purpose in mind. Some attributes instruct Visual Studio to display the members of a class in specific ways. You’ve probably already played with the form-editing features of Visual Studio to design a
  • 35.
    The Parts ofthe .NET Framework | 15 simple Windows desktop application. When you add a control (such as a button or a listbox) to a form and select that control, Visual Studio lets you edit details of that control through the Properties panel area (see Figure 1-4). The Button control is implemented as a class, and many of its class members appear in the Properties panel, but not all of them. When the Button class was designed, attributes were added to its members that tell Visual Studio which members should appear in the Properties panel, and which should not. Visual Studio dutifully exam- ines these attributes, and displays only the requested properties. Versioning Like yours, my applications are perfect from their initial release, and I never have a reason to modify them or add features. But there are software development organiza- tions—including one large company that, so as not to cause embarrassment, I will refer to only by its initial letter of M—that feel the need to “one-up” their competi- tion by coming out with “improved” versions of their previously released software offerings. Let’s say that “M” happened to have a popular word processor that includes version 1.0 of a spellcheck component. “M” also happens to sell an email tool that depends specifically on version 1.0 of that same shared component. If, in a show of competitive machismo, “M” releases an update to the word processor and the spellcheck component (now version 2.0), what happens to the email tool’s spellchecking ability? Figure 1-4. The Properties panel in Visual Studio I'm talking about this Properties area
  • 36.
    16 | Chapter1: Introducing .NET Not that this ever happens in real life. But if it did, the replacement of a vital shared component with a newer but somewhat incompatible version could cause real prob- lems. A related problem is the deployment of multiple versions of a single component on the same workstation, all in different directories. Can any of them be safely deleted? .NET solves these problems through versioning. All assemblies that use shared com- ponents identify exactly which versions of the shared components they require. Although an application can be reconfigured to use a later version, it will use only the originally specified version of a shared component by default. Multiple versions of a single shared component can be added to the GAC, a feature called side-by-side deployment. The CLR ensures that the right application links up with the right component. You can even run applications simultaneously that use different versions of the same component. From Source Code to EXE Now you know pretty much everything there is to know about .NET except for that pesky programming thing. Before delving into some actual code, let’s take a little snack break and examine the lifetime of an application, from start to finish (see Figure 1-5). So, here’s what happens, step by step: 1. You, as the programmer, are responsible for preparing the basic ingredients (a) of the application. For Visual Basic programs, this means creating one or more source code files with a .vb extension. Your ingredients may also include other support files, such as resource files (text and graphics files, often used for multi- language support). Figure 1-5. The real Visual Basic development process (a) (b) (c) (e) (d)
  • 37.
    What About VisualStudio and Visual Basic? | 17 2. Your application is cooked by the Visual Basic compiler (b). The result is an assembly, complete with a manifest and metadata. The output is actually semi- compiled MSIL and includes ready-to-execute versions of the original source code’s types and members, including all member and type names. All this con- tent can be “decompiled” (returned back to full MSIL, although not to full Visual Basic) using a tool named ildasm.exe (the Microsoft Intermediate Lan- guage Disassembler), which is included with the .NET Framework. Since you probably don’t want just anyone disassembling your application and looking at the code, Microsoft (and other third parties) also supplies an obfuscator, which sufficiently scrambles the content of your code to make it just difficult enough to discourage prying eyes. 3. The assembly (c) is deployed to the user’s workstation. A few different methods are used to deploy the application, including (1) generating a standard Windows Installer setup package; (2) generating a ClickOnce deployment; or (3) performing an xcopy install, which involves nothing more than copying the EXE assembly itself to the destination machine. No matter which deployment method you choose, the .NET runtime (d) must also be installed on the user’s workstation. 4. The user eats—I mean runs—the program (e). The CLR does a final just-in-time (JIT) compile of the MSIL assembly, to prepare it for use on the local platform. It then presents the application to the user, and manages all aspects of the applica- tion while it runs. The user experiences a level of joy and satisfaction rarely encountered when using other software applications. As with the preparation of a Thanksgiving meal, the actual development process is somewhat more involved than just reading a paragraph (or a recipe book) about it. But it’s not so difficult that it can’t be put in a book like this one. What About Visual Studio and Visual Basic? Wait a minute, what about Visual Studio? That last section didn’t even mention it. And it didn’t need to, since you do not need to use Visual Studio to develop, compile, deploy, or run Visual Basic applications. The entire .NET Framework—including the Visual Basic compiler—is available for free from Microsoft’s web site; download it and use it to develop and deploy applications that are every bit as powerful and com- plex as, well, Visual Studio. The July 1983 issue of Datamation magazine includes an article from manly reader Ed Post, titled “Real Programmers Don’t Use Pascal.”* I highly recommend that you read this article, as it will help you quickly separate the real programmers from the “quiche eaters.” And when you do, run away as fast as you can from the real programmers. * Datamation 29 (7): July 1983, pp. 263–265. I also found the text of the article on the Internet by doing a search on the title. A similar version of the text, with only minor editorial changes, also exists under the title “Real Programmers Don’t Write Pascal.”
  • 38.
    18 | Chapter1: Introducing .NET Oh, sure, they can reconstruct your source code from the obfuscated .NET assembly, but they will be useless on a team project using Visual Studio. A “real programmer” could code any .NET application using Notepad, and it would run. Actually, real programmers would use Emacs or vi instead of Notepad (since Windows does not include a keypunch interface), but the results would be the same. They would growl as you blissfully type away in Visual Studio’s elegant, well- designed, and fully customizable and extensible user interface. They would gripe and bare their cheese-cracker-with-peanut-butter-encrusted teeth at you while you use the IntelliSense and AutoCompletion features built into the Visual Studio code edi- tor. They would consume another slice of quiche-shaped cold pizza while you drag- and-drop both Windows and web-based user interfaces. Yes, the real programmer could generate full applications with just a text (or hex) editor and a .NET compiler, but you would get the glory, since you would be done in a fraction of the time it would take the FORTRAN lover to eek out his code. Visual Studio 2008 Since this is a book on Visual Basic development and not on Visual Studio usage, I won’t be delving too much into Visual Studio’s features or its user interface ele- ments. It is a great application, and its tight integration with the .NET Framework makes it the best tool for developing applications with .NET. But as the real pro- grammer would tell you, it is really just a glorified text editor. Visual Studio hides a lot of the complexity of .NET code, and its automatic generation of the code needed to build your application’s user interface is a must-have. Most of its features exist to simplify the process of adding code to your application. Although I will not be including a 20-page review of Visual Studio right here, you will find images of Visual Studio throughout the text, placed so as to advance your understanding of the topics under discussion in each chapter. When you start up Visual Studio for the first time, it displays the Start Page. (See Figure 1-6. The screen- shots in this book are taken from the Professional Edition of Visual Studio 2008.) Visual Studio 2008 is the fourth major release of the product since .NET’s initial introduction in 2002. Each release (in 2002, 2003, 2005, and 2008) corresponds to a related release of the .NET Framework (versions 1.0, 1.1, 2.0, and 3.5, respectively) and of the .NET implementation of Visual Basic. The 2008 release of Visual Studio is major. It is packed with new usability features, and comes in four delicious flavors: Visual Studio 2008 Express Edition This entry-level product is geared toward the home hobbyist or weekend pro- grammer who wants to learn .NET and one of its core programming languages, but won’t be snuggling up to it on a daily basis. Visual Studio 2008 Express Edi- tion is actually multiple Express Edition language products promoted together, including Visual Basic 2008 Express Edition. Microsoft’s goal is to introduce as
  • 39.
    Visual Studio 2008| 19 many people as possible to the joys of .NET programming, so it offers the Express Edition products at no cost. This edition includes a simplified Visual Studio-like user interface, but it does impose a few restrictions on your program- crafting ability. You can still edit the source code directly and craft applications of any complexity, but the Express UI won’t always assist you with this. For instance, you cannot develop web applications with the Visual Basic Express product unless you install the separate Visual Web Developer 2008 product. Also, Express doesn’t include much support for deployment; applications designed with the Express Edition are generally expected to be used on your own workstation only. Visual Studio 2008 Standard Edition Visual Studio’s Standard Edition is just like the Express Edition, with a few extras thrown in, such as multiple-language support, web development tools, and deployment support through both ClickOnce and Windows Installer meth- ods. SQL Server 2005 Express Edition is included. Visual Studio 2008 Professional Edition This is the minimum level required by programmers who will develop applica- tions on a daily basis for money. It’s the version that I use, and it includes all the “power” features needed by a single programmer for both desktop and web- based development. The straightjacketed Express user interface is out, replaced Figure 1-6. The Visual Studio Start Page
  • 40.
    20 | Chapter1: Introducing .NET by the full Visual Studio “mighty” Integrated Development Environment (IDE) and all documentation. Also included are special tools that help you develop applications for Microsoft Office, and for mobile devices. But wait, there’s more. You also get SQL Server 2005 Developer Edition. All instructions in this book that relate to using the development environment refer to the Professional Edi- tion. But if you are following along using the Express or Standard Edition, you will be just fine since the interfaces are quite similar. Visual Studio Team System 2008 The crème de la crème of the Visual Studio product line is Team System. It includes features needed by development teams that work on projects together, features such as project management tools and source code control. Visual Studio Team System 2008 Team Foundation Server, a separate product, can be installed on a shared server, and enhances the features of the Team System package. SQL Server 2008, the latest edition of Microsoft’s flagship database product, was officially launched on the same day as Visual Studio 2008. Unfortunately, “launch” had two different meanings depending on which of the products you were talking about. For Visual Studio 2008, “launch” meant you could download the product from Microsoft’s web site several months before the launch event. For SQL Server, a mirror was used to allow access to the product a few months after the event. That difference was enough to prevent SQL Server 2008 from being the database version bundled with Visual Studio. But you do get SQL Server 2005 in your Visual Studio goodie bag, and you can always upgrade if needed. Beyond the database support, Visual Studio 2008 has been endowed with several new usability and feature enhancements: LINQ-specific features We’ll discuss the new LINQ feature in Chapter 17. Beyond the code changes added to .NET to support LINQ, Visual Studio includes special designers that assist you in programming with LINQ. Support for Windows Presentation Foundation projects Windows Presentation Foundation, formerly code-named Avalon, is a new XML-based user interface system supported by Windows for both desktop and web-based applications. Visual Studio 2008 lets you create WPF-based applica- tion or control projects. This book discusses Windows Presentation Foundation briefly in Chapter 18. Improved HTML (web page) editor The new HTML editor improves on the previous editions found in earlier releases of Visual Studio. The 2008 release includes a “split view” editor show- ing HTML and WYSIWYG views simultaneously (see Figure 1-7). Cascading Style Sheets (CSS) finally get their due with a new CSS style editor and IntelliSense sup- port for CSS content.
  • 41.
    Visual Studio 2008| 21 Targeted library support Earlier releases of Visual Studio were closely tied to the related release of .NET. Visual Studio 2008 continues that tradition through its association with version 3.5 of the .NET Framework. However, you can now target earlier versions of .NET (back through version 2.0) in Visual Studio 2008 with just the click of the mouse. Enhanced debugging support Visual Studio 2008 includes better support for remote debugging, especially on Windows Vista. But the most amazing of the new debugging features is the abil- ity to step into the source code for the .NET Framework libraries, with Visual Studio dynamically obtaining the right version of the source code based on your project type and framework version. Transparent IntelliSense IntelliSense is a productivity tool that helps speed you along in your code-crafting frenzy. But sometimes the IntelliSense windows that popped up would obscure your source code. Visual Studio 2008 now lets you look through the IntelliSense list window just by holding down the Ctrl key (see Figure 1-8). JavaScript IntelliSense and debugging support Although Visual Studio once claimed amnesia concerning Java and JavaScript, it now fully embraces the latter. This enhanced JavaScript environment simplifies the creation of new Ajax applications. While not specifically needed for Visual Basic, this new support is a big plus for those who develop web-based applications. Figure 1-7. Have it both ways: HTML markup and display
  • 42.
    22 | Chapter1: Introducing .NET Despite all these great new features, Microsoft still refuses to implement the most requested Visual Studio feature, Procedure AutoCompletion, in which Visual Studio would create the entire content of a source code procedure based on your entry of its name and the use of the Ctrl-Space bar key combination. Instead, Microsoft frit- ters away its time on other so-called productivity features. With Procedure Auto- Completion, you could write entire applications in minutes. Until that feature becomes available, you and I will have to continue writing software, crafting the quality code that users have come to expect from our fingers. Summary Nearly two decades ago, Visual Basic transformed the Windows development land- scape with its drag-and-drop programming model and its glitzy event-driven devel- opment structure. But Windows has changed a lot since those days of Windows 3.x. As Windows has changed, Visual Basic has changed right along with it. Visual Basic 2008, through its association with the .NET Framework, provides access to the pro- gramming tools needed to develop quality applications for the Windows desktop, the Internet, and the next generation of mobile devices. And Microsoft is not halting this progress with the 2008 release. The next version of Visual Basic, code-named both VBx and Hawaii, promises to include even more advanced features. That release will be built on top of Microsoft’s Dynamic Lan- guage Runtime (DLR), allowing it to freely interact with libraries from languages such as Ruby and Python. Figure 1-8. Seeing right through Visual Studio’s tricks
  • 43.
    Project | 23 Project Welcometo the “Project” section, the part of each chapter where you have an oppor- tunity to get “hands-on” with Visual Studio 2008 and Visual Basic. Development of the Library Project, the main project focus of this book, formally begins in Chapter 3, but there’s still project work to do in the meantime. In this chapter, I’ll introduce you to the sample source code provided with this book, and we’ll take a stab at using it. Since most “Project” sections, including this one, will involve Visual Studio, make sure you have it installed and ready to use. Also, since each “Project” section is designed for you to use interactively with the supplied source code, I will assume that you have downloaded and installed the source code (see Appendix A for instruc- tions), and are viewing the source code with one eye while you read this section with the other. I will print sections of the source code in the book, but with tens of thou- sands of source code lines in the Library Project, I will not be able to print every line here. You will certainly get a lot out of each “Project” section by simply reading it, but you will get even more if you have access to the full source code. In this chapter’s project, we’ll load a sample program into Visual Studio and run it. There are two ways to do this. The first way is just to open the existing project directly from the installation directory. Browse to the directory where you installed this book’s source code, open the Chapter 1 subdirectory, and double-click the Chapter1.vbproj file. This will open the project directly in Visual Studio, ready to use. The second way is to use the chapter-specific project templates to create new projects in Visual Studio. The Setup program for this book’s source code modifies your installation of Visual Studio, adding new entries in the New Project dialog win- dow. Each of these new “project templates” can be used as the starting point for a new Visual Basic project. To load the Chapter 1 sample program using the template, start Visual Studio. The Start Page will appear, as shown way back in Figure 1-6. From the File menu, select New Project to display the New Project dialog window (see Figure 1-9). Your New Project dialog window may differ slightly depending on the features you chose to install with Visual Studio. The available projects are grouped by the descrip- tion in the “Project types” field. For instance, Figure 1-9 shows the various default project types you can create in Visual Basic, including Windows Forms Application (a standard desktop application for the Windows platform), Class Library (a DLL of class- defined features), and Console Application (command-line, text-based applications). To create a new application, first select the project type, select the template to use, and finally enter the name of the new project in the Name field. Clicking the OK but- ton creates a new project.
  • 44.
    24 | Chapter1: Introducing .NET To use the sample Chapter 1 project, select the Programming Visual Basic 2008 entry within the Visual Basic project type, and then select Chapter 1 Sample from the Tem- plates field (see Figure 1-10). Finally, click OK to create the new sample project. Once the project loads, access the program’s main form by double-clicking on the Form1.vb file in the Solution Explorer (see Figure 1-11). This default presentation of Visual Studio Professional Edition includes three editing components: (1) the main editing area, where the view of “Form1” appears; (2) the Solution Explorer panel, which provides access to all files included in the project; and (3) the Properties panel, which lets you edit various aspects of the currently selected item in the main editor area or elsewhere in the user interface. The sample project is pretty basic. It includes one form with a single action button. Clicking this button in the running application displays a simple message. Run the project by pressing the F5 key. When the main form appears, clicking on the “Go Ahead, Click Me!” button displays the message in Figure 1-12 (goal, sweet goal). Figure 1-9. The New Project dialog window: so many choices Figure 1-10. Selecting the Chapter 1 Sample project
  • 45.
    Project | 25 So,what about all that complex code I had to write to develop this multifaceted application? It’s all there for the viewing. From the Solution Explorer panel, right- click on the Form1.vb entry and select View Code from the shortcut menu. (As with most source code samples presented in this book, I have had to slightly adjust the code so that it displays properly on the printed page. Generally, this involves split- ting a long logical line into two or more shorter ones.) Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click MsgBox("Hello, World!") End Sub End Class Figure 1-11. The main form of the sample application Figure 1-12. Hello again, world!
  • 46.
    26 | Chapter1: Introducing .NET We’ll get into the intricacies of such code in later chapters, but here is the gist: • The main form, Form1, is represented in code by a class, named “Form1.” • The form includes a command button named Button1 that exposes a Click event. This event is handled by the Button1_Click procedure, a member of the Form1 class. • The “event handler,” Button1_Click, includes a single statement, a MsgBox state- ment. This statement does the heavy lifting by presenting the ever-friendly mes- sage box to the world. That’s all the code that I wrote for Form1.vb. It sure seems pretty short for all the work it does. There has to be more code hiding somewhere. And sure enough, a half dozen or so additional files are included in the project. Visual Studio hides these by default, since it manages some or all of the content in these files on your behalf. To view the files, click on the Show All Files button (the second toolbar button from the left in the Solution Explorer panel). Look at all those files! To see the additional files associated with Form1, expand it by clicking on the plus sign (+) to its left (see Figure 1-13). Double-click on the Form1.Designer.vb entry to see the code that Visual Studio auto- matically wrote for this form. (Dramatic pause.) Wow! Look at all that scary code. Actually, it’s not that bad. By the end of this book, you will have a firm grasp on all of it. Here in Chapter 1, it’s not really necessary to comprehend it all, but there are a few interesting lines to note. I’m including line numbers to make it easier to find the matching code in Visual Studio. If you want to view line numbers in Visual Studio (Professional Edition instructions listed here): Figure 1-13. Viewing hidden files through the Solution Explorer Click here Then here
  • 47.
    Project | 27 1.Select the Tools ➝ Options menu item to display Visual Studio’s options. 2. Select Text Editor ➝ Basic ➝ Editor from the tree view to the left. If the “Show all settings” field is checked, the last component you click in the tree view will be General, not Editor. 3. Select (check) the Line Numbers field on the right. 4. Click OK to apply the changes. If you’re new to Visual Basic or .NET programming, don’t worry now if this code doesn’t make sense; it will all become clear as you pass through the pages of this book. 01 <Global.Microsoft.VisualBasic.CompilerServices. _ DesignerGenerated( )> _ 02 Partial Public Class Form1 20 <System.Diagnostics.DebuggerNonUserCode( )> _ 21 Protected Overloads Overrides Sub Dispose _ (ByVal disposing As Boolean) These lines show attributes in action. These two attributes (DesignerGenerated and DebuggerNonUserCode) are somewhat like the Obsolete attribute discussed earlier, in that they provide some informational identity to the related code. DesignerGenerated modifies the entire section of Form1’s code, whereas DebuggerNonUserCode modifies only the Dispose member. For clarity, both attributes include their full namespace paths. The Global keyword at the beginning of the DesignerGenerated attribute is actually a Visual Basic keyword that says, “Start at the very tippy-top of the namespace hierarchy; this is not a relative path.” 02 Partial Public Class Form1 Did you see the word Partial right there on line 02? I know I did. Hey, wait a minute; “Public Class Form1” also appeared in the Form1.vb file, but without the Partial keyword. Visual Basic 2008 includes a feature that lets you divide a single class (Form1 in this case) among multiple source code files by including the Partial key- word with at least one of the parts. Pretty cool, eh? It allows Visual Studio to add complex initialization code for your form (as found in this Form1.Designer.vb file) without it bothering your main source code file (Form1.vb). 03 Inherits System.Windows.Forms.Form The Inherits keyword defines the inheritance relationship between this new Form1 class and the previously written System.Windows.Forms.Form class. Form is the “base” class and Form1 is the “derived” class; Form1 inherits all the functionality of the Form class, including its initial look and feel. I’ll discuss these class relationships in more detail in Chapter 8. 44 Friend WithEvents Button1 As System.Windows.Forms.Button
  • 48.
    28 | Chapter1: Introducing .NET Line 44 defines the “Go Ahead, Click Me!” button that appears in the center of the form. All controls that appear on your form are separate instances of classes. (Friend is a declaration statement described in Chapter 6.) The WithEvents keyword indi- cates that this instance of the Button class will respond to events, such as a user click- ing on it with the mouse. This line doesn’t actually create an instance of the Button class; that happens back on line 22. 22 Me.Button1 = New System.Windows.Forms.Button The New keyword creates new instances of classes. In this case, that new instance is assigned to the Button1 class member defined on line 44. At this moment, Button1 is a default instance of the Button class; it doesn’t have any of its custom settings, such as its size and position, or the “Go Ahead, Click Me!” display text. All of that is set in lines 27 to 31: 27 Me.Button1.Location = New System.Drawing.Point(64, 104) 28 Me.Button1.Name = "Button1" 29 Me.Button1.Size = New System.Drawing.Size(152, 23) 30 Me.Button1.TabIndex = 0 31 Me.Button1.Text = "Go Ahead, Click Me!" Finally, the button is “glued” onto the form on line 38: 38 Me.Controls.Add(Me.Button1) This adds the Button1 instance to the list of Controls managed by Form1. The Me key- word used throughout this code refers to the Form1 class itself, so Me.Button1 refers to the Button1 class member specifically in the current Form1 class. Most of the code in this file appears in the InitializeComponent member procedure: 21 Private Sub InitializeComponent( ) ... 43 End Sub When Visual Basic creates an instance of Form1 to display on the screen, it calls the InitializeComponent procedure to do the work of adding the controls to the form. Actually, Visual Basic calls the form’s constructor, which in turn calls InitializeComponent. Constructors are special class members that perform any needed initialization on a class instance. They are called automatically by .NET each time a class instance is created. In Visual Basic, all constructors use the name New, as with the following code: Friend Class ClassWithConstructor Public Sub New( ) ' ----- All initialization code goes here. End Sub End Class I’ll talk much more about constructors in Chapter 8, but for now, locate the con- structor in the code for Form1. (Very long pause.) What? There is no constructor? So, if there isn’t a constructor, how is the InitializeComponent member ever called?
  • 49.
    Project | 29 That’swhat I’d like to know. Actually, when the Visual Basic compiler generates the MSIL code for Form1, it adds a constructor silently, a constructor that calls InitializeComponent. How about that! Why didn’t Microsoft simply include the con- structor’s code right in the source code? It’s a simplicity-for-the-programmer thing. Microsoft needed to have a default constructor that would call InitializeComponent, but it didn’t want a conflict to arise if you added your own default constructor in the non-Designer file. So it hid all the code until it came time to actually compile the form. Clearly, it’s all rather hush-hush, so let’s move on. Well, that’s pretty much the entire code, at least the part that matters to us now. Although we will rarely, if ever, examine the Visual Studio-generated code for the forms in the Library Project, it’s good to see what’s going on behind the scenes. If you were a Visual Basic 6 programmer, you probably looked at the source code for your forms through Notepad at one time or another. If you did, you noticed that the form and all its controls were defined with a hierarchy of special commands, and not with actual Visual Basic code. In .NET, that’s all changed; the form and all its con- trols are created with ordinary Visual Basic code, so you can access it all and see what is really going on. Now, turn to Chapter 2, where I delve into the Visual Basic language itself.
  • 50.
    30 Chapter 2 CHAPTER 2 IntroducingVisual Basic 2 It was a dark and stormy night. Hector gazed wearily through his bloodshot eyes, through the black-rimmed corrective lenses, and through the haze of the fluorescent overhead lights at the phosphor-enriched display. Had it really been four months since he started the six-month project? Did his boss really threaten to fire him after seeing his progress? It seemed like all of those MS-DOS programs he had written for the company over the years meant nothing. Why did he promise to port the com- pany’s main internal system to Windows? In a moment of despair, tears streamed down his cheeks, diluting his last remaining can of Jolt Cola. It’s 8:00 a.m. A loud thump on Hector’s desk brings him suddenly out of his slum- ber, the drool still trickling from the corner of his mouth. What’s that? What’s that box on his desk? “V-i-s-u-a-l B-a-s-i-c?” A note on the box says to rewrite his code in “this.” Desperate to try anything, Hector installs the three floppy disks on his ’386 powerhouse. Six weeks later, Hector has completed the project, ahead of schedule, feature-complete, and with the accolades of his boss and department. And it’s all due to Visual Basic. But VB didn’t just improve his programming life. Overall, he’s happier, has kicked the caffeine habit, is able to bench-press 300 pounds, no longer walks with a limp, has increased libido, and has whiter teeth. “Thank you, Visual Basic 1.0!” The History of the Visual Basic Revolution It’s possible that I got a few of the details wrong in Hector’s life. But for many busi- ness developers, Visual Basic 1.0 was a breath of fresh air. It’s not that they could do more with Visual Basic; programs written in C were more powerful and had greater flexibility. But business programmers didn’t always need that flexibility back in the transition from MS-DOS. They just wanted to manage data, and they didn’t want to worry about how to present every little pixel on the screen. Visual Basic provided the tools to write applications quickly and with much less effort than that required by other Windows development tools and languages.
  • 51.
    The History ofthe Visual Basic Revolution | 31 Visual Basic’s simplicity was embraced by developers everywhere, but the honey- moon quickly wore off. Given the speed at which programs of reasonable quality could be cranked out with Visual Basic, programmers and businesses began demand- ing more. And Microsoft responded. Visual Basic 2.0 and 3.0 were released in quick succession in 1992 and 1993, providing enhanced database integration and addi- tional visual development features. Version 4.0, released in 1996, introduced 32-bit programming to the language, and support for the already-popular Windows 95 platform. Two more quick releases—Visual Basic 5.0 in 1997 and Visual Basic 6.0 in 1998—added even more features and complexity to the otherwise “basic” language, features supporting some but not all object-oriented programming (OOP) tech- niques, ActiveX control development, and web-based logic coding. Microsoft had even integrated the core Visual Basic engine—christened Visual Basic for Applications, or VBA—into its suite of Office products, proclaiming it as the new official macro lan- guage and making the engine available to any third party that wanted to do the same. Seven years after its initial introduction, Visual Basic had taken the programming world by storm. Millions of developers were using the language, including in-house developers at Fortune 500 companies, writing applications that supported core busi- ness functions. VB still retained some of the flavor of the original BASIC language—a “beginner’s” programming language developed by John Kemeny and Thomas Kurtz at Dartmouth College back in 1963. This caused no end of snickering from C and C++ developers and other cola addicts. But VB programmers could see a powerful future for their language of choice. Then the unthinkable happened. Microsoft announced that it would no longer enhance the core Visual Basic engine. Instead, it would rewrite and reimplement Visual Basic using its soon-to-be-released .NET development platform. Yes, Visual Basic would be endowed with all the power promised for Microsoft’s new C- and Java-like language, C#. But for many hardcore VB developers, it was wrong, just wrong. Words were exchanged. Petitions were crafted. Letters to the editor sounded the call to the Visual Basic faithful, urging them to never write a single line of Visual Basic .NET code, ever. In frustration, a Visual Basic user’s group set fire to the entire Microsoft campus in Redmond. Well, that didn’t happen. In fact, nothing bad happened at all. Visual Basic .NET turned out to be a software wunderkind, providing power and features that far sur- passed anything available in Visual Basic 6.0. Its initial release in 2002 was proof that. Visual Basic .NET 2002 was powerful, but it was also a little hard to use, at least compared with version 6.0, and especially when compared with the original 1.0 product. Visual Basic .NET 2003, released just a year later (obviously), was a rela- tively minor update with not much in the way of new or easier functionality. Visual Basic 2005 marked a return to the simpler days of Visual Basic development, days of harmony and peace between “newbies” and their general-purpose program- ming language. Not only did Microsoft remove the term “.NET” from the product
  • 52.
    32 | Chapter2: Introducing Visual Basic name, but it also removed some of the barriers that kept entry-level programmers from approaching the language. Pre-.NET features, such as Edit and Continue and the display of forms through the simple use of the form’s name, once again found their way into the language and into the hearts of software engineers. Visual Basic still retained all the power it gained with .NET, but with true improvements in usability. It was like when they add a label to your toothpaste that says, “New pack- age, same great regular flavor!” Except that Visual Basic’s flavor was improved, too. Visual Basic was once again accessible to first-time developers. Since the 2005 release, Microsoft hasn’t just been sitting on its laurels, as painful as that would be. It dug into its bag of tricks with both hands and came out with Visual Basic 2008, the latest VB offering. Formerly code-named Orcas, Visual Basic 2008 brings additional power and simplicity—yes, both of those—to the language. The biggest new feature, LINQ, makes data access easier by letting you tell the system what data you want instead of detailing how to obtain that data. The language also pro- vides more direct access to new technologies such as Ajax and the Windows Presenta- tion Foundation (WPF). But enough fawning. Let’s start learning about the language. Visual Basic from the Inside Out As a general-purpose development language, Visual Basic includes gobs of features that allow you to develop just about any type of application supported by the Microsoft Windows platform. As such, all of its features could never be covered in a concise, 20- or 30-page chapter, and I won’t try. What I will do in this chapter is to introduce you to the basics of the language, and its core features. Features not cov- ered in this chapter are discussed throughout the rest of the book. It has to be that way, since I don’t want you to finish this chapter and then say to yourself, “That Tim Patrick is so amazing. I learned all I needed to know about Visual Basic in one chap- ter; I didn’t even have to read the rest of the book.” My publisher would not be amused. In the remainder of this chapter, I will take the “from the inside out” approach, start- ing the discussion with the core concepts of logic and data, and adding layer after layer of Visual Basic functionality as you turn the pages. The Basics of Logic and Data Lest you forget it, let me remind you again: computers are not really very smart. They know how to do only the simplest of tasks. If you want them to do anything remotely complex, you have to give precise, step-by-step instructions down to moving individual bits of data—only 1s and 0s, remember—around in memory.
  • 53.
    The Basics ofLogic and Data | 33 Fortunately, most of the code you would ever need at that low level has already been written for you, and incorporated into the Windows operating system and the .NET Framework. Microsoft- and third-party-supplied code libraries give you a lot of pre- written functionality that’s available for use in your own programs. And that’s good, because you would rather be hurtled into space on a giant bungee cord than have to write business applications at the machine code level all day long. Even though you have all this great prewritten code in your arsenal, you still have to tell the computer precisely what you want it to do, in fine detail, or it won’t do it. And that’s where high-level languages like Visual Basic come in. They provide the grammar you need to communicate with the computer. For any given tasks that the computer needs to perform, your job as a programmer is to determine the individual steps to accomplish that task—the logic—and translate those steps into computer- ese using the programming language. As an example, let’s say you receive a request from the sales department for a pro- gram that will reverse all the letters in any chunk of text provided to the program. “Our customers are clamoring for this; we need it by Tuesday,” they say. OK, so first you figure out the logic, and then you implement it in Visual Basic. Using pseudocode, an artificial programming language that you make up yourself to help you write programs, you can sketch out the basics of this task (with leading line numbers): 01 Obtain the original text (or string) from the user. 02 If the user didn't supply any content, then quit now. 03 Prepare a destination for the reversed string, empty for now. 04 Repeat the following until the original string is empty: 05 Copy the last character from the remaining original string. 06 Put that character onto the end of the destination string. 07 Shorten the original string, dropping the last character. 08 [End of repeat section] 09 Show the user the destination string. You could write this logic in many ways; this is just one example. You can now con- vert this pseudocode into your language of choice; in this case, Visual Basic (don’t worry about the syntax details for now): 01 originalText = InputBox("Enter text to reverse.") 02 If (Len(originalText) = 0) Then Return 03 finalText = "" 04 Do While (originalText <> "") 05 oneCharacter = Right(originalText, 1) 06 finalText &= oneCharacter 07 originalText = Left(originalText, _ Len(originalText) - 1) 08 Loop 09 MsgBox("The reverse is: " & finalText)
  • 54.
    34 | Chapter2: Introducing Visual Basic This source code is now ready to be used in a Visual Basic program. And it also dem- onstrates several essential aspects of coding: • The individual steps of the step-by-step instructions are called statements. In Visual Basic, each statement appears on a line by itself. You can break long state- ments into multiple lines by connecting the lines with a space-underscore pair, as shown in line 07 of the code. When a single statement is spread across multi- ple lines in this manner, the entire statement is sometimes called a logical line. Since a single logical line often includes only a single primary Visual Basic action (such as the If or Do action, or the various assignment actions using the equals sign [=]), these actions are also referred to as statements. • The statements of the code are processed one at a time, from top to bottom. However, certain statements alter the normal top-to-bottom flow of the pro- gram, as is done with the Do While...Loop block on lines 04 and 08 of the sam- ple code. Such statements are called flow control statements, and include loops (repeating a block of code), conditions (optionally processing a block of code based on a comparison or calculated result), and jumps (moving immediately to some other section of the code). • Data can be stored in variables, which are named containers for data values. The sample code block includes three variables: originalText, oneCharacter, and finalText, all of which store text (string) data. The .NET Common Type System (CTS) allows you to create variables for four primary types of basic data values: text (both single characters and longer strings), numbers (both integer and deci- mal values), dates (and times), and Booleans (true or false values). You can also build more complex types of data by grouping the basic types. • Data is stored in a variable through an assignment. Generally, this involves plac- ing a variable name on the left side of an = assignment operator, and putting the data or calculation to store in that variable on the right side of that same equals sign. The statement finalText = "" on line 03 stores an empty string ("") in the variable finalText. The &= assignment statement on line 06 shows a slightly dif- ferent assignment syntax. • Statements can include function calls, blocks of prewritten functionality, all squished down into a single name. Function calls do a bunch of work, and then return a final result, a data value. Function names are followed by a set of paren- theses, which may include zero or more arguments, additional data values sup- plied by the calling code that the function uses to generate its result. The sample code includes many examples of function calls, including the Right function on line 05. This function returns a copy of the rightmost characters from another text string. It accepts two parameters: the original string from which to extract the rightmost characters, and an integer value indicating the number of characters to return. The code Right(originalText, 1) returns a copy of the rightmost single character (1) from originalText.
  • 55.
    Another Random ScribdDocument with Unrelated Content
  • 56.
    according to hisdeeds; for he cast his spear against this holy thing, and now the gods have slain him.” Then all cried out together that the Horse of wood must be drawn to the citadel. Whereupon they opened the Scæan Gate, and pulled down the wall that was thereby, and put rollers under the feet of the Horse, and joined ropes thereto. So, in much joy, they drew it into the city, youths and maidens singing about it the while, and laying their hands to the ropes with great gladness. And yet there wanted not signs and tokens of evil to come. Four times it halted on the threshold of the gate, and men might have heard a clashing of arms within. Cassandra also opened her mouth, prophesying evil: but no man heeded her, for that was ever the doom upon her, not to be believed speaking truth. So the men of Troy drew the Horse into the city. And that night they kept a feast to all the gods with great joy, not knowing that the last day of the great city had come. But when night was now fully come, and the men of Troy lay asleep, lo! from the ship of King Agamemnon there rose up a flame for a signal to the Greeks; and these straightway manned their ships, and made across the sea from Tenedos, there being a great calm, and the moon also giving them light. Sinon likewise opened a secret door that was in the great Horse, and the chiefs issued forth therefrom, and opened the gates of the city, slaying those that kept watch. Meanwhile there came a vision to Æneas, who now, Hector being dead, was the chief hope and stay of the men of Troy. It was Hector’s self that he seemed to see, but not such as he had seen him coming back rejoicing with the arms of Achilles, or setting fire to the ships, but even as he lay after that Achilles dragged him at his chariot wheels, covered with dust and blood, his feet swollen and pierced through with thongs. To him said Æneas, not knowing what he said, “Why hast thou tarried so long? Much have we suffered waiting for thee! And what grief hath marked thy face? and whence these wounds?”
  • 57.
    But to thisthe spirit answered nothing, but said, groaning the while, “Fly, son of Venus, fly, and save thee from these flames. The enemy is in the walls, and Troy hath utterly perished. If any hand could have saved our city, this hand had done so. Thou art now the hope of Troy. Take then her gods, and flee with them for company, seeking the city that thou shalt one day build across the sea.” And now the alarm of battle came nearer and nearer, and Æneas, waking from sleep, climbed upon the roof, and looked on the city. As a shepherd stands, and sees a fierce flame sweeping before the south wind over the cornfields or a flood rushing down from the mountains, so he stood. And as he looked, the great palace of Deïphobus sank down in the fire, and the house of Ucalegon, that was hard by, blazed forth, till the sea by Sigeüm shone with the light. Then, scarce knowing what he sought, he girded on his armor, thinking, perchance, that he might yet win some place of vantage, or, at the least, might avenge himself on the enemy, or find honor in his death. But as he passed from out of his house there met him Panthus, the priest of Apollo that was on the citadel, who cried to him, “O Æneas, the glory is departed from Troy, and the Greeks have the mastery in the city; for armed men are coming forth from the great Horse of wood, and thousands also swarm in at the gates, which Sinon hath treacherously opened.” And as he spake others came up under the light of the moon, as Hypanis, and Dymas, and young Corœbus, who had but newly come to Troy, seeking Cassandra to be his wife. To whom Æneas spake: “If ye are minded, my brethren, to follow me to the death, come on. For how things fare this night ye see. The gods who were the stay of this city have departed from it; nor is aught remaining to which we may bring succor. Yet can we die as brave men in battle. And haply he that counts his life to be lost may yet save it.” Then, even as ravening wolves hasten through the mist seeking for prey, so they went through the city, doing dreadful deeds. And for a while the men of Greece fled before them.
  • 58.
    First of allthere met them Androgeos with a great company following him, who, thinking them to be friends, said, “Haste, comrades, why are ye so late? We are spoiling this city of Troy, and ye are but newly come from the ships.” But forthwith, for they answered him not as he had looked for, he knew that he had fallen among enemies. Then even as one who treads upon a snake unawares among thorns, and flies from it when it rises angrily against him with swelling neck, so Androgeos would have fled. But the men of Troy rushed on, and seeing that they knew all the place, and that great fear was upon the Greeks, slew many men. Then said Corœbus, “We have good luck in this matter, my friends. Come now, let us change our shields, and put upon us the armor of these Greeks. For whether we deal with our enemy by craft or by force, who will ask?” Then he took to himself the helmet and shield of Androgeos, and also girded the sword upon him. In like manner did the others, and thus going disguised among the Greeks slew many, so that some again fled to the ships and some were fain to climb into the Horse of wood. But lo! men came dragging by the hair from the temple of Minerva the virgin Cassandra, whom when Corœbus beheld, and how she lifted up her eyes to heaven (but as for her hands, they were bound with iron), he endured not the sight, but threw himself upon those that dragged her, the others following him. Then did a grievous mischance befall them, for the men of Troy that stood upon the roof of the temple cast spears against them, judging them to be enemies. The Greeks also, being wroth that the virgin should be taken from them, fought the more fiercely, and many who had before been put to flight in the city came against them, and prevailed, being indeed many against few. Then first of all fell Corœbus, being slain by Peneleus the Bœotian, and Rhipeus also, the most righteous of all the sons of Troy. But the gods dealt not with him after his righteousness. Hypanis also was slain and Dymas, and Panthus escaped not for all that more than other men he feared the gods and was also the priest of Apollo. Then was Æneas severed from the rest, having with him two only, Iphitus and Pelias, Iphitus being an old man and Pelias sorely
  • 59.
    wounded by Ulysses.And these, hearing a great shouting, hastened to the palace of King Priam, where the battle was fiercer than in any place beside. For some of the Greeks were seeking to climb the walls, laying ladders thereto, whereon they stood, holding forth their shields with their left hands, and with their right grasping the roofs. And the men of Troy, on the other hand, being in the last extremity, tore down the battlements and the gilded beams wherewith the men of old had adorned the palace. Then Æneas, knowing of a secret door whereby the unhappy Andromaché in past days had been wont to enter, bringing her son Astyanax to his grandfather, climbed on to the roof, and joined himself to those that fought therefrom. Now upon this roof there was a tower, whence all Troy could be seen and the camp of the Greeks and the ships. This the men of Troy loosened from its foundations with bars of iron, and thrust it over, so that it fell upon the enemy, slaying many of them. But not the less did others press forward, casting the while stones and javelins and all that came to their hands. Meanwhile others sought to break down the gates of the palace, Pyrrhus, son of Achilles, being foremost among them, clad in shining armor of bronze. Like to a serpent was he, which sleeps indeed during the winter, but in the spring comes forth into the light, full fed on evil herbs, and, having cast his skin and renewed his youth, lifts his head into the light of the sun and hisses with forked tongue. And with Pyrrhus were tall Periphas, and Automedon, who had been armor-bearer to his father Achilles, and following them the youth of Scyros, which was the kingdom of his grandfather Lycomedes. With a great battle-axe he hewed through the doors, breaking down also the door-posts, though they were plated with bronze, making, as it were, a great window, through which a man might see the palace within, the hall of King Priam and of the kings who had reigned aforetime in Troy. But when they that were within perceived it, there arose a great cry of women wailing aloud and clinging to the doors and kissing them. But ever Pyrrhus pressed on, fierce and strong as ever was his father Achilles, nor could aught stand against him, either the doors or they that guarded them. Then, as a river bursts
  • 60.
    its banks andoverflows the plain, so did the sons of Greece rush into the palace. But old Priam, when he saw the enemy in his hall, girded on him his armor, which now by reason of old age he had long laid aside, and took a spear in his hand, and would have gone against the adversary, only Queen Hecuba called to him from where she sat. For she and her daughters had fled to the great altar of the household gods, and sat crowded about it like unto doves that are driven by a storm. Now the altar stood in an open court that was in the midst of the palace, with a great bay-tree above it. So when she saw Priam, how he had girded himself with armor as a youth, she cried to him and said, “What hath bewitched thee, that thou girdest thyself with armor? It is not the sword that shall help us this day; no, not though my own Hector were here, but rather the gods and their altars. Come hither to us, for here thou wilt be safe, or at the least wilt die with us.” So she made the old man sit down in the midst. But lo! there came flying through the palace, Polites, his son, wounded to death by the spear of Pyrrhus, and Pyrrhus close behind him. And he, even as he came into the sight of his father and his mother, fell dead upon the ground. But when King Priam saw it he contained not himself, but cried aloud, “Now may the gods, if there be any justice in heaven, recompense thee for this wickedness, seeing that thou hast not spared to slay the son before his father’s eyes. Great Achilles, whom thou falsely callest thy sire, did not thus to Priam, though he was an enemy, but reverenced right and truth, and gave the body of Hector for burial, and sent me back to my city.” And as he spake the old man cast a spear, but aimless and without force, and that pierced not even the boss of the shield. Then said the son of Achilles, “Go thou and tell my father of his unworthy son and all these evil deeds. And that thou mayest tell him, die!” And as he spake he caught in his left hand the old man’s white hair, and dragged him, slipping the while in the blood of his own son, to the altar, and then, lifting his sword high for a blow, drave it to the
  • 61.
    hilt in theold man’s side. So King Priam, who had ruled mightily over many peoples and countries in the land of Asia, was slain that night, having first seen Troy burning about him, and his citadel laid even with the ground. So was his carcase cast out upon the earth, headless, and without a name.
  • 62.
    CHAPTER VIII. THE ADVENTURESOF ULYSSES. When the great city of Troy was taken, all the chiefs who had fought against it set sail for their homes. But there was wrath in heaven against them, for indeed they had borne themselves haughtily and cruelly in the day of their victory. Therefore they did not all find a safe and happy return. For one was shipwrecked, and another was shamefully slain by his false wife in his palace, and others found all things at home troubled and changed, and were driven to seek new dwellings elsewhere. And some, whose wives and friends and people had been still true to them through those ten long years of absence, were driven far and wide about the world before they saw their native land again. And of all, the wise Ulysses was he who wandered farthest and suffered most. He was well-nigh the last to sail, for he had tarried many days to do pleasure to Agamemnon, lord of all the Greeks. Twelve ships he had with him—twelve he had brought to Troy—and in each there were some fifty men, being scarce half of those that had sailed in them in the old days, so many valiant heroes slept the last sleep by Simoïs and Scamander, and in the plain on the sea-shore, slain in battle or by the shafts of Apollo. First they sailed north-west to the Thracian coast, where the Ciconians dwelt, who had helped the men of Troy. Their city they took, and in it much plunder, slaves and oxen, and jars of fragrant wine, and might have escaped unhurt, but that they stayed to hold
  • 63.
    revel on theshore. For the Ciconians gathered their neighbors, being men of the same blood, and did battle with the invaders, and drove them to their ship. And when Ulysses numbered his men, he found that he had lost six out of each ship. Scarce had he set out again when the wind began to blow fiercely; so, seeing a smooth sandy beach, they drave the ships ashore and dragged them out of reach of the waves, and waited till the storm should abate. And the third morning being fair, they sailed again, and journeyed prosperously till they came to the very end of the great Peloponnesian land, where Cape Malea looks out upon the southern sea. But contrary currents baffled them, so that they could not round it, and the north wind blew so strongly that they must fain drive before it. And on the tenth day they came to the land where the lotus grows—a wondrous fruit, of which whosoever eats cares not to see country or wife or children again. Now the Lotus-eaters, for so they called the people of the land, were a kindly folk, and gave of the fruit to some of the sailors, not meaning them any harm, but thinking it to be the best that they had to give. These, when they had eaten, said that they would not sail any more over the sea; which, when the wise Ulysses heard, he bade their comrades bind them and carry them, sadly complaining, to the ships. Then, the wind having abated, they took to their oars, and rowed for many days till they came to the country where the Cyclopes dwell. Now, a mile or so from the shore there was an island, very fair and fertile, but no man dwells there or tills the soil, and in the island a harbor where a ship may be safe from all winds, and at the head of the harbor a stream falling from a rock, and whispering alders all about it. Into this the ships passed safely, and were hauled up on the beach, and the crews slept by them, waiting for the morning. And the next day they hunted the wild goats, of which there was great store on the island, and feasted right merrily on what they caught, with draughts of red wine which they had carried off from the town of the Ciconians.
  • 64.
    But on themorrow, Ulysses, for he was ever fond of adventure, and would know of every land to which he came what manner of men they were that dwelt there, took one of his twelve ships and bade row to the land. There was a great hill sloping to the shore, and there rose up here and there a smoke from the caves where the Cyclopes dwelt apart, holding no converse with each other, for they were a rude and savage folk, but ruled each his own household, not caring for others. Now very close to the shore was one of these caves, very huge and deep, with laurels round about the mouth, and in front a fold with walls built of rough stone, and shaded by tall oaks and pines. So Ulysses chose out of the crew the twelve bravest, and bade the rest guard the ship, and went to see what manner of dwelling this was, and who abode there. He had his sword by his side, and on his shoulder a mighty skin of wine, sweet-smelling and strong, with which he might win the heart of some fierce savage, should he chance to meet with such, as indeed his prudent heart forecasted that he might. So they entered the cave, and judged that it was the dwelling of some rich and skilful shepherd. For within there were pens for the young of the sheep and of the goats, divided all according to their age, and there were baskets full of cheeses, and full milkpails ranged along the wall. But the Cyclops himself was away in the pastures. Then the companions of Ulysses besought him that he would depart, taking with him, if he would, a store of cheeses and sundry of the lambs and of the kids. But he would not, for he wished to see, after his wont, what manner of host this strange shepherd might be. And truly he saw it to his cost! It was evening when the Cyclops came home, a mighty giant, twenty feet in height, or more. On his shoulder he bore a vast bundle of pine logs for his fire, and threw them down outside the cave with a great crash, and drove the flocks within, and closed the entrance with a huge rock, which twenty wagons and more could not bear. Then he milked the ewes and all the she-goats, and half of the milk he curdled for cheese, and half he set ready for himself, when he should sup. Next he kindled a fire with the pine logs, and
  • 65.
    the flame lightedup all the cave, showing him Ulysses and his comrades. “Who are ye?” cried Polyphemus, for that was the giant’s name. “Are ye traders, or, haply, pirates?” For in those days it was not counted shame to be called a pirate. Ulysses shuddered at the dreadful voice and shape, but bore him bravely, and answered, “We are no pirates, mighty sir, but Greeks, sailing back from Troy, and subjects of the great King Agamemnon, whose fame is spread from one end of heaven to the other. And we are come to beg hospitality of thee in the name of Zeus, who rewards or punishes hosts and guests according as they be faithful the one to the other, or no.” “Nay,” said the giant, “it is but idle talk to tell me of Zeus and the other gods. We Cyclopes take no account of gods, holding ourselves to be much better and stronger than they. But come, tell me where have you left your ship?” But Ulysses saw his thought when he asked about the ship, how he was minded to break it, and take from them all hope of flight. Therefore he answered him craftily,— “Ship have we none, for that which was ours King Poseidon brake, driving it on a jutting rock on this coast, and we whom thou seest are all that are escaped from the waves.” Polyphemus answered nothing, but without more ado caught up two of the men, as a man might catch up the whelps of a dog, and dashed them on the ground, and tore them limb from limb, and devoured them, with huge draughts of milk between, leaving not a morsel, not even the very bones. But the others, when they saw the dreadful deed, could only weep and pray to Zeus for help. And when the giant had ended his foul meal, he lay down among his sheep and slept. Then Ulysses questioned much in his heart whether he should slay the monster as he slept, for he doubted not that his good sword
  • 66.
    would pierce tothe giant’s heart, mighty as he was. But, being very wise, he remembered that, should he slay him, he and his comrades would yet perish miserably. For who should move away the great rock that lay against the door of the cave? So they waited till the morning. And the monster woke, and milked his flocks, and afterwards, seizing two men, devoured them for his meal. Then he went to the pastures, but put the great rock on the mouth of the cave, just as a man puts down the lid upon his quiver. All that day the wise Ulysses was thinking what he might best do to save himself and his companions, and the end of his thinking was this: there was a mighty pole in the cave, green wood of an olive tree, big as a ship’s mast, which Polyphemus purposed to use, when the smoke should have dried it, as a walking staff. Of this he cut off a fathom’s length, and his comrades sharpened it and hardened it in the fire, and then hid it away. At evening the giant came back, and drove his sheep into the cave, nor left the rams outside, as he had been wont to do before, but shut them in. And having duly done his shepherd’s work, he made his cruel feast as before. Then Ulysses came forward with the wine-skin in his hand, and said,— “Drink, Cyclops, now that thou hast feasted. Drink and see what precious things we had in our ship. But no one hereafter will come to thee with such like, if thou dealest with strangers as cruelly as thou hast dealt with us.” Then the Cyclops drank, and was mightily pleased, and said, “Give me again to drink, and tell me thy name, stranger, and I will give thee a gift such as a host should give. In good truth this is a rare liquor. We, too, have vines, but they bear not wine like this, which indeed must be such as the gods drink in heaven.” Then Ulysses gave him the cup again, and he drank. Thrice he gave it to him, and thrice he drank, not knowing what it was, and how it would work within his brain. Then Ulysses spake to him. “Thou didst ask my name, Cyclops. Lo! my name is No Man. And now that thou knowest my name, thou
  • 67.
    shouldst give methy gift.” And he said, “My gift shall be that I will eat thee last of all thy company.” And as he spoke he fell back in a drunken sleep. Then Ulysses bade his comrades be of good courage, for the time was come when they should be delivered. And they thrust the stake of olive wood into the fire till it was ready, green as it was, to burst into flame, and they thrust it into the monster’s eye; for he had but one eye, and that in the midst of his forehead, with the eyebrow below it. And Ulysses leant with all his force upon the stake, and thrust it in with might and main. And the burning wood hissed in the eye, just as the red-hot iron hisses in the water when a man seeks to temper steel for a sword. Then the giant leapt up, and tore away the stake, and cried aloud, so that all the Cyclopes who dwelt on the mountain side heard him and came about his cave, asking him, “What aileth thee, Polyphemus, that thou makest this uproar in the peaceful night, driving away sleep? Is any one robbing thee of thy sheep, or seeking to slay thee by craft or force?” And the giant answered, “No Man slays me by craft.” “Nay, but,” they said, “if no man does thee wrong, we cannot help thee. The sickness which great Zeus may send, who can avoid? Pray to our father, Poseidon, for help.” Then they departed; and Ulysses was glad at heart for the good success of his device, when he said that he was No Man. But the Cyclops rolled away the great stone from the door of the cave, and sat in the midst, stretching out his hands to feel whether perchance the men within the cave would seek to go out among the sheep. Long did Ulysses think how he and his comrades should best escape. At last he lighted upon a good device, and much he thanked Zeus for that this once the giant had driven the rams with the other
  • 68.
    sheep into thecave. For, these being great and strong, he fastened his comrades under the bellies of the beasts, tying them with osier twigs, of which the giant made his bed. One ram he took, and fastened a man beneath it, and two others he set, one on either side. So he did with the six, for but six were left out of the twelve who had ventured with him from the ship. And there was one mighty ram, far larger than all the others, and to this Ulysses clung, grasping the fleece tight with both his hands. So they waited for the morning. And when the morning came, the rams rushed forth to the pasture; but the giant sat in the door and felt the back of each as it went by, nor thought to try what might be underneath. Last of all went the great ram. And the Cyclops knew him as he passed, and said,— “How is this, thou, who art the leader of the flock? Thou art not wont thus to lag behind. Thou hast always been the first to run to the pastures and streams in the morning, and the first to come back to the fold when evening fell; and now thou art last of all. Perhaps thou art troubled about thy master’s eye, which some wretch—No Man, they call him—has destroyed, having first mastered me with wine. He has not escaped, I ween. I would that thou couldst speak, and tell me where he is lurking. Of a truth I would dash out his brains upon the ground, and avenge me of this No Man.” So speaking, he let him pass out of the cave. But when they were out of reach of the giant, Ulysses loosed his hold of the ram, and then unbound his comrades. And they hastened to their ship, not forgetting to drive before them a good store of the Cyclops’ fat sheep. Right glad were those that had abode by the ship to see them. Nor did they lament for those that had died, though they were fain to do so, for Ulysses forbade, fearing lest the noise of their weeping should betray them to the giant, where they were. Then they all climbed into the ship, and sitting well in order on the benches, smote the sea with their oars, laying-to right lustily, that they might the sooner get away from the accursed land. And when they had rowed a hundred yards or so, so that a man’s voice could
  • 69.
    yet be heardby one who stood upon the shore, Ulysses stood up in the ship and shouted,— “He was no coward, O Cyclops, whose comrades thou didst so foully slay in thy den. Justly art thou punished, monster, that devourest thy guests in thy dwelling. May the gods make thee suffer yet worse things than these!” Then the Cyclops, in his wrath, broke off the top of a great hill, a mighty rock, and hurled it where he had heard the voice. Right in front of the ship’s bow it fell, and a great wave rose as it sank, and washed the ship back to the shore. But Ulysses seized a long pole with both hands and pushed the ship from the land, and bade his comrades ply their oars, nodding with his head, for he was too wise to speak, lest the Cyclops should know where they were. Then they rowed with all their might and main. And when they had gotten twice as far as before, Ulysses made as if he would speak again; but his comrades sought to hinder him, saying, “Nay, my lord, anger not the giant any more. Surely we thought before we were lost, when he threw the great rock, and washed our ship back to the shore. And if he hear thee now, he may crush our ship and us, for the man throws a mighty bolt, and throws it far.” But Ulysses would not be persuaded, but stood up and said, “Hear, Cyclops! If any man ask who blinded thee, say that it was the warrior Ulysses, son of Laertes, dwelling in Ithaca.” And the Cyclops answered with a groan, “Of a truth, the old oracles are fulfilled, for long ago there came to this land one Telemus, a prophet, and dwelt among us even to old age. This man foretold to me that one Ulysses would rob me of my sight. But I looked for a great man and a strong, who should subdue me by force, and now a weakling has done the deed, having cheated me with wine. But come thou hither, Ulysses, and I will be a host indeed to thee. Or, at least, may Poseidon give thee such a voyage to thy
  • 70.
    home as Iwould wish thee to have. For know that Poseidon is my sire. May be that he may heal me of my grievous wound.” And Ulysses said, “Would to God I could send thee down to the abode of the dead, where thou wouldst be past all healing, even from Poseidon’s self.” Then Cyclops lifted up his hands to Poseidon and prayed,— “Hear me, Poseidon, if I am indeed thy son and thou my father. May this Ulysses never reach his home! or, if the Fates have ordered that he should reach it, may he come alone, all his comrades lost, and come to find sore trouble in his house!” And as he ended he hurled another mighty rock, which almost lighted on the rudder’s end, yet missed it as by a hair’s breadth. So Ulysses and his comrades escaped, and came to the island of the wild goats, where they found their comrades, who indeed had waited long for them, in sore fear lest they had perished. Then Ulysses divided amongst his company all the sheep which they had taken from the Cyclops. And all, with one consent, gave him for his share the great ram which had carried him out of the cave, and he sacrificed it to Zeus. And all that day they feasted right merrily on the flesh of sheep and on sweet wine, and when the night was come, they lay down upon the shore and slept. After sailing awhile, they came to the island of Æolus, who is the king of the winds, and who dwelt there with his children, six sons and six daughters. Right well did Æolus entertain them, feasting them royally for a whole month, while he heard from Ulysses the story of all that had been done at Troy. And when Ulysses prayed him that he would help him on his way homewards, Æolus hearkened to him, and gave him the skin of an ox in which he had bound all contrary winds, so that they should not hinder him. But he let a gentle west wind blow, that it might carry him and his comrades to their home. For nine days it blew and now they were near to Ithaca, their country, so that they saw lights burning in it, it being night-time. But now, by an ill chance, Ulysses fell asleep, being
  • 71.
    wholly wearied out,for he had held the helm for nine days, nor trusted it to any of his comrades. And while he slept his comrades, who had cast eyes of envy on the great ox-hide, said one to another,— “Strange it is how men love and honor this Ulysses whithersoever he goes. And now he comes back from Troy with much spoil, but we with empty hands. Let us see what it is that Æolus hath given, for doubtless in this ox-hide is much silver and gold.” So they loosed the great bag of ox-hide, and lo! all the winds rushed out, and carried them far away from their country. But Ulysses, waking with the tumult, doubted much whether he should not throw himself into the sea and so die. But he endured, thinking it better to live. Only he veiled his face and so sat, while the ships drave before the winds, till they came once more to the island of Æolus. Then Ulysses went to the palace of the king, and found him feasting with his wife and children, and sat him down on the threshold. Much did they wonder to see him, saying, “What evil power has hindered thee, that thou didst not reach thy country and home?” Then he answered, “Blame not me, but the evil counsels of my comrades, and sleep, which mastered me to my hurt. But do ye help me again.” But they said, “Begone; we may not help him whom the gods hate; and hated of them thou surely art.” So Æolus sent him away. Then again they launched their ships and set forth, toiling wearily at the oars, and sad at heart. Six days they rowed, nor rested at night, and on the seventh they came to Lamos, which was a city of the Læstrygons, in whose land the night is as the day, so that a man might earn double wage, if only he wanted not sleep—shepherd by day and herdsman by night. There was a fair haven with cliffs about it, and a narrow
  • 72.
    mouth with greatrocks on either side. And within are no waves, but always calm. Now Ulysses made fast his ship to the rocks, but the others entered the haven. Then he sent two men and a herald with them, and these came upon a smooth road by which waggons brought down wood from the mountain to the city. Here they met a maiden, the stalwart daughter of Antiphates, king of the land, and asked of her who was lord of that country. Whereupon she showed them her father’s lofty palace. And they, entering this, saw the maiden’s mother, big as a mountain, horrible to behold, who straightway called to Antiphates, her husband. The messengers, indeed, fled to the ships; but he made a great shout, and the Læstrygons came flocking about him, giants, not men. And these broke off great stones from the cliffs, each stone as much as a man could carry, and cast them at the ships, so that they were broken. And the men they speared, as if they were fishes, and devoured them. So it happened to all the ships in the haven. Ulysses only escaped, for he cut the hawser with his sword, and bade his men ply their oars, which indeed they did right willingly. After a while they came to the island of Ææa, where Circé dwelt, who was the daughter of the Sun. Two days and nights they lay upon the shore in great trouble and sorrow. On the third, Ulysses took his spear and sword and climbed a hill that there was, for he wished to see to what manner of land they had come. And having climbed it, he saw the smoke rising from the palace of Circé, where it stood in the midst of a wood. Then he thought awhile: should he go straightway to the palace that he saw, or first return to his comrades on the shore? And this last seemed better; and it chanced that as he went he saw a great stag which was going down to the river to drink, for indeed the sun was now hot, and casting his spear at it he pierced it through. Then he fastened together the feet with green withes and a fathom’s length of rope, and slinging the beast round his neck, so carried it to the ship, leaning on his spear; for indeed it was heavy to bear, nor could any man have carried it on the shoulder with one hand. And when he was come to the ship, he
  • 73.
    cast down hisburden. Now the men were sitting with their faces muffled, so sad were they. But when he bade them be of good cheer, they looked up and marvelled at the great stag. And all that day they feasted on deer’s flesh and sweet wine, and at night lay down to sleep on the shore. But when morning was come, Ulysses called them all together and spake,— “I know not, friends, where we are. Only I know, having seen smoke yesterday from the hill, that there is a dwelling in this island.” It troubled the men much to hear this, for they thought of the Cyclops and of the Læstrygons; and they wailed aloud, but there was no counsel in them. Wherefore Ulysses divided them into two companies, setting Eurylochus over the one and himself over the other, and shook lots in a helmet who should go and search out the island, and the lot of Eurylochus leapt out. So he went, and comrades twenty and two with him. And in an open space in the wood they found the palace of Circé. All about were wolves and lions; yet these harmed not the men, but stood up on their hind legs, fawning upon them, as dogs fawn upon their master when he comes from his meal. And the men were afraid. And they stood in the porch and heard the voice of Circé as she sang with a lovely voice and plied the loom. Then said Polites, who was dearest of all his comrades to Ulysses,— “Some one within plies a great loom, and sings with a loud voice. Some goddess is she, or woman. Let us make haste and call.” So they called to her, and she came out and beckoned to them that they should follow. So they went, in their folly. And she bade them sit, and mixed for them a mess, red wine, and in it barley-meal and cheese and honey, and mighty drugs withal, of which, if a man drank, he forgot all that he loved. And when they had drunk she smote them with her wand. And lo! they had of a sudden the heads and the voices and the bristles of swine, but the heart of a man was in them still. And Circé shut them in sties, and gave them mast and acorns and cornel to eat.
  • 74.
    But Eurylochus fledback to the ship. And for a while he could not speak, so full was his heart of grief, but at the last he told the tale of what had befallen. Then Ulysses took his silver-studded sword and his bow, and bade Eurylochus guide him by the way that he had gone. Nor would he hearken when Eurylochus would have hindered him, but said, “Stay here by the ship, eating and drinking, if it be thy will, but I must go, for necessity constrains me.” And when he had come to the house, there met him Hermes of the golden wand, in the shape of a fair youth, who said to him,— “Art thou come to rescue thy comrades that are now swine in Circé’s house? Nay, but thou shalt never go back thyself. Yet, stay; I will give thee such a drug as shall give thee power to resist all her charms. For when she shall have mixed thee a mess, and smitten thee with her wand, then do thou rush upon her with thy sword, making as if thou wouldst slay her. And when she shall pray for peace, do thou make her swear by the great oath that binds the gods that she will not harm thee.” Then Hermes showed Ulysses a certain herb, whose root was black, but the flower white as milk. “Moly,” the gods call it, and very hard it is for mortal man to find. Then Ulysses went into the house, and all befell as Hermes had told him. For Circé would have changed him as she had changed his comrades. Then he rushed at her with his sword, and made her swear the great oath which binds the gods that she would not harm him. But afterwards, when they sat at meat together, the goddess perceived that he was silent and ate not. Wherefore she said, “Why dost thou sit, Ulysses, as though thou wert dumb? Fearest thou any craft of mine? Nay, but that may not be, for have I not sworn the great oath that binds the gods?” And Ulysses said, “Nay, but who could think of meat and drink when such things had befallen his companions?”
  • 75.
    Then Circé ledthe way, holding her wand in her hand, and opened the doors of the sties, and drove out the swine that had been men. Then she rubbed on each another mighty drug, and the bristles fell from their bodies and they became men, only younger and fairer than before. And when they saw Ulysses they clung to him and wept for joy, and Circé herself was moved with pity. Then said she, “Go, Ulysses, to thy ship, and put away all the goods and tackling in the caves that are on the shore, but come again hither thyself, and bring thy comrades with thee.” Then Ulysses went. Right glad were they who had stayed to see him, glad as are the calves who have been penned in the fold-yard when their mothers come back in the evening. And when he told them what had been, and would have them follow him, they were all willing, save only Eurylochus, who said,— “O ye fools, whither are we going? To the dwelling of Circé, who will change us all into swine, or wolves, or lions, and keep us in prison, even as the Cyclops did! For was it not this same foolhardy Ulysses that lost our comrades there?” Then was Ulysses very wroth, and would have slain Eurylochus, though near of kin to him. But his comrades hindered him, saying, “Let him abide here and keep the ship, if he will. But we will go with thee to the dwelling of Circé.” Then Ulysses forbore. Nor did Eurylochus stay behind, but followed with the rest. So they went to the dwelling of Circé, who feasted them royally, so that they remained with her for a whole year, well content. But when the year was out they said to Ulysses, “It were well to remember thy country, if it is indeed the will of the gods that thou shouldst return thither.” Then Ulysses besought Circé that she would send him on his way homewards, as indeed she had promised to do. And she answered,—
  • 76.
    “I would nothave you abide in my house unwillingly. Yet must thou first go another journey, even to the dwellings of the dead, there to speak with the seer Tiresias.” But Ulysses was sore troubled to hear such things, and wept aloud, saying, “Who shall guide us in this journey?—for never yet did ship make such a voyage as this.” Then said Circé, “Seek no guide; only raise the mast of thy ship and spread the white sails, and sit in peace. So shall the north wind bear thee to the place on the ocean shore where are the groves of Persephoné, tall poplars and willows. There must thou beach thy ship. And after that thou must go alone.” Then she told him all that he must do if he would hold converse with the dead seer Tiresias, and hear what should befall him. So the next morning he roused his companions, telling them that they should now return. But it chanced that one of them, Elpenor by name, was sleeping on the roof, for the coolness, being heavy with wine. And when he heard the stir of his comrades, he rose up, nor thought of the ladder, but fell from the roof and brake his neck. And the rest being assembled, Ulysses told them how they must take another journey first, even to the dwellings of the dead. This they were much troubled to hear, yet they made ready the ship and departed. So they came to the place of which Circé had told them. And when all things had been rightly done, Ulysses saw spirits of the dead. First of all came Elpenor, and he marvelled much to see him, saying,— “How camest thou hither?—on foot or in the ship?” Then he answered, telling how he had died; and he said, “Now, as thou wilt go back, I know, to the island of Circé, suffer me not to remain unburied, but make above me a mound of earth, for men in aftertimes to see, and put upon it my oar, with which I was wont to row while I yet lived.”
  • 77.
    These things Ulyssespromised that he would do. Afterwards came the spirit of Tiresias, holding a sceptre of gold in his hand. And when Ulysses asked him of his return, he said,— “Thy return shall be difficult, because of the anger of Poseidon, whose son thou madest blind. Yet, when thou comest to the island of the Three Capes, where feed the oxen of the Sun, if thou leave these unhurt, thou and thy comrades shall return to Ithaca. But otherwise they shall perish, and thou shalt return, after long time, in a ship not thine own, and shalt find in thy palace, devouring thy goods, men of violence, suitors of thy wife. These shalt thou slay, openly or by craft. Nor yet shalt thou rest, but shalt go to a land where men know not the sea, nor eat their meat with salt; and thou shalt carry thy oar on thy shoulder. And this shall be a sign to thee, when another wayfarer, meeting thee, shall ask whether it be a winnowing fan that thou bearest on thy shoulder; then shalt thou fix thy oar in the earth, and make a sacrifice to Poseidon, and so return. So shalt thou die at last in peace.” Then Tiresias departed. After this he saw his mother, and asked how it fared with his home in Ithaca, and she told him all. And many others he saw, wives and daughters of the heroes of old time. Also there came King Agamemnon, who told him how Ægisthus, with Clytemnestra, his wicked wife, had slain him in his own palace, being newly returned from Troy. Fain would the King have heard how it fared with Orestes, his son, but of this Ulysses could tell him nothing. Then came the spirit of Achilles, and him Ulysses comforted, telling him how bravely and wisely his son Neoptolemus had borne himself in Troy. Also he saw the spirit of Ajax, son of Telamon; but Ajax spake not to him, having great wrath in his heart, because of the arms of Achilles. For the two, Ajax and Ulysses, had contended for them, Achilles being dead, before the assembly of the Greeks, and the Greeks had given them to Ulysses, whereupon Ajax, being very wroth, had laid hands upon himself.
  • 78.
    Welcome to ourwebsite – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com