1. Trang chủ
  2. » Công Nghệ Thông Tin

visual basic 2010 unleashed

1,4K 2,8K 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Visual Basic 2010 Unleashed
Tác giả Alessandro Del Sole
Trường học Pearson Education, Inc.
Chuyên ngành Computer Science
Thể loại Sách tham khảo
Năm xuất bản 2010
Thành phố Indianapolis
Định dạng
Số trang 1.372
Dung lượng 45,5 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

...89 .NET Framework Primitive Value Types ...90 Using Value Types...92 Working with BigInteger ...100 Building Custom Value Types ...101 Understanding Reference Types.. ...598 Understan

Trang 3

system, or transmitted by any means, electronic, mechanical, photocopying, recording,

or otherwise, without written permission from the publisher No patent liability is

assumed with respect to the use of the information contained herein Although every

precaution has been taken in the preparation of this book, the publisher and author

assume no responsibility for errors or omissions Nor is any liability assumed for

damages resulting from the use of the information contained herein.

ISBN-10: 0-672-33154-3

ISBN-13: 978-0-672-33154-1

Library of Congress Cataloging-in-Publication Data

Del Sole, Alessandro.

Visual Basic 2010 unleashed / Alessandro Del Sole.

Printed in the United States of America

First Printing: May 2010

Trademarks

All terms mentioned in this book that are known to be trademarks or service marks

have been appropriately capitalized Pearson Education, Inc cannot attest to the

accu-racy of this information Use of a term in this book should not be regarded as affecting

the validity of any trademark or service mark.

Warning and Disclaimer

Every effort has been made to make this book as complete and as accurate as

possi-ble, but no warranty or fitness is implied The information provided is on an “as is”

basis The author and the publisher shall have neither liability nor responsibility to any

person or entity with respect to any loss or damages arising from the information

contained in this book.

Bulk Sales

Pearson offers excellent discounts on this book when ordered in quantity for bulk

purchases or special sales For more information, please contact:

U.S Corporate and Government Sales

Technical Editor Matt Kleinwaks Publishing Coordinator Cindy Teeters Designer Gary Adair Compositor Mark Shirar

Trang 4

Part I Learning the Basics of VB

1 Introducing the NET Framework 4.0 1

2 Getting Started with the Visual Studio 2010 IDE .11

3 The Anatomy of a Visual Basic Project 59

4 Data Types and Expressions 85

5 Debugging Visual Basic 2010 Applications 177

6 Handling Errors and Exceptions 207

Part II Object-Oriented Programming with Visual Basic 2010 7 Class Fundamentals 225

8 Managing an Object’s Lifetime 267

9 Organizing Types Within Namespaces 281

10 Modules 295

11 Structures and Enumerations 299

12 Inheritance 317

13 Interfaces 341

14 Generics and Nullable Types 359

15 Delegates and Events 371

16 Working with Collections 385

17 Visually Designing Objects 407

18 “Generate From Usage” Coding Techniques 421

Part III Advanced VB Language features 19 Manipulating Files and Streams 429

20 The My Namespace 451

21 Advanced Language Features 485

Part IV Data Access with ADO.NET and LINQ 22 Introducing ADO.NET and DataSets 513

23 Introducing LINQ 523

24 LINQ to Objects .531

25 LINQ to SQL 561

26 LINQ to DataSets 595

Trang 5

27 Introducing ADO.NET Entity Framework 603

28 Manipulating Xml Documents with LINQ and Xml Literals 635

29 Overview of Parallel LINQ 655

Part V Building Windows Applications 30 Creating Windows Forms 4.0 Applications 665

31 Creating WPF Applications 681

32 WPF Common Controls 715

33 Brushes, Styles, Templates, and Animations in WPF 745

34 Manipulating Documents and Media 781

35 Introducing Data-Binding 799

36 Localizing Applications 829

Part VI Building Web Applications 37 Building ASP.NET Web Applications .839

38 Publishing ASP.NET Web Applications .865

39 Building Rich Internet Applications with Silverlight 871

40 Building and Deploying Applications for Windows Azure 899

Part VII Networking and Exposing Data Through Networks 41 Creating and Consuming WCF Services 927

42 Implementing and Consuming WCF Data Services 949

Part VIII Advanced NET Framework with VB 2010 43 Serialization 971

44 Processes and Multithreading 993

45 Parallel Programming 1005

46 Working with Assemblies 1029

47 Reflection 1043

48 Coding Attributes 1065

49 Platform Invokes and Interoperability with the COM Architecture 1075

50 Documenting the Source Code 1091

51 Advanced Compilations with MSBuild 1105

52 Building Customizations for Microsoft Office 1119

Part IX Applications Deployment 53 Understanding the Global Assembly Cache 1137

Trang 6

Part X Mastering the Visual Studio 2010 IDE

56 Advanced IDE Features 1175

57 Introducing the Visual Studio Extensibility 1199

58 Advanced Analysis Tools .1223

59 Testing Code with Unit Tests, Test-Driven Development, and

Code Contracts 1251

Appendixes

A Installing Visual Studio 2010 .1275

B Useful Resources and Tools for Visual Basic .1281 Index

1285

Trang 7

Part I Learning the Basics of VB

1 Introducing the NET Framework 4.0 1

What Is the NET Framework? .1

Where Is the NET Framework 2

The NET Framework Architecture 2

The Common Language Runtime 4

Writing Managed Code 4

.NET Assemblies .5

The Base Class Library 5

.NET Languages .6

.NET Framework Tools 7

Windows Software Development Kit 7

What’s New in NET Framework 4.0 8

2 Getting Started with the Visual Studio 2010 IDE 11 What’s New in Visual Studio 2010 11

Start Page .12

Get Started Tab 13

The Guidance and Resources Tab 13

The Latest News Tab 14

Working with Projects and Solutions 15

Creating Visual Basic Projects 16

Multitargeting 17

Accessing Recent and Online Templates 18

Searching for Installed Templates 20

Creating Reusable Projects and Items Templates 21

Creating Your First Visual Basic 2010 Project 21

Finding Visual Basic Projects 23

Working with the Code Editor 24

Working with Tool Windows .26

The Solution Explorer Window 27

Error List Window 28

The Properties Window 30

Output Window .31

Trang 8

Compiling Projects 37

Debug and Release Configurations 38

Other Compile Options .41

Advanced Compile Options 44

Debugging Overview 47

Debugging an Application 47

Breakpoints and Data Tips 49

About Runtime Errors .52

Edit and Continue 53

Browsing the Visual Basic and NET Documentation 54

Online Help and the MSDN Library 55

Object Browser Window .55

3 The Anatomy of a Visual Basic Project 59 Brief Overview of Types and Members .59

Classes 60

Properties 60

Methods 60

Modules 61

Structures 61

Inheritance 61

Namespaces 62

Accessing Members 63

Imports Directives 64

#Region #End Region Directives 64

Attributes 65

A New Feature: Implicit Line Continuation 65

Visual Basic 2010 Reserved Keywords 67

Understanding Project Files .70

Dissecting My Project 70

Application.MyApp 70

AssemblyInfo.vb 72

Resources and the Resources.resx File 73

Application Settings .77

Understanding References 79

Adding References to COM Libraries 82

Deploy Without PIAs .83

Final Considerations .84

4 Data Types and Expressions 85 Common Type System .85

Everything Is an Object 86

Trang 9

Introducing Value Types and Reference Types 86

System.Object and System.ValueType 87

Understanding Value Types 89

.NET Framework Primitive Value Types 90

Using Value Types 92

Working with BigInteger 100

Building Custom Value Types 101

Understanding Reference Types 101

.NET Framework Primitive Reference Types 103

Differences Between Value Types and Reference Types 104

Memory Allocation 104

Object-Oriented Differences 107

Performance Differences 109

What Custom Type Should I Choose? 109

Converting Between Value Types and Reference Types .110

Understanding Implicit Conversions 110

Boxing and Unboxing 112

Deep Copy and Shallow Copy 114

The GetType Keyword 118

Conversion Operators 119

Widening and Narrowing Conversions 119

Working with NET Fundamental Types 124

Working with Strings 125

Working with Dates 137

Working with Time .143

Working with TimeZone and TimeZoneInfo 144

Working with GUIDs 147

Working with Arrays .148

Common Operators 155

Arithmetic Operators 155

Assignment Operators 157

Logical, Bitwise and Shift Operators 158

Concatenation Operators 163

Comparison Operators 164

Iterations, Loops, and Conditional Code Blocks 166

Iterations 166

Loops 169

Conditional Code Blocks 171

Constants 174

With End With statement 175

Trang 10

5 Debugging Visual Basic 2010 Applications 177

Preparing an Example 177

Debugging Instrumentation 178

Debugging in Steps 178

Mixed Mode Debugging 180

“Just My Code” Debugging 180

Working with Breakpoints and Trace Points 182

Locals Window 185

Command Window 185

Call Stack Window 186

Watch Windows .187

Threads Window .189

Autos Window 190

Debugger Visualizers 191

Debugging in Code 192

The Debug Class 192

The Trace Class 194

Understanding Trace Listeners 195

Using Debug Attributes in Your Code 201

6 Handling Errors and Exceptions 207 Introducing Exceptions 207

Handling Exceptions 208

Are You Upgrading from Visual Basic 6? 209

System.Exception, Naming Conventions and Specialization 209

Try Catch Finally 209

The Throw Keyword 218

The When Keyword 222

Catching Exceptions Without a Variable 224

Part II Object-Oriented Programming with Visual Basic 2010 7 Class Fundamentals 225 Declaring Classes .225

Nested Classes 226

Fields 227

Avoiding Ambiguities with Local Variables 228

Properties .229

Read-Only Properties 231

Write-Only Properties 231

Trang 11

Exposing Custom Types 232

Accessing Properties .232

Default Properties 233

Scope 234

Methods 236

Invoking Methods 236

Methods Arguments: ByVal and ByRef 237

Overloading Methods 242

Exit from Methods 245

Partial Classes 246

Partial Methods 249

Constructors 251

Overloading Constructors 254

Object Initializers .256

Shared Members 257

Shared Classes 258

Shared Fields 258

Shared Properties 259

Shared Methods 259

Shared Constructors 261

Common Language Specification .262

Where Do I Need to Apply? 262

Marking Assemblies and Types as CLS-Compliant 263

Naming Conventions 263

Rules About Classes 265

Rules About Properties .265

Rules About Methods 265

Rules About Arrays 266

8 Managing an Object’s Lifetime 267 Understanding Memory Allocation 267

Understanding Garbage Collection 268

Understanding the Finalize Method 269

Understanding Dispose and the IDisposable Interface 271

Using End Using Statement 273

Putting Dispose and Finalize Together 273

Object Resurrection 276

Advanced Garbage Collection 277

Interacting with the Garbage Collector 277 Understanding Generations and

Trang 12

9 Organizing Types Within Namespaces 281

Understanding What Namespaces Are 281

Organizing Types Within Namespaces 282

Why Are Namespaces So Useful? 285

Nested Namespaces .286

Scope 289

Root Namespace 289

Global Keyword .290

Imports Directives 291

Namespaces and Common Language Specification 294

10 Modules 295 Modules Overview 295

Scope 296

Differences Between Modules and Classes 297

No Constructor 297

No Inheritance Support 297

No Interface Implementation 297

11 Structures and Enumerations 299 Assignments 302

Passing Structures to Methods 302

Members’ Visibility 303

Inheritance Limitations and Interfaces Implementation 303

Memory Allocation 303

Organizing Structures 304

Overloading Operators 305

Overloading CType 307

Structures and Common Language Specification 308

Enumerations 309

Using Enumerations 310

Useful Methods from System.Enum 311

Using Enums As Return Values From Methods 314

Enum Values As Bit Flags 315

Enumerations and Common Language Specification 315

12 Inheritance 317 Applying Inheritance 318

Illustrating System.Object in Detail 321

Introducing Polymorphism 323

Overriding Members 325

Trang 13

NotOverridable Keyword 328

Overloading Derived Members 328

Conditioning Inheritance 328

NotInheritable Keyword 329

MustInherit and MustOverride Keywords 330

Accessing Base Classes Members 331

MyBase Keyword 332

MyClass Keyword 334

Constructors’ Inheritance 335

Shadowing .336

Overriding Shared Members 337

Practical Inheritance: Building Custom Exceptions 338

13 Interfaces 341 Defining Interfaces 341

Implementing and Accessing Interfaces 343

Passing Interfaces As Method Arguments 345

Interfaces and Polymorphism .345

Interfaces Inheritance 346

Defining CLS-Compliant Interfaces 347

Most Common NET Interfaces 348

The IEnumerable Interface 348

The IComparable Interface 351

The IConvertible Interface 353

The IFormattable Interface 356

14 Generics and Nullable Types 359 Introducing Generics 359

Creating and Consuming Generics 360

Consuming Generic Types 362

Implementing Generic Methods 363

Understanding Constraints 363

Overloading Type Parameters .366

Introducing Nullable Types 367

15 Delegates and Events 371 Understanding Delegates 371

Declaring Delegates 372

Combining Delegates: Multicast Delegates 374

Handling Events .375

Trang 14

Offering Events to the External World .378

Raising Events 378

Creating Custom Events 381

16 Working with Collections 385 Understanding Collections Architecture 385

Working with Nongeneric Collections 386

The ArrayList Collection 386

The Queue Collection .389

The Stack Collection .390

The HashTable Collection 390

The ListDictionary Collection 391

The OrderedDictionary Collection 391

The SortedList Collection 392

The HybridDictionary Collection 392

The StringCollection Collection 392

The StringDictionary Collection 393

The NameValueCollection Collection 393

The BitArray Collection 393

The Bitvector32 Collection 394

Working with Generic Collections 395

The List(Of T) Collection 395

Working with Collection Initializers 397

The ReadOnlyCollection(Of T) Collection 398

The Dictionary(Of TKey, TValue) Collection 399

The SortedDictionary(Of TKey, TValue) Collection 400

The ObservableCollection(Of T) Collection 400

The ReadonlyObservableCollection(Of T) Collection 402

The LinkedList(Of T) Collection 403

The Queue(Of T) and Stack(Of T) Collections 405

Building Custom Collections 405

Concurrent Collections 406

17 Visually Designing Objects 407 Visual Studio Class Designer .407

Enabling the Class Designer 408

Adding and Designing Objects 409

Implementing Derived Classes .413

Creating Multiple Diagrams 416

Exporting the Diagram 416

Class View Window 417

Class Details Window 418

Trang 15

18 “Generate From Usage” Coding Techniques 421

Coding New Types 421

Generating Shared Members 425

On-the-Fly Code and Object Initializers 425

Generating Complex Objects 426

Interfaces Additions 428

Part III Advanced VB Language features 19 Manipulating Files and Streams 429 Manipulating Directories and Pathnames .429

The System.IO.Path Class 430

The System.IO.Directory Class 431

The System.IO.DirectoryInfo Class 434

The System.IO.DriveInfo Class 434

Handling Exceptions for Directories and Pathnames 435

Manipulating Files 436

The System.IO.File Class 436

The System.IO.FileInfo Class 438

Handling File Exceptions .439

Understanding Permissions .439

Introducing Streams 440

Reading and Writing Text Files 441

Reading and Writing Binary Files 442

Using Memory Streams 442

Using Streams with Strings 443

Compressing Data with Streams 444

Networking with Streams 448

20 The My Namespace 451 Introducing My 451

My.Application 452

Retrieving Assembly Information 452

Working with Cultures 453

Deployment and Environment Information 454

My.Computer 456

Working with the File System 457

Working with the Clipboard 458

Playing Audio Files 459

Managing the Keyboard 460

Working with the Registry 460

Trang 16

My.Settings .464

My.Settings Events 469

My.Resources .470

Getting Resources by Name in Code 474

My.User .474

My.WebServices .476

Extending My .476

Extending My.Application and My.Computer 478

Extending My.Resources and My.Settings .480

My in Different Applications 480

Understanding Application Events 483

21 Advanced Language Features 485 Local Type Inference 485

Option Infer Directive 487

Local Type Inference Scope 488

Array Literals 489

Multidimensional and Jagged Arrays 489

Extension Methods 490

Coding Custom Extension Methods 495

Exporting Extension Methods .497

Anonymous Types 498

Relaxed Delegates .500

Lambda Expressions 500

Type Inference and Lambda Expressions 503

Multiline Lambdas .504

Sub Lambdas 505

Lexical Closures 506

Ternary If Operator 507

Generic Variance 509

Covariance 509

Contra Variance 510

Part IV Data Access with ADO.NET and LINQ 22 Introducing ADO.NET and DataSets 513 Introducing ADO.NET 513

Data Providers 514

Connection Modes 515

Understanding Connections and Data Readers 515

Introducing DataSets 517

Creating DataSets 517

Trang 17

What Is LINQ? 523

LINQ Examples 525

Language Support 526

Understanding Providers 527

Overview of LINQ Architecture 528

24 LINQ to Objects 531 Introducing LINQ to Objects 531

Querying in Memory Objects 532

Understanding Deferred Execution .539

Introducing Standard Query Operators .541

Projection Operators 542

Restriction Operators 543

Aggregation Operators 544

Understanding the Let Keyword 546

Conversion Operators 546

Generation Operators 548

Ordering Operators .549

Set Operators .550

Grouping Operators 551

Union Operators 553

Equality Operators 556

Quantifiers 556

Concatenation Operators 557

Elements Operators 557

Partitioning Operators 558

25 LINQ to SQL 561 Introducing LINQ to SQL 561

Prerequisites 562

Understanding LINQ to SQL Classes 562

Behind the Scenes of LINQ to SQL Classes 573

Querying Data with LINQ to SQL 574

Insert/Update/Delete Operations with LINQ 579

Inserting Entities 579

Updating Entities 583

Deleting Entities 584

Mapping Stored Procedures 584

Using the Log 587

Trang 18

Handling Optimistic Concurrency 590

Using SQL Syntax Against Entities 591

LINQ to SQL with SQL Server Compact Edition .592

Writing the Connection String 593

26 LINQ to DataSets 595 Querying Datasets with LINQ 595

Building Complex Queries with Anonymous Types 598

LINQ to DataSets’ Extension Methods 598

Understanding CopyToDataTable .598

Understanding Field(Of T) and SetField(Of T) 600

27 Introducing ADO.NET Entity Framework 603 Introducing Entity Framework 603

Understanding Entity Data Models 604

Understanding the ObjectContext class: The Visual Basic Mapping 612

Entity Designer Tool Windows 617

Insert/Update/Delete Operations for Entities .620

Instantiating the ObjectContext .620

Adding Entities 623

Deleting Entities 624

Updating Entities 625

Handling Optimistic Concurrency .626

Validating Data 627

Querying EDMs with LINQ to Entities .628

Querying EDMs with Entity SQL .629

Mapping Stored Procedures 631

28 Manipulating Xml Documents with LINQ and Xml Literals 635 Introducing LINQ to Xml .635

The System.Xml.Linq Namespace .636

Xml Literals .641

LINQ Queries with Xml Literals 644

Understanding Embedded Expressions 646

Xml Schema Inference 649

29 Overview of Parallel LINQ 655 Introducing PLINQ 655

Simulating an Intensive Work 656

Measuring Performances of a Classic LINQ Query 656

Trang 19

Measuring Performances of a PLINQ Query 657

Ordering Sequences 659

AsParallel and Binary Operators .660

Using ParallelEnumerable 660

Controlling PLINQ Queries 661

Handling Exceptions 663

Part V Building Windows Applications 30 Creating Windows Forms 4.0 Applications 665 What Windows Forms Is Today 665

Creating Windows Forms Applications 666

What’s New in Windows Forms 4.0 667

Available Windows Forms Controls 667

Building Windows Forms Applications with ADO.NET Entity Framework and Chart Control .668

Providing Custom Validation 674

Understanding Chart Control 675

Populating the Chart Control 677

Running the Sample Application 680

31 Creating WPF Applications 681 What Is WPF? 682

Improvements in WPF 4 682

WPF Architecture 683

Building WPF Applications with Visual Studio 2010 685

Understanding the eXtensible Application Markup Language (XAML) 687

Declaring and Using Controls with the Designer and XAML .689

Understanding Visual Tree and Logical Tree .692

Handling Events in WPF .694

A More Thorough Discussion: Introducing the Routed Events 695

Arranging Controls with Panels 697

The Grid Panel 697

The StackPanel Panel 700

The WrapPanel Panel 701

The Canvas Panel 703

The DockPanel Panel 703

The ViewBox Panel 704

Managing Windows 704

Instantiating Windows at Runtime 706

Trang 20

Introducing WPF Controls Features 715

Understanding the ContentControl 716

Understanding Common Controls 717

Border 717

Button 718

Calendar 718

CheckBox 719

ComboBox 720

DataGrid 721

DatePicker 721

DocumentViewer 723

Ellipse 723

Expander 723

Frame .724

GroupBox 725

Image .726

Label .726

ListBox 727

ListView 728

MediaElement 729

Menu .729

PasswordBox 732

ProgressBar 732

RadioButton 734

Rectangle 734

RichTextBox 734

ScrollBar 735

ScrollViewer 735

Separator 736

Slider 736

StatusBar 737

TabControl 737

TextBlock 738

TextBox 739

ToolBar 740

TreeView 741

WebBrowser 742

WindowsFormsHost 742

Using Common Dialogs 743

Trang 21

33 Brushes, Styles, Templates, and Animations in WPF 745

Introducing Brushes .745

Applying a SolidColorBrush .747

Applying a LinearGradientBrush 748

Applying a RadialGradientBrush 749

Applying an ImageBrush .751

Applying SelectionBrush and CaretBrush 753

Applying a VisualBrush .754

Applying a DrawingBrush .755

Applying a BitmapCacheBrush 757

Introducing Styles 759

Styles Inheritance 761

Understanding Triggers 761

Introducing Control Templates 763

Introducing Transformations .766

Applying RotateTransform .767

Applying ScaleTransform .767

Applying SkewTransform .768

Applying TranslateTransform 768

Applying Multiple Transforms 769

Introducing Animations 770

Applying DoubleAnimation .771

Applying ColorAnimation .773

Working with Animation Events 775

Creating Animations with Visual Basic .776

34 Manipulating Documents and Media 781 Viewing Images 781

Playing Media 783

Manipulating Documents 786

Understanding the RichTextBox Control 795

Viewing XPS Documents 796

35 Introducing Data-Binding 799 Introducing the Data-Binding 799

Binding UI Elements with the Binding Markup Extension .800

Understanding the DataGrid and the ObservableCollection 802

Discussing the New Drag’n’Drop Data-Binding .806

Creating Tabular Data Forms .807

Creating Master-Details Forms 813

Trang 22

Introducing NET Localization 829

Windows Forms Localization 830

WPF Localization 832

Preparing the LocBaml tool .832

Localizing a WPF Application 833

Part VI Building Web Applications

37 Building ASP.NET Web Applications 839

Introducing the ASP.NET Model .839

Understanding Page Requests 840

Scalability and Performances .840

Available Project Templates 841

Web Forms and Master Pages 842

Understanding State Management 848

The Application State 849

The Cache State 849

The Context State 850

Using Cookies for Saving Information 850

The Session State 851

The ViewState State 851

Creating a Web Application with VB 2010 with

Navigation and Data-Binding 851

Master Pages 852

Adding the Data Model 855

Adding a New Web Form 855

Adding Data Controls 857

Adding Filtering Capabilities 860

Adding Navigation Controls 861

Running the Application 861

Configuring a Web Application for Security 863

38 Publishing ASP.NET Web Applications 865

Deployment Overview 865

The 1-Click Deployment 866

Classic Publishing 866

Trang 23

MSDeploy Publish .868

Understanding Packages 868 Deploy with MSDeploy 868

39 Building Rich Internet Applications with Silverlight 871

Introducing Silverlight 871

Creating Silverlight Projects with Visual Basic 2010 872

Adding Controls and Handling Events 875

How Silverlight Applications Are Packaged 876 Playing Media 876

Animating UI Elements 880

Introducing Navigation Applications .882

Introducing WCF RIA Services 886

Adding the Data Source 887 Adding the Domain Service Class 887 Data-Binding to Controls 891 Running the Application 893

“Out of Browser” Applications 894

40 Building and Deploying Applications for Windows Azure 899

About Windows Azure Platform 899

Registering for the Windows Azure Developer Portal 901

Downloading and Installing Tools for Visual Studio 901

Additional Tools 902 Creating a Demo Project .902

Understanding Web Roles and Web Configuration 902 Adding a Silverlight 3 Project .905 Testing the Application Locally .911Deploying Applications to Windows Azure 913

Activating the Storage Account 921

Using the Windows Azure Management Console Snap-In 922Part VII Networking and Exposing Data Through Networks

41 Creating and Consuming WCF Services 927

Introducing Windows Communication Foundation 928

Understanding Endpoints 928 Address, Binding, Contract: The ABC of WCF 928Implementing WCF Services 929

Implementing Custom Logic for the WCF Service .933

Trang 24

Understanding the Proxy Class 938 Invoking Members from the Service 939Handling Exceptions in WCF 943

Hosting WCF Services in Internet Information Services 944

Configuring Services with the Configuration Editor 945

42 Implementing and Consuming WCF Data Services 949

What Are Data Services? 949

Querying Data via Http Requests .950 Implementing WCF Data Services .951

Deploying WCF Data Services to Internet Information Services 957 Consuming WCF Data Services 957

Creating a Client Application 957 Querying Data 962Implementing Service Operations 963

Implementing Query Interceptors 965

Understanding Query Interceptors 965 Understanding Change Interceptors 967Understanding Server-Driven Paging 968

Part VIII Advanced NET Framework with VB 2010

Objects Serialization 972

Binary Serialization 972 Soap Serialization 975 Providing Serialization for Custom Objects 976 NonSerialized events 978XML Serialization 979

Customizing Xml Serialization 980 Custom Serialization .982

Serialization Events 983 Serialization with XAML .984

Serialization in Windows Communication Foundation 987

JSON Serialization 989 Serialization in the ADO.NET Entity Framework 990

Managing Processes 994

Querying Existing Processes 995 Introducing Multithreading 996

Creating Threads 996 Passing Parameters 997

Trang 25

Understanding the NET Thread Pool 997

Getting and Setting Information in the Thread Pool .998 Threads Synchronization 999

The SyncLock End SyncLock Statement 1000 Synchronization with the Monitor Class .1001 Read/Write Locks 1001

Introducing Parallel Computing 1006

Introducing Parallel Classes .1006 Understanding and Using Tasks 1007

What Is a Task? 1007 Running Tasks with Parallel.Invoke 1008 Creating, Running, and Managing Tasks: The Task Class 1009 Creating Tasks That Return Values 1009 Exception Handling 1011 Cancelling Tasks 1012 The Barrier Class 1014Parallel Loops 1015

Parallel.For Loop 1017

Parallel.ForEach Loop 1018Debugging Tools For Parallel Tasks 1021

Creating Application Domains and Executing Assemblies 1031 Overview of Security Changes in NET 4.0 1034

Permissions 1035 The Transparency Level 2 1036 Sandboxing 1038

Trang 26

Introducing Reflection 1043

Understanding Assemblies’ Metadata 1044

Preparing a Sample Assembly .1045

Getting Assembly Information 1046

Reflecting Types 1048

Reflecting a Single Type 1053

Invoking Code Dynamically .1055

Generating Code at Runtime with Reflection.Emit 1057

Late Binding Concepts 1062

Applying Attributes 1065

Coding Custom Attributes 1068

Applying Custom Attributes 1070

Applying Attributes Multiple Times 1071

Defining Inheritance 1071

Reflecting Attributes 1073

49 Platform Invokes and Interoperability with the COM Architecture 1075

Importing and Using COM Objects 1075

Importing COM Components into Visual Studio 1076

Using COM Objects in Code 1077

Catching Exceptions .1078

Releasing COM Objects 1078

Exposing NET Objects to the COM World .1078

P/Invokes and Unmanaged Code 1081

Understanding P/Invokes 1081

Encapsulating P/Invokes 1082

Converting Types to Unmanaged 1084

The StructLayout Attribute 1085

The VBFixedString attribute 1087

Handling Exceptions 1087

References to the Win32 API calls 1089

Understanding XML Documents .1091

Enabling XML Comments 1092

Implementing XML Comments 1093

Defining Complex Code Documentation .1095

Generating Compiled Help Files 1102

Trang 27

51 Advanced Compilations with MSBuild 1105

Introducing MSBuild 1105

Introducing Projects 1107 Understanding Tasks and Creating Targets 1111Advanced MSBuild Features 1114

Batching 1114 Logging 1116 Transformations 1116

52 Building Customizations for Microsoft Office 1119

Introducing the Visual Studio Tools for Office 1120 Understanding Application-Level Solutions and Document-Level

Solutions 1120 What Are Office Business Applications? 1121Creating an Application-Level Add-In for Microsoft Word 1121

Creating a Document-Level Add-In for Microsoft Excel .1126

Designing the Add-In 1129 Interacting with Documents via Visual Basic 2010 Code 1130 Running the Customized Document 1132Deploying VSTO Add-Ins 1132

Part IX Applications Deployment

53 Understanding the Global Assembly Cache 1137

The Dll Hell Problem 1137

XCopy Deployment 1138 The Global Assembly Cache 1139

Installing and Uninstalling Assemblies 1140 Signing Assemblies with Strong Names 1141 Top Reasons for Installing (or Not) Assemblies to the GAC 1143 Adding References from Visual Studio to Your Own Assemblies 1143

54 Setup & Deployment Projects for Windows Installer 1145

Windows Installer Overview 1145

Creating a Setup Project 1146

Configuring the Setup Project 1149

Editing the File System 1150 Editing Registry Values 1152 Customizing Dialogs 1152 Creating File Types 1153

Trang 28

Specifying Launch Conditions 1155

Package Configuration and Prerequisites .1156

Building and Deploying the Windows Installer Package .1158

55 Deploying Applications with ClickOnce 1159

Introducing ClickOnce 1159

How ClickOnce Handles Applications 1160

When Should I Use ClickOnce? 1160

Deploying Applications with ClickOnce .1161

Structure of a ClickOnce Deployment 1164

Part X Mastering the Visual Studio 2010 IDE

Exporting Templates 1175

Exporting Project Templates 1175

Exporting Item Templates 1178

Customizing Visual Studio 2010 1181

Customizing the Tools Menu 1181

Customizing Commands and Toolbars 1182

Managing User Settings 1185

Exporting Settings 1185

Importing Settings 1186

Customizing the Toolbox 1189

Using, Creating, and Managing Reusable Code Snippets 1190

Consuming Code Snippets 1190

The Code Snippet Manager 1192

Creating and Consuming Custom Code Snippets 1193

57 Introducing the Visual Studio Extensibility 1199

Introducing Visual Studio Extensibility 1199

What’s New in the Extensibility with Visual Studio 2010 1200

The Visual Studio 2010 SDK .1201

Trang 29

Building a Visual Studio Package .1201

Deploying Visual Studio Extensions 1212

Managing Extensions with the Extension Manager 1214

Managing Add-Ins with the Add-In Manager 1216

Extending the Code Editor 1217

Introducing Analysis Tools 1224

Performing Code Analysis 1224

Calculating Code Metrics 1230

Profiling Applications 1231

Profiling External Executables .1241 IntelliTrace, the Historical Debugger .1242

IntelliTrace Options 1242 Creating a Sample Application 1243 Tracking Application Events and Exceptions with IntelliTrace 1245 Analyzing IntelliTrace Logs 1247 Using IntelliTrace for Unit Tests 1248Generating Dependency Graphs 1248

59 Testing Code with Unit Tests, Test-Driven Development,

Testing Code with Unit Tests .1251

Creating Unit Tests 1252 Running Unit Tests 1256 Enabling Code Coverage 1257 Unit Tests and IntelliTrace 1259Introducing Test-Driven Development .1261

Creating a Test Project 1261 Creating Unit Tests 1263 Refactoring Code 1266Understanding Code Contracts 1267

Setting Up the Environment 1267 Setting Contracts Properties 1268 Tools for Code Contracts .1269 Preconditions 1269 Post-Conditions 1271 Invariants 1272 Assertions and Assumptions .1273 Contract Events 1273

Trang 30

Appendixes

A Installing Visual Studio 2010 1275

Installing Visual Studio 2010 1275

Installing the Offline Documentation 1278

Finding Additional Contents Online 1278

Running Visual Studio 2010 for the First Time 1279

B Useful Resources and Tools for Visual Basic 1281

Visual Basic Resources in MSDN 1281

Useful Developer Tools for Visual Basic 1282

Trang 31

The first time I ever heard from Alessandro was through my blog contact form A few

years ago he reached out to me about his interest in donating an article to the Visual

Basic Developer Center on MSDN Reading his email, it was immediately apparent that

Alessandro was passionate about programming and particularly the Visual Basic language

With a quick Internet search I was at his blog and learning about him and the Visual

Basic Tips and Tricks community Not long after we published his first article, Alessandro

was awarded Microsoft Most Valuable Professional (MVP) for his exceptional community

leadership and technical expertise

I remember at the time how fun it was working with Alessandro and to see his excitement

and passion for the developer community—something we both share Today he continues

to help me with the VB Dev Center to provide training content for developers I always

smile when I get an email from Alessandro, because I know he’s going to reach out to

help by sending me more articles or ideas on improving the site When he told me he was

writing this book, I was excited for the VB community, because I know how much his

online content helps the community today And the passion he has for Visual Basic

comes through in everything he writes

Visual Basic is an amazing language I started picking it up around 2000 with the release

of NET and it really helped me navigate the vastness of the platform Particularly things

like background compilation and Intellisense gave me immediate cues about whether the

code I was attempting to write was correct Also, coming from a more dynamic language

background, it was much easier to write the types of data-oriented systems I was building

using a language that was both static and dynamic at the same time With the release of

Language Integrated Query (LINQ), data became much easier to work with and Visual

Basic’s support for LINQ is extremely full featured with its set of expanded query

opera-tors and easy to use language syntax Coupled with the latest features in 2010 like

implicit line continuation and multiline and statement lambdas makes Visual Basic one of

the premiere modern programming languages of today Millions of developers agree

This book takes you on a journey through the NET platform through the eyes of a Visual

Basic developer If you’re just learning the platform this is a great place to start as

Alessandro begins with the basics of the platform and the language, and then touches on

a variety of different application development technologies and techniques If you’re

already programming on the NET platform, then this book will show you what’s new,

not only in the Visual Basic language, but also the NET Framework 4.0 and Visual Studio

2010 I am personally very excited about this release

Alessandro explains these concepts in a way that is very easy to understand with a

language that’s easy to use and his passion comes through in every paragraph I know you

will find this book filled with tips and tricks as well as development methodologies that

you can apply to the modern applications you are building today I really enjoyed reading

this book and I’m sure you will too

Beth Massi

Trang 32

Alessandro Del Sole, a Microsoft Most Valuable Professional (MVP) for Visual Basic, is

well known throughout the global VB community He is a community leader on the

Italian “Visual Basic Tips and Tricks” website (http://www.visual-basic.it) that serves more

than 41,000 VB developers, as well as a frequent contributor to the MSDN Visual Basic

Developer Center He enjoys writing articles on NET development, writing blog posts on

both his Italian and English blogs, and producing instructional videos You can find him

online in forums or newsgroups

Trang 33

To my parents, we live our lives many kilometers away from each other but I know you are

always there for me You are the best parents a son could ever desire Thank you!

To my best friend Nadia, whose support during the writing of this book has been as fundamental

as all my experience in the computer world, starting from my first article until becoming an MVP.

I’m very glad to let the world know how special you are to me Thanks for being always there.

Trang 34

First of all I would like to thank Brook Farling and all at Sams Publishing for giving me

the great opportunity of writing the most important book of my life on Visual Basic

Behind the scenes a lot of people did hard work, so I would like to say “thanks!” to

every-one, including the technical editor Matthew Kleinwaks and all the people involved in the

review process

Special thanks to all the Microsoft Visual Basic Team for doing a great job; particularly I

would like to give my special thanks to Lisa Feigenbaum for helping me to contact the

right people in the teams working on Visual Studio and the NET Framework She does

her work with great passion and professionalism; her help has been so precious to me

Many thanks, Lisa

Next I would like to thank Beth Massi from the VB Team for the opportunity of technical

discussions on the Visual Basic language She always creates great work producing content

that helps others learn something new every day If you are searching for information

using VB against the most recent Microsoft technologies, take a look at her blog

Great thanks also to some guys from the Italian subsidiary of Microsoft: Alessandro Teglia

(my MVP Lead), who has a great passion for his work and for the MVP’s community; he

did a really great job when I had some important questions related to information

required for this book, rapidly pointing me in the right direction, and Lorenzo Barbieri

His indications and suggestions on the Team System instrumentation were invaluable

Thanks to my boss Giampiero Ianni for his cordiality

I would like to thank my everyday friends; most of them aren’t interested in application

development but they’re always happy when listening to me talk about computers,

appli-cation development, and my books Most of all, they are always ready to encourage me

Writing a large book like this is not easy, but they always have the right words when

things are difficult So my deep thanks to Roberto Bianchi, Alessandro Ardovini, Daniela

Maggi, Maurizio Cagliero, Eugenio Ricci, Alessandra Gueragni, Francesca Bongiorni, Paolo

Leoni, Meso, Luca Libretti, and Sara Gerevini You guys really rock!

I’m a community leader and team member in the Italian “Visual Basic Tips & Tricks”

community (www.visual-basic.it); therefore, I would like to thank all those guys who are

the right stimulus for making things better every day; all those people who visited my

blogs at least once or who read even one article of mine, and all those people who every

day visit our website and follow us on forums, videos, articles, and blogs Special thanks

to my MVP colleagues Diego Cattaruzza, Antonio Catucci, and Raffaele Rialdi for their

great support and precious suggestions Thanks to Renato Marzaro and Marco Notari for

their continuous support and encouragement

Trang 35

your opinion and want to know what we’re doing right, what we could do better, what

areas you’d like to see us publish in, and any other words of wisdom you’re willing to

pass our way

As an executive editor for Sams Publishing, I welcome your comments You can email or

write me directly to let me know what you did or didn’t like about this book—as well as

what we can do to make our books better

Please note that I cannot help you with technical problems related to the topic of this

book We do have a User Services group, however, where I will forward specific technical

questions related to the book

When you write, please be sure to include this book’s title and author as well as your

name, email address, and phone number I will carefully review your comments and share

them with the author and editors who worked on the book

Visit our website and register this book at informit.com/register for convenient access to

any updates, downloads, or errata that might be available for this book

Trang 36

Introducing the NET

Framework 4.0

What Is the NET Framework?

The Common Language Runtime

The Base Class Library

.NET Languages

.NET Framework Tools

What’s New in NET Framework 4.0

As a Visual Basic 2010 developer, you need to understand

the concepts and technology that empower your

applica-tions: the Microsoft NET Framework The NET Framework

(also simply known as NET) is the technology that provides

the infrastructure for building the next generation’s

applica-tions that you will create Although covering every aspect

of the NET Framework is not possible, in this chapter you

learn the basis of the NET Framework architecture, why it

is not just a platform, and notions about the Base Class

Library and tools The chapter also introduces important

concepts and terminology that will be of common use

throughout the rest of the book

What Is the NET Framework?

Microsoft NET Framework is a complex technology that

provides the infrastructure for building, running, and

managing next generation applications In a layered

repre-sentation, the NET Framework is a layer positioned

between the Microsoft Windows operating system and your

applications .NET is a platform but also is defined as a

technology because it is composed of several parts such as

libraries, executable tools, and relationships and integrates

with the operating system Microsoft Visual Studio 2010

relies on the new version of the NET Framework 4.0 Visual

Basic 2010, C# 4.0, and F# 2010 are NET languages that

rely on and can build applications for the NET Framework

4.0 The new version of this technology introduces

impor-tant new features that will be described later In this chapter

you get an overview of the most important features of the

Trang 37

.NET Framework so that you will know how applications built with Visual Basic 2010 can

run and how they can be built

Where Is the NET Framework

When you install Microsoft Visual Studio 2010, the setup process installs the NET Framework

4.0 .NET is installed to a folder named %windir%\Microsoft.NET\Framework\4.0 If you

open this folder with Windows Explorer, you see a lot of subfolders, libraries, and

executable tools Most of the DLL libraries constitute the Base Class Library, whereas most

of the executable tools are invoked by Visual Studio 2010 to perform different kinds of

tasks, even if they can also be invoked from the command line Later in this chapter we

describe the Base Class Library and provide an overview of the tools; for now you need to

notice the presence of a file named Vbc.exe, which is the Visual Basic Compiler and a

command line tool In most cases you do not need to manually invoke the Visual Basic

compiler, because you will build your Visual Basic applications writing code inside Visual

Studio 2010, and the IDE invokes the compiler for you But it is worth mentioning that

you could create the most complex application using Windows’s Notepad and then run

Vbc Finally, it is also worth mentioning that users can get the NET Framework 4.0 from

Microsoft for free This means that the Visual Basic compiler is also provided free with

.NET, and this is the philosophy that characterizes the NET development since the first

version was released in 2002

The NET Framework Architecture

To better understand the structure of the NET Framework, think about it as a layered

architecture Figure 1.1 shows a high-level representation of the NET Framework 4.0

architecture

The first level of the representation is the operating system; the NET layer is located

between the system and applications The second level is the Common Language Runtime

(CLR), which provides the part of the NET Framework doing the most work We discuss

the CLR later in this chapter The next level is the Base Class Library (BCL), which provides

all NET objects that can be used both in your code and by Visual Basic when creating

applications The BCL also provides the infrastructure of several NET technologies that

you use in building applications, such as WPF, Windows Forms, ASP.NET, WCF, and so on

The last level is represented by applications that rely on the previous layers

DIFFERENCES WITH PREVIOUS VERSIONS

If you upgrade to Visual Basic 2010 from Visual Basic 2008, the main difference that

you notice is that NET 4.0 is a standalone infrastructure You may remember that NET

Framework 3.5 was instead an incremental framework that needed the prior installation

of NET 2.0 and NET 3.0 For example, LINQ was part of NET 3.5 whereas WPF was

part of NET 3.0 and Windows Forms was part of NET 2.0 (see Figure 1.2 for a

graphi-cal representation) With NET 4.0 this incremental structure disappears, and all the

Trang 38

FIGURE 1.1 The NET Framework 4.0 architecture

FIGURE 1.2 The incremental architecture of the NET Framework 3.5 SP 1

Trang 39

Although the various frameworks exposed by the BCL are discussed later in the book, in this

chapter, now you get an overview of the library and can understand how it works and how

you can use it But before examining the BCL, consider the Common Language Runtime

The Common Language Runtime

As its name implies, the Common Language Runtime provides an infrastructure that is

common to all NET languages This infrastructure is responsible for taking control of the

application’s execution and manages tasks such as memory management, access to system

resources, security services, and so on This kind of common infrastructure bridges the gap

that exists between different Win32 programming languages because all NET languages

have the same possibilities Moreover, the Common Language Runtime enables

applica-tions to run inside a managed environment The word managed is fundamental in the

.NET development, as explained in next paragraph

Writing Managed Code

When talking about Visual Basic 2010 development and, more generally, about NET

development, you often hear about writing managed code Before the first version of NET

(or still with non-.NET development environments), the developer was the only

responsi-ble person for interacting with system resources and the operating system For example,

taking care of accessing parts of the operating system or managing memory allocation for

objects were tasks that the developer had to consider In other words, the applications

could interact directly with the system, but as you can easily understand this approach

has some big limitations both because of security issues and because damages could be

dangerous The NET Framework provides instead a managed environment This means

that the application communicates with the NET Framework instead of with the

operat-ing system, and the NET runtime is responsible for managoperat-ing the application execution,

including memory management, resources management, and access to system resources

For example, the Common Language Runtime could prevent an application from

access-ing particular system resources if it is not considered full-trusted accordaccess-ing to the Security

Zones of NET

DIALING WITH THE SYSTEM

You can still interact directly with the operating system, for example invoking Windows

APIs (also known as Platform Invoke or P/Invoke for short) This technique is known as

writing unmanaged code that should be used only when strictly required This topic is

discussed in Chapter 49, “Platform Invokes and Interoperability with the COM

Architecture.”

Trang 40

.NET Assemblies

In classic Win32 development environments, such as Visual Basic 6 or Visual C++, your

source code is parsed by compilers that produce binary executable files that can be

imme-diately interpreted and run by the operating system This affects both standalone

applica-tions and dynamic/type libraries Actually Win32 applicaapplica-tions, built with Visual Basic 6

and C++, used a runtime, but if you had applications developed with different

program-ming languages, you also had to install the appropriate runtimes In.NET development

things are quite different Whatever NET language you create applications with, compilers

generate an assembly, which is a file containing NET executable code and is composed

essentially by two kinds of elements: MSIL code and metadata MSIL stands for Microsoft

Intermediate Language and is a high-level assembly programming language that is also

object-oriented, providing a set of instructions that are CPU-independent (rather than

building executables that implement CPU-dependent sets of instructions) MSIL is a

common language in the sense that the same programming tasks written with different

.NET languages produce the same IL code Metadata is instead a set of information related

to the types implemented in the code Such information can contain signatures, functions

and procedures, members in types, and members in externally referenced types Basically

metadata’s purpose is describing the code to the NET Framework Obviously, although an

assembly can have exe extension, due to the described structure, it cannot be directly

executed by the operating system In fact, when you run a NET application the operating

system can recognize it as a NET assembly (because between NET and Windows there is a

strict cooperation) and invoke the Just-In-Time compiler

The Execution Process and the Just-In-Time (JIT) Compiler

.NET compilers produce assemblies that store IL code and metadata When you launch an

assembly for execution, the NET Framework packages all the information and translates

them into an executable that the operating system can understand and run This task is

the responsibility of the Just-In-Time (JIT) compiler JIT compiles code on-the-fly just

before its execution and keeps the compiled code ready for execution It acts at the

method level This means that it first searches for the application’s entry point (typically

the Sub Main) and then compiles other procedures or functions (methods in NET

termi-nology) referenced and invoked by the entry point and so on, just before the code is

executed If you have some code defined inside external assemblies, just before the

method is executed the JIT compiler loads the assembly in memory and then compiles the

code Of course loading an external assembly in memory could require some time and

affect performance, but it can be a good idea to place seldom-used methods inside

exter-nal assemblies, the same way as it could be a good idea to place seldom-used code inside

separated methods

The Base Class Library

The NET Framework Base Class Library (BCL) provides thousands of reusable types that

you can use in your code and that cover all the NET technologies, such as Windows

Presentation Foundation, ASP.NET, LINQ, and so on Types defined in the Base Class

Library enable developers to do millions of things without the need of calling unmanaged

Ngày đăng: 01/08/2014, 16:22

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN