CONTENTS

INTRODUCTION

PART I: LANGUAGE CONSTRUCTS AND ENVIRONMENT

CHAPTER 1: VISUAL STUDIO 2010

Visual Studio 2010: Express through Ultimate

Visual Basic Keywords and Syntax

Project ProVB_VS2010

Enhancing a Sample Application

Useful Features of Visual Studio 2010

Summary

CHAPTER 2: OBJECTS AND VISUAL BASIC

Object-Oriented Terminology

Working With Visual Basic Types

Commands: Conditional

Value Types (Structures)

Reference Types (Classes)

Parameter Passing

Variable Scope

Working with Objects

Data Type Conversions

Creating Classes

Advanced Concepts

Summary

CHAPTER 3: CUSTOM OBJECTS

Inheritance

Multiple Interfaces

Abstraction

Encapsulation

Polymorphism

Inheritance

Summary

CHAPTER 4: THE COMMON LANGUAGE RUNTIME

Elements of a .NET Application

Versioning and Deployment

Cross-Language Integration

IL Disassembler

Memory Management

Namespaces

Creating Your Own Namespaces

The My Keyword

Extending the My Namespace

Summary

CHAPTER 5: DECLARATIVE PROGRAMMING WITH VISUAL BASIC

Declarative Programming and Visual Basic

Using XAML to Create a Window

XAML Syntax

Using XAML to Declare a Workflow

Summary

CHAPTER 6: EXCEPTION HANDLING AND DEBUGGING

New in Visual Studio 2010 Team System: Historical Debugging

Notes on Compatibility with VB6

Exceptions in .NET

Structured Exception-Handling Keywords

Interoperability with VB6-Style Error Handling

Error Logging

Summary

CHAPTER 7: TEST-DRIVEN DEVELOPMENT

When and How to Test

TDD Tools in Visual Studio

UnitTesting Walk-Through

Other Visual Studio Editions

Third Party Testing Frameworks

Summary

PART II: BUSINESS OBJECTS AND DATA ACCESS

CHAPTER 8: ARRAYS, COLLECTIONS, AND GENERICS

Arrays

Collections

Generics

Creating Generics

Summary

CHAPTER 9: USING XML WITH VISUAL BASIC

An Introduction to XML

XML Serialization

System.Xml Document Support

XML Stream-Style Parsers

XSL Transformations

XML in ASP.NET

LINQ to XML

LINQ Helper XML Objects

Visual Basic and XML Literals

Using LINQ to Query XML Documents

Working with the XML Document

Lambda Expressions in Visual Basic

Summary

CHAPTER 10: ADO.NET AND LINQ

ADO.NET Architecture

Basic ADO.NET Features

.NET Data Providers

The DataSet Component

Working with the Common Provider Model

Connection Pooling in ADO.NET

Transactions and System.Transactions

LINQ to SQL

LINQ to SQL and Visual Basic

How Objects Map to LINQ Objects

Querying the Database

Stored Procedures

Updating the Database

Summary

CHAPTER 11: DATA ACCESS WITH THE ENTITY FRAMEWORK

Object-Relational Mapping

Entity Framework Architecture

Mapping Objects to Entities

Generating the Database from a Model

Summary

CHAPTER 12: WORKING WITH SQL SERVER

SQL Server Compact

SQL Server’s Built-in XML Features

CLR Integration In SQL Server

WCF Data Services

Summary

CHAPTER 13: SERVICES (XML/WCF)

Introduction to Services

The Larger Move to SOA

Building a WCF Service

Building a WCF Consumer

Working with Data Contracts

Namespaces

Summary

PART III: SMART CLIENT APPLICATIONS

CHAPTER 14: WINDOWS FORMS

The System.Windows.Forms Namespace

Using Forms

Controls

Other Handy Programming Tips

Summary

CHAPTER 15: ADVANCED WINDOWS FORMS

Packaging Logic in Visual Controls

Custom Controls in Windows Forms

Inheriting from an Existing Control

The Control and UserControl Base Classes

A Composite UserControl

Building a Control from Scratch

Attaching an Icon for the Toolbox

Embedding Controls in Other Controls

Summary

CHAPTER 16: USER CONTROLS COMBINING WPF AND WINDOWS FORMS

The Integration Library

Hosting WPF Controls in Windows Forms

Hosting Windows Forms Controls in WPF

Integration Limitations

Summary

CHAPTER 17: WPF DESKTOP APPLICATIONS

What, Where, Why, How — WPF Strategy

Raster Graphics and Vector Graphics

Should Your Next Windows Project Use WPF?

Creating a WPF Application

Summary

CHAPTER 18: EXPRESSION BLEND 3

Getting to Know Blend

SketchFlow

Summary

CHAPTER 19: SILVERLIGHT

What Is Silverlight?

Starting a Silverlight Project

Silverlight Solution

Controls

Adding Items to the Silverlight Project

Silverlight Out of the Browser

Summary

PART IV: INTERNET APPLICATIONS

CHAPTER 20: SILVERLIGHT AND SERVICES

Services and Silverlight

Model-View-ViewModel

Summary

CHAPTER 21: WORKING WITH ASP.NET

The History of ASP.NET

Key Features of ASP.NET

Visual Studio Support for ASP.NET

Building ASP.NET Applications Using Web Forms

Data-Driven Applications

Summary

CHAPTER 22: ASP.NET ADVANCED FEATURES

Master Pages

Navigation

Working with the ASP.NET Provider Model

Membership and Role Management

Profile Properties

Microsoft Ajax (ASP.NET AJAX)

Summary

CHAPTER 23: ASP.NET MVC

Model-View-Controller and ASP.NET

Building an ASP.NET MVC Application

Summary

CHAPTER 24: SHAREPOINT 2010 DEVELOPMENT

Introduction

Features and the Solutions Framework

Visual Studio Tools for SharePoint Development

The SharePoint 2010 Object Models

Building Web Parts

Summary

PART V: LIBRARIES AND SPECIALIZED TOPICS

CHAPTER 25: VISUAL STUDIO TOOLS FOR OFFICE

Examining the VSTO Releases

Office Business Application Architecture

Working with Both VBA and VSTO

Creating a Document Template (Word)

Creating an Office Add-In (Excel)

Outlook Form Regions

Summary

CHAPTER 26: WINDOWS WORKFLOW FOUNDATION

Workflow in Applications

Building Workflows

Rehosting the Workflow Designer

Summary

CHAPTER 27: LOCALIZATION

Cultures and Regions

Translating Values and Behaviors

ASP.NET Resource Files

Resource Files in Windows Forms

Summary

CHAPTER 28: COM-INTEROP

Understanding COM

COM and .NET in Practice

ActiveX Controls

Using .NET Components in the COM World

P/Invoke

Summary

CHAPTER 29: NETWORK PROGRAMMING

Protocols, Addresses, and Ports

The System.Net Namespace

Sockets

Using Internet Explorer in Your Applications

Summary

CHAPTER 30: APPLICATION SERVICES

Using IIS for Application Services

Windows Services

Characteristics of a Windows Service

Interacting with Windows Services

Creating a Windows Service

Creating a Windows Service in Visual Basic

Creating a File Watcher Service

Communicating with the Service

Custom Commands

Passing Strings to a Service

Debugging the Service

Summary

CHAPTER 31: ASSEMBLIES AND REFLECTION

Assemblies

The Manifest

Assemblies and Deployment

Versioning Issues

Basics of Reflection

Dynamic Loading of Assemblies

Summary

CHAPTER 32: SECURITY IN THE .NET FRAMEWORK

Security Concepts and Definitions

Permissions in the System.Security.Permissions Namespace

Managing Code Access Permission Sets

User Access Control

Defining Your Application UAC Settings

Encryption Basics

Summary

CHAPTER 33: PARALLEL PROGRAMMING USING TASKS AND THREADS

Launching Parallel Tasks

Transforming Sequential Code to Parallel Code

Parallelizing Loops

Specifying the Desired Degree of Parallelism

Creating and Managing Tasks

Summary

CHAPTER 34: DEPLOYMENT

Application Deployment

Choosing a Framework Version

Visual Studio Deployment Projects

Modifying the Deployment Project

Internet Deployment of Windows Applications

IIS Web Deployment Tool

Summary

Appendix A: The Visual Basic Compiler

Appendix B: Visual Basic Power Packs Tools

Appendix C: Workflow 2008 Specifics

Appendix D: Enterprise Services

Appendix E: Programming for the Cloud

Index

Professional Visual Basic® 2010 and .NET 4

Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com

Copyright © 2010 by Wiley Publishing, Inc., Indianapolis, Indiana

Published by Wiley Publishing, Inc., Indianapolis, Indiana

Published simultaneously in Canada

ISBN: 978-0-470-50224-2

Manufactured in the United States of America

10 9 8 7 6 5 4 3 2 1

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.

Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.

For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.

Library of Congress Control Number: 2010921246

Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. Visual Basic is a registered trademark of Microsoft Corporation in the United States and/or other countries. All other trademarks are the property of their respective owners. Wiley Publishing, Inc. is not associated with any product or vendor mentioned in this book.

To my wonderful wife, Tracie, who is forced to carry on while I isolate myself to concentrate on writing. And to the next generation of children who have joined our extended Sheldon family (my own and my brothers’) in the past five years — Nick, Elena, Ben, Billy V, Abigail, and Johnny — each and every one of you is a valuable part of our lives.

—BILL SHELDON

I owe tremendous thanks to my family, who have somehow learned to put up with marathon writing sessions, and to my business partner, Gary Bailey, for keeping our clients happy while I’m writing.

—BILLY HOLLIS

To Babi, for keeping me alive and putting up with me — hopefully, for a long time to come.

—KENT SHARKEY

To my beautiful wife, Jennifer, who was my greatest encouragement despite the long days of writing and working. And to my loving daughter, Kathryn, who always managed to put a smile on my face after a long day.

—JONATHAN MARBUTT

To my Dad, who did not complain too much about the weekends I spent writing instead of playing golf with him.

—ROB WINDSOR

To my son, Kevin

—GASTÓN HILLAR

ABOUT THE AUTHORS

BILL SHELDON is a software architect and engineer, originally from Baltimore, Maryland. Holding a degree in computer science from the Illinois Institute of Technology (IIT), Bill has been actively employed as a software engineer since resigning his commission with the United States Navy. He is a Microsoft MVP for Visual Basic employed in Carlsbad, California. Bill also works as an instructor for .NET courses at the University of California San Diego Extension. In addition to writing books, Bill has published dozens of articles, including the Developer Update Newsletter, SQL Server Magazine feature articles, and other Penton publications. He is an established online presenter for MSDN and speaks at live events such as VSLive, DevConnections, Office Developers Conference, and community events such as user groups and code camp. Bill is an avid cyclist and is active in the fight against diabetes. Bill can be tracked down through his blog: www.nerdnotes.net/blog or via Twitter: NerdNotes.

BILLY HOLLIS is an author and software consultant based in Nashville, Tennessee. Billy was co-author of the first book ever published on Visual Basic .NET, as well as many other books on software development. He is a member of the Microsoft Regional Director program and a Microsoft MVP. In 2002, Billy was selected as one of the original .NET “Software Legends.” He is heavily involved with consulting, training, and development on the .NET platform, focusing on architecture, smart-client development, commercial packages, and user-interface technologies. He regularly speaks on software development at major conferences all over the world, including Microsoft’s PDC and TechEd events, DevConnections, VSLive, and architecture events such as the Patterns and Practices Architect Summit.

KENT SHARKEY is an independent consultant who lives and codes in Comox, British Columbia. Before going solo, Kent worked at Microsoft as a technical evangelist and content strategist, promoting the use of .NET technologies. He lives with his wife, Margaret, and three “children” — Squirrel, Cica, and Toffee.

JONATHAN MARBUTT is Vice President of Development for WayCool Software, Inc., based in Birmingham, AL. He has been working professionally in software development since 1996, where he has covered various Microsoft technologies from VB6 to .NET. Over the recent years, Jonathan has been developing with Silverlight to build Rich Internet Line of Business applications for the non-profit sector. Through this development, he is beginning to focus on User Experience (UX) by utilizing Microsoft products like Expression Blend and technologies like Silverlight. For more information,contact Jonathan at www.jmtechware.com.

ROB WINDSOR is a developer, trainer, writer and Senior Consultant with ObjectSharp Consulting — a Microsoft Gold Partner based in Toronto, Canada. He has over fifteen years experience developing rich-client and web applications with Delphi, VB, C# and VB.NET and is currently spending a majority of his time working with SharePoint. Rob is a member of both the INETA Speakers Bureau and the MSDN Canada Speakers Bureau and is a regular speaker at conferences, code camps, and user groups across North America and Europe. He is President of the Toronto Visual Basic User Group and has been recognized as a Microsoft Most Valuable Professional for his involvement in the developer community.

GASTÓN C. HILLAR has been working with computers since he was eight. He began programming with the legendary Texas TI-99/4A and Commodore 64 home computers in the early 80s. He has worked as developer, architect, and project manager for many companies in Buenos Aires, Argentina. Now, he is an independent IT consultant working for several Spanish, German, and Latin American companies, and a freelance author. He is always looking for new adventures around the world.

Gastón is the author of more than forty books in Spanish and has written two books in English. He contributes to Dr. Dobb’s Go Parallel programming portal at www.ddj.com/go-parallel/, Dr. Dobb’s at http://drdobbs.com, and is a guest blogger at Intel Software Network at http://software.intel.com.

He lives with his wife, Vanesa, and his son, Kevin. When not tinkering with computers, he enjoys developing and playing with wireless virtual reality devices and electronics toys with his father, his son, and his nephew Nico.

You can reach him at: gastonhillar@hotmail.com

You can follow him on Twitter at: http://twitter.com/gastonhillar

Gastón’s blog is at: http://csharpmulticore.blogspot.com

ABOUT THE TECHNICAL EDITORS

DIANNE SIEBOLD is a software developer and writer specializing in VB, C#, .NET Framework, WCF, ADO, and SQL Server. She has worked for a number of Microsoft partners writing enterprise applications with an emphasis on services and data access. Currently, she works for Microsoft writing developer documentation in the Dynamics product group. Reach her by e-mail at dsiebold@earthlink.net.

DOUG PARSONS is a .NET Software Architect and professional Technical Editor who specializes in C#, SQL Server, and numerous architectural paradigms. Over the course of his career, he has worked on a myriad of projects; most notably, however, was the United States 2008 Presidential Campaign website of John McCain. He is currently employed by NJI New Media, writing software for clients of a predominantly political nature. He can be reached by email at douglas.c.parsons@gmail.com.

DOUG WATERFIELD is a software architect and engineer who lives with his family in Avon, Indiana. Since earning a degree in computer science from Rose-Hulman Institute of Technology, Doug has been designing and developing commercial and enterprise applications in a wide variety of technologies. Doug led development teams and departments for several firms before becoming an independent consultant with a focus on .NET technologies. He is a retired officer in the US Army Reserve and serves as a volunteer leader in Cub Scouts and Boy Scouts.

CREDITS

ACQUISITIONS EDITOR
Paul Reese

SENIOR PROJECT EDITOR
Adaobi Obi Tulton

TECHNICAL EDITORS
Dianne Siebold
Doug Parsons
Doug Waterfield

SENIOR PRODUCTION EDITOR
Debra Banninger

COPY EDITOR
Luann Rouff

EDITORIAL DIRECTOR
Robyn B. Siesky

EDITORIAL MANAGER
Mary Beth Wakefield

ASSOCIATE DIRECTOR OF MARKETING
David Mayhew

PRODUCTION MANAGER
Tim Tate

VICE PRESIDENT AND EXECUTIVE GROUP PUBLISHER
Richard Swadley

VICE PRESIDENT AND EXECUTIVE PUBLISHER
Barry Pruett

ASSOCIATE PUBLISHER
Jim Minatel

PROJECT COORDINATOR, COVER
Lynsey Stanford

PROOFREADERS
Nancy Carrasco
Beth Prouty, Word One

INDEXER
Robert Swanson

COVER DESIGNER
Michael E. Trent

COVER IMAGE
© Dan Barnes/istockphoto

ACKNOWLEDGMENTS

AS WITH ANY MAJOR PROJECT PUTTING A BOOK OF this size and scope together is a team effort and we as authors were really lucky to have such a great support team helping to keep us on track and focused. I’d like to publicly call out and thank our editor, Adaobi, who managed to turn around several of the late chapters (those would be mine) in an incredibly short time, and our technical editors, in particular Dianne, who did an outstanding job. They found hundreds of issues so that our readers wouldn’t need to, and helped ensure that everything worked and flowed in a logical fashion.

—BILL SHELDON

WHILE WRITING can be a solitary activity, writing for a book definitely is not, and I have many people to thank for getting me here.

Thank you to all my coworkers who picked up the slack while I worked on this (Oh, wait — I work alone — never mind). Thank you to my co-authors, and my fine editors: Adaobi Obi Tulton, Paul Reese, and Dianne Siebold. If there is any quality here, it is likely due to their hard work.

I am definitely grateful to all the people who regularly put up with my negativity, and help me to become better: Eileen, Chris, Tharun, Kraig and Duncan. Thank you, thank you, thank you.

And finally, thanks to all of you that have selected this book. I hope it helps.

—KENT SHARKEY

THANKS TO BETH MASSI for being too busy to work on this project and thanks to the people at Wrox for accepting Beth’s suggestion that I would be a suitable replacement.

As a first time author, I have to give special thanks to Adaobi Obi Tulton, Dianne Siebold, Doug Parsons, Doug Waterfield, and Luann Rouff for helping me make my work appear as if it was written by a professional author. I’m sure it wasn’t easy.

Finally, I’d like to thank those who helped me advance professionally to the point that this opportunity was even possible: Craig Flanagan, Sasha Krsmanovic, Jean-Rene Roy, Mark Dunn, Carl Franklin, Richard Campbell, all the Canadian RDs, and everyone at ObjectSharp.

—ROB WINDSOR

I WISH TO ACKNOWLEDGE Paul Reese and Adaobi Obi Tulton; they had a lot of patience and they allowed me to make the necessary changes to my chapter in order to include the most appropriate information about the new parallel programming features introduced in .NET Framework 4 and Visual Basic 2010.

Special thanks go to my wife, Vanesa S. Olsen, because she understood that I needed to work with many computers at the same time to test each code snippet.

—GASTÓN C. HILLAR

INTRODUCTION

IN 2002, VISUAL BASIC EXPERIENCED the biggest leap in innovation since it was released, with the introduction of Visual Basic .NET (as it was then named). After more than a decade, Visual Basic was overdue for a major overhaul. Nevertheless, .NET went beyond an overhaul. The changes affected almost every aspect of development with Visual Basic. The entire runtime model shifted to a new common language runtime (CLR) environment and the language went from object-based to object-oriented. From integrating Internet functionality to creating object-oriented frameworks, Visual Basic .NET challenged traditional VB developers to learn dramatic new concepts and techniques.

The various releases since then have continued to provide even more enhancements to the Visual Basic language. New features have been added that both cement this language’s position as a true object-oriented language and provide access to new and better technologies. Visual Basic 2010 continues this evolution; and while it remains a challenge for VB6 developers to learn, it’s an easy road for those with any familiarity with previous versions, and this book is here to help you on your way.

Visual Studio 2010 ships with version 4 of the .NET Framework. This book provides details about not only the latest version of Visual Basic — version 10 — but also the new .NET Framework 4. Combined, these products give Visual Basic developers the capability to build applications using Windows Presentation Foundation (WPF), Windows Forms, Visual Studio Tools for Office, and applications and libraries based upon the Windows Communication Foundation (WCF), the Windows Workflow Foundation (WF), and SharePoint.

The .NET Framework 4 is the most significant change to the core framework since .NET Framework 2.0. Fortunately, as with Visual Studio 2008, Visual Studio 2010 enables developers to continue to build and deploy applications that target both the newly released version of .NET, and previously released versions of the .NET Framework.

For those who may only now be transitioning from the VB6 development model, you’ll find that this version of Visual Basic Professional is targeted less than ever at traditional VB6 code differences. With each of the four .NET versions, the core language has continued to progress and differentiate itself from where it was 10+ years ago. In some cases, the same functionality is implemented in a different way. This was not done arbitrarily — there are good reasons for the changes. However, you must be prepared to unlearn old habits and form new ones.

Next, you must be open to the new concepts. Full object orientation, new component techniques, new visual tools for both local and Internet interfaces — all of these and more must become part of your skill set to effectively develop applications in Visual Basic.

This book covers Visual Basic from start to finish. It starts by introducing Visual Studio 2010. As the tool you’ll use to work with Visual Basic, understanding Visual Studio’s core capabilities is key to your success and enjoyment with building .NET applications. In these pages, you have the opportunity to learn everything from database access, Language Integrated Queries (LINQ), and the Entity Framework, to integration with other technologies such as WPF, WCF, and service-based solutions. Along with investigating new features in detail, you’ll see that Visual Basic 10 has emerged as a powerful yet easy-to-use language that enables you to target the Internet just as easily as the desktop. This book covers the .NET Framework 4.

THE FUTURE OF VISUAL BASIC

Early in the adoption cycle of .NET, Microsoft’s new language, C#, got the lion’s share of attention. However, as .NET adoption has increased, Visual Basic’s continuing importance has also been apparent. Microsoft has publicly stated that it considers Visual Basic to be the language of choice for applications for which developer productivity is one of the highest priorities.

Future development of Visual Basic will emphasize capabilities that enable access to the whole expanse of the .NET Framework in the most productive way. In the past, it was common for Microsoft and others to “target” different development styles; with Visual Studio 2010, Microsoft announced that VB and C# will follow a process of coevolution. As new language features are developed, they will be introduced to both Visual Basic and C# at the same time. This release is the first step in that process, although it’s not complete at this time.

Coevolution does not mean that the languages will look the same, but rather that they will support the same capabilities. For example, Visual Basic has XML literals, but that doesn’t mean C# will get exactly the same functionality, as C# has the capability to work with XML through the existing framework classes. The old process of first introducing a feature in Visual Basic and then in the next release having C# catch up, and vice versa, is over. As new capabilities and features are introduced, they will be introduced to both Visual Basic and C# at the same time.

As mentioned earlier, although the changes aren’t complete, the next version of Visual Basic will be coordinated with a new release of Visual Studio, and the capabilities of C# and Visual Basic should fully mirror each other, as both will be first-class .NET development languages. That fits the traditional role of Visual Basic as the language developers use in the real world to create business applications as quickly as possible.

One of the most important advantages of the .NET Framework is that it enables applications to be written with dramatically less code. In the world of business applications, the goal is to concentrate on writing business logic and to eliminate routine coding tasks as much as possible. In other words, of greatest value in this new paradigm is writing robust, useful applications without churning out a lot of code.

Visual Basic is an excellent fit for this type of development, which makes up the bulk of software development in today’s economy. Moreover, it will grow to be an even better fit as it is refined and evolves for exactly that purpose.

WHO THIS BOOK IS FOR

This book was written to help experienced developers learn Visual Basic 2010. For those who are just starting the transition from earlier versions to those who have used Visual Basic for a while and need to gain a deeper understanding, this book provides information on the most common programming tasks and concepts you need.

Professional Visual Basic 2010 offers a wide-ranging presentation of Visual Basic concepts, but the .NET Framework is so large and comprehensive that no single book can cover it all. The focus in this book is providing a working knowledge of key technologies that are important to Visual Basic developers. It provides adequate knowledge for a developer to work in any of these areas, although developers may choose to add to their knowledge by leveraging a book dedicated entirely to a single technology area.

WHAT YOU NEED TO USE THIS BOOK

Although it is possible to create Visual Basic applications using the command-line tools contained in the .NET Framework, you’ll want Visual Studio 2010 (Standard Edition or higher), which includes the .NET Framework 4, to get the most out of this book. You may use Visual Basic Express Edition instead, but in some cases the exercises won’t work because functionalities and capabilities are not available in this limited version. In addition, note the following:

You’ll need .NET Framework 4, which is installed with whatever version of Visual Studio 2010 you select.

Some chapters make use of SQL Server 2008. You can run the example code using Microsoft’s SQL Express, which ships with Visual Studio 2010.

Chapter 7 makes reference to the Unit Test tools, which are included with Visual Studio Professional Edition or higher.

Several chapters make use of Internet Information Services (IIS). IIS is part of every operating system released by Microsoft since Windows XP, but on newer operating systems you’ll need to run as administrator to develop against it. Alternatively, you can leverage the development server that ships with Visual Studio 2010.

Chapter 18 makes use of Expression Blend 3.0. Blend is available with upper-tier MSDN subscriptions, but you should be able to leverage a trial version to explore the capabilities described in that chapter.

Chapter 24 looks at SharePoint development. SharePoint services ship with Windows Server versions. The full Microsoft Office SharePoint Server is a product that requires a license, although MSDN owners can get access to a development server.

Chapter 25 looks at Visual Studio Tools for Office, so in order to leverage products built against the Office suite, you’ll need a copy of the specified product(s).

Appendix D makes use of MSMQ to work with queued transactions. MSMQ also ships with Windows, but it is not installed by default.

Appendix E looks at the online services that are accessible to Microsoft developers. Azure has a trial period so that you can work with the examples in that chapter.

WHAT THIS BOOK COVERS

Part I, “Language Constructs and Environment” — The first seven chapters of the book focus on core language elements and development tools used by Visual Basic developers. This section introduces Visual Studio 2010, objects, syntax, and debugging.

Chapter 1, “Visual Studio 2010” — Start with the environment where you will work with Visual Basic 10. This chapter looks at the newly redesigned WPF-based Visual Studio development environment. Introducing a simple Windows forms project and reviewing key capabilities like the debugger, this chapter will help you to prepare for and become comfortable with this powerful environment.

Chapter 2, “Objects and Visual Basic” — This is the first of three chapters that explore object-oriented programming and the role of the .NET Framework in Visual Basic. This chapter introduces the basics of objects, types, type conversion, reference types, and the key syntax which make up the core of Visual Basic.

Chapter 3, “Custom Objects” — This chapter examines creating objects, and describes how they fit within Visual Basic. Starting with inheritance, you create simple and abstract classes and learn how to create base classes from which other classes can be derived. This chapter puts the theory of object-oriented development into practice. The four defining object-oriented concepts (abstraction, encapsulation, polymorphism, inheritance) are described, and you will learn how these concepts can be applied in design and development to create effective object-oriented applications.

Chapter 4, “The Common Language Runtime” — This chapter examines the core of the .NET platform: the common language runtime (CLR). The CLR is responsible for managing the execution of code compiled for the .NET platform. You learn about versioning and deployment, memory management, cross-language integration, metadata, and the IL Disassembler. The chapter also introduces namespaces and their hierarchical structure. An explanation of namespaces and some common examples are provided. In addition, you learn about custom namespaces, and how to import and alias existing namespaces within projects. This chapter also looks at the My namespace available in Visual Basic.

Chapter 5, “Declarative Programming with Visual Basic” — The introduction of Windows Presentation Foundation, Windows Workflow (WF), and Silverlight brought a new syntax to .NET: XAML. XML for Application Markup Language, commonly pronounced “zamel,” is the core of a new declarative programming model. Using this model, developers describe what they want — e.g., a window. The code that implements the creation of that window is abstracted from the request. As noted, XAML is an enabling syntax for several new technology feature sets. This chapter introduces the core common elements of the XAML syntax so that the other chapters that leverage this syntax have a common baseline.

Chapter 6, “Exception Handling and Debugging” — This chapter covers how error handling and debugging work in Visual Basic 2010 by discussing the CLR exception handler and the Try…Catch…Finally structure. Also covered are error and trace logging, and how you can use these methods to obtain feedback about how your program is working.

Chapter 7, “Test-Driven Development” — This chapter introduces the concepts of test-driven development (TDD) with Visual Studio 2010 and the unit test tools.

Part II, “Business Objects and Data Access” — The next seven chapters, Chapter 8 through Chapter 14, look at common structures used to contain and access data. This includes framework elements such as arrays and collections, XML, database access, and Windows Communication Foundation (WCF) services. These chapters focus on gathering data for use within your applications.

Chapter 8, “Arrays, Collections, Generics” — This chapter focuses on introducing arrays and collections as a baseline for having a sets of related items. It then expands on these basic structures by exploring generics. Introduced with version 2.0 of the .NET Framework, generics enable strongly typed collections. One of the important new features associated with .NET Framework 4 is the extension of generic support to include covariance.

Chapter 9, “Using XML with Visual Basic” — This chapter presents the features of the .NET Framework that facilitate the generation and manipulation of XML. We describe the .NET Framework’s XML-related namespaces, and a subset of the classes exposed by these namespaces is examined in detail. This chapter also touches on a set of technologies that utilize XML — specifically, ADO.NET and SQL Server — and then describes in detail how to work with LINQ for XML.

Chapter 10, “ADO.NET and LINQ” — This chapter focuses on what you need to know about the ADO.NET object model in order to build flexible, fast, and scalable data-access objects and applications. The evolution of ADO into ADO.NET is explored, and the main objects in ADO.NET that you need to understand in order to build data access into your .NET applications are explained. Additionally, this chapter delves into LINQ to SQL. LINQ offers the capability to easily access underlying data — basically a layer on top of ADO.NET. Microsoft has provided LINQ as a lightweight façade that provides a strongly typed interface to the underlying data stores.

Chapter 11, “Data Access with the Entity Framework” — One of the major enhancements being released with Visual Studio 2010 is the Entity Framework (EF). The EF represents Microsoft’s implementation of an Entity Relationship Modeling (ERM) tool. Using EF, developers can generate classes to represent the data structures that are defined within SQL Server, and leverage these objects within their applications.

Chapter 12, “Working with SQL Server” — This chapter describes how to work with SQL Server 2008 along with your .NET applications. SQL Server provides a strong connection to your applications, and this chapter explains how to effectively utilize this powerful database.

Chapter 13, “Services (XML/WCF)” — This chapter looks at the newest way to build service-oriented components that allow for standards-based communications over a number of protocols. WCF is Microsoft’s latest answer for component communications within and outside of the enterprise. Additionally, this chapter reviews the creation and consumption of XML Web services. The abstract classes provided by the CLR to set up and work with Web services are discussed, as well as some of the technologies that support Web services. Also examined are some of the disadvantages to using any distributed architecture.

Part III, “Smart Client Applications” — The next six chapters, Chapter 15 through Chapter 20, focus on creating client applications. Starting with the Windows Forms application model, which was introduced with .NET 1.0, these chapters move through the migration to Windows Presentation Foundation and the introduction of the Blend design engine and Silverlight.

Chapter 14, “Windows Forms” — This chapter looks at Windows Forms, concentrating primarily on forms and built-in controls. What is new and what has been changed from previous versions of Visual Basic are discussed, along with the System.Windows.Forms namespace.

Chapter 15, “Advanced Windows Forms” — This chapter explores some of the more advanced features that are available to you in building your Windows Forms applications.

Chapter 16, “User Controls Combining WPF and Windows Forms” — One of the best practices for creating Windows client applications is the use of user controls. User controls allow for the encapsulation of related user interface elements. In addition, these controls become key for the migration from Windows Forms to WPF. Because many organizations have made significant investments in Windows Forms and are not ready to fully switch their applications to this new technology, Microsoft has provided significant support to integrate WPF into your Windows Forms applications, as well as the capability to bring your Windows Forms components to a WPF application.

Chapter 17, “WPF Desktop Applications” — A technology that was introduced in .NET 3.0, Windows Presentation Foundation offers an alternate mechanism for building desktop applications. This chapter describes how WPF provides a presentation layer that you should find rather fluid and enriching.

Chapter 18, “Expression Blend 3” — In conjunction with the release of WPF, Microsoft introduced a new suite of tools called “Expression Studio.” These tools target building rich user interfaces based on XAML. The Blend tool (included in Expression Studio) in particular has proven valuable for designing WPF user interfaces. This chapter introduces you to Expression Blend, which provides a powerful set of tools for designing applications and working with XAML.

Chapter 19, “Silverlight” — This chapter looks at the latest use of XAML for building user interfaces: Silverlight. Silverlight provides a platform-independent solution for .NET-based client application development. Silverlight enables developers to use XAML markup, and brings a more fluid experience to the end user in the browser or on the desktop.

Part IV, “Internet Applications” — The next five chapters, Chapter 20 through Chapter 24, focus on creating applications for the Web. Leveraging Silverlight, which has a client-like feel, these chapters introduce ASP.NET and capabilities such as AJAX and MVC, including fully cloud-hosted solutions, and introduce SharePoint.

Chapter 20, “Silverlight and Services” — Once you’ve been introduced to Silverlight and what it can do for client applications, this chapter looks at both hosting Silverlight within your website and hooking it to Web services to provide business data.

Chapter 21, “Working with ASP.NET” — This chapter explores the basics of ASP.NET in detail. It looks at building Web applications using Visual Studio and includes discussions on the overall application and page frameworks.

Chapter 22, “ASP.NET Advanced Features” — This chapter looks at several of ASP.NET’s advanced features, in particular focusing on AJAX. Examples of items covered include cross-page posting, master pages, site navigation, personalization, and more.

Chapter 23, “ASP.NET MVC” — Visual Studio 2010 introduces the MVC (Model-View-Controller) pattern for ASP.NET to mainstream development. This pattern provides a more structured framework for developing Web applications. This chapter outlines the advantages of using this pattern for new ASP.NET projects.

Chapter 24, “SharePoint 2010 Development” — SharePoint, which includes a number of technologies and services, is Microsoft’s fastest-growing product. This chapter looks at how Visual Basic developers can customize and leverage this versatile tool for hosting custom solutions.

Part V, “Libraries and Specialized Topics” — The final 10 chapters, Chapter 25 through Chapter 34, focus on a disparate collection of specialized topics. These topics reference specific .NET libraries that you will probably be interested in working with as you create new solutions and modify existing ones.

Chapter 25, “Visual Studio Tools for Office” — This chapter looks at using Visual Basic to work with your Microsoft Office–focused applications.

Chapter 26, “Windows Workflow Foundation” — This chapter covers the newly updated Workflow implementation. The new capabilities introduced with Visual Studio 2010 make it easy to integrate workflow into your applications. Windows Workflow was introduced in the .NET Framework 3.0, but the new release is a significant departure from the original logic (coverage of the original workflow has been moved to Appendix D).

Chapter 27, “Localization” — This chapter looks at some of the important items to consider when building your applications for worldwide use. It looks closely at the System.Globalization namespace and everything it offers your applications.

Chapter 28, “COM-Interop” — This chapter discusses COM and .NET component interoperability, and what tools are provided to help link the two technologies.

Chapter 29, “Network Programming” — This chapter covers working with some of the networking protocols that are available to you in your development and how to incorporate a wider network into the functionality of your applications.

Chapter 30, “Application Services” — This chapter examines how Visual Basic is used in the production of Windows Services. The creation, installation, running, and debugging of Windows Services are covered.

Chapter 31, “Assemblies and Reflection” — This chapter examines assemblies and their use within the CLR. The structure of an assembly, what it contains, and the information it contains are described. In addition, you will look at the manifest of the assembly and its role in deployment, and how to use remoting. You examine the basic architecture of remoting and build a basic server and client that uses a singleton object for answering client requests in the business tier. You will also learn how to use serialization to return more complex objects from the server to the client, and how to use the call context for passing extra data from the client to the server along with each call, without having to change the object model.

Chapter 32, “Security in the .NET Framework” — This chapter examines additional tools and functionality with regard to the security provided by .NET. Caspol.exe and Permview.exe, which assist in establishing and maintaining security policies, are discussed. The System.Security.Permissions namespace is also covered, including how it relates to managing permissions. Finally, you look at the System.Security.Cryptography namespace and run through some code that demonstrates its capabilities.

Chapter 33, “Parallel Programming Using Tasks and Threads” — This chapter explores threading and explains how the various objects in the .NET Framework enable any of its consumers to develop multithreaded applications. You will learn how threads can be created, how they relate to processes, and the differences between multitasking and multithreading. Additionally, Visual Studio 2010 introduces an entirely new parallel processing framework, which is addressed in this chapter.

Chapter 34, “Deployment” — This chapter takes a close look at the available deployment options for Windows Forms and Web Forms, including the ClickOnce deployment feature and creating .msi files.

Appendix A, “The Visual Basic Compiler” — This appendix covers the Visual Basic compiler vbc.exe and the functionality it provides.

Appendix B, “Visual Basic Power Packs Tools” — This appendix looks at the Visual Basic Power Packs Tools, originally released as off-cycle packages to aid developers who are maintaining traditional Visual Basic 6.0 applications or are looking for capabilities similar to those in Visual Basic 6. These tools were integrated with Visual Studio and help begin the process of transitioning to the current version of Visual Basic.

Appendix C, “Workflow 2008 Specifics” — The Windows Workflow Foundation introduced with .NET 3.0 and supported by Visual Studio 2008 has been completely redone for Visual Studio 2010. However, we moved coverage of the original Workflow services to this appendix so that you will continue to be able to reference this material for existing solutions.

Appendix D, “Enterprise Services” — Over time, with new transaction support and related capabilities, the material in this appendix, which was previously its own chapter, has become less applicable. It has been migrated to this appendix to support those with existing implementations that reference Enterprise Services. This chapter explores the .NET component services — in particular, transaction processing and queued components.

Appendix E, “Programming for the Cloud” — This chapter looks at several new cloud-based environments that Microsoft has introduced and how they affect you as a Visual Basic developer. Whether you are keeping data in the cloud or developing applications that will live in the cloud, this chapter will help you understand this new application paradigm.

CONVENTIONS

To help you get the most from the text and keep track of what’s happening, we’ve used a number of conventions throughout the book.

Boxes like this one hold important, not-to-be forgotten information that is directly relevant to the surrounding text.

Tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.

As for styles in the text:

We italicize new terms and important words when we introduce them.

We show keyboard strokes like this: Ctrl+A.

We show filenames, URLs, and code within the text like so: persistence.properties.

We present code in two different ways:

We use a monofont type with no highlighting for most code examples.
We use bold to emphasize code that is particularly important in the present context or to show changes from a previous code snippet.

SOURCE CODE

As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All the source code used in this book is available for download at http://www.wrox.com. When at the site, simply locate the book’s title (use the Search box or one of the title lists) and click the Download Code link on the book’s detail page to obtain all the source code for the book. Code that is included on the Web site is highlighted by the following icon:

Listings include the filename in the title. If it is just a code snippet, you’ll find the filename in a code note such as this:

Code snippet filename

Once you download the code, just decompress it with your favorite compression tool. Alternately, you can go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.

Because many books have similar titles, you may find it easiest to search by ISBN; this book’s ISBN is 978-0-470-50224-2.

ERRATA

We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, such as a spelling mistake or a faulty piece of code, we would be very grateful for your feedback. By sending in errata, you may save another reader hours of frustration, and at the same time you will be helping us provide even higher-quality information.

To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page, you can view all errata that has been submitted for this book and posted by Wrox editors. A complete book list, including links to each book’s errata, is also available at www.wrox.com/misc-pages/booklist.shtml.

If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. We’ll check the information and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions of the book.

P2P.WROX.COM

For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a Web-based system for you to post messages relating to Wrox books and related technologies, and interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.

At http://p2p.wrox.com, you will find a number of different forums that will help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps:

1.  Go to p2p.wrox.com and click the Register link.

2.  Read the terms of use and click Agree.

3.  Complete the required information to join, as well as any optional information you wish to provide, and click Submit.

4.  You will receive an e-mail with information describing how to verify your account and complete the joining process.

You can read messages in the forums without joining P2P, but in order to post your own messages you must join.

Once you join, you can post new messages and respond to messages other users post. You can read messages at any time on the Web. If you would like to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.

For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works, as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.

PART I

Language Constructs and Environment

CHAPTER 1: Visual Studio 2010

CHAPTER 2: Objects and Visual Basic

CHAPTER 3: Custom Objects

CHAPTER 4: The Common Language Runtime

CHAPTER 5: Declarative Programming with Visual Basic

CHAPTER 6: Exception Handling and Debugging

CHAPTER 7: Test-Driven Development

1

Visual Studio 2010

WHAT YOU WILL LEARN IN THIS CHAPTER

Versions of Visual Studio

An introduction to key Visual Basic terms

Targeting a runtime environment

Creating a baseline Visual Basic Windows Form

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!