Log In
Or create an account ->
Imperial Library
Home
About
News
Upload
Forum
Help
Login/SignUp
Index
Microsoft® Visual Basic® 2010 Developer’s Handbook
Foreword
Introduction
Who Should Read This Book
Assumptions
Who Should Not Read This Book
Organization of This Book
Conventions and Features in This Book
System Requirements
Code Samples
Installing the Code Samples
Using the Code Samples
Acknowledgments
Errata and Book Support
We Want to Hear from You
Stay in Touch
I. Beginning with Language and Tools
1. Beginners All-Purpose Symbolic Instruction Code
Starting Visual Studio for the First Time
Console Applications
Starting an Application
Anatomy of a (Visual Basic) Program
Starting Up with the Main Method
Methods with and Without Return Values
Defining Methods Without Return Values by Using Sub
Defining Methods with Return Values by Using Function
Declaring Variables
Nullables
Expressions and Definitions of Variables
Defining and Declaring Variables at the Same Time
Complex Expressions
Boolean Expressions
Comparing Objects and Data Types
Deriving from Objects and Abstract Objects
Properties
Type Literal for Determining Constant Types
Type Safety
Local Type Inference
Arrays and Collections
Executing Program Code Conditionally
If ... Then ... Else ... ElseIf ... End If
The Logical Operators And, Or, Xor, and Not
Comparison Operators That Return Boolean Results
Short Circuit Evaluations with OrElse and AndAlso
Select ... Case ... End Select
The If Operator and IIf Function
Loops
For ... Next Loops
Nesting For Loops
For ... Each Loops
Do ... Loop and While ... End While Loops
Exit—Leaving Loops Prematurely
Continue—Repeating Loops Prematurely
Simplified Access to Object Properties and Methods Using With ... End With
The Scope of Variables
The += and –= Operators and Their Relatives
The Bit Shift Operators << and >>
Error Handling in Code
Elegant Error Handling with Try/Catch/Finally
Catching Multiple Exception Types
Using the Finally Block
2. Introduction to the .NET Framework
What Is .NET, and What Is It Composed Of?
What Is an Assembly?
What Is a Namespace?
Embedding of Namespaces and Assemblies in Code Files and Projects: a Practical Example
Common Language Runtime and Common Language Infrastructure
The Framework Class Library and the Base Class Library
The Common Type System
Microsoft Intermediate Language and the Just-In-Time Compiler
3. Sightseeing
Introduction
Starting Visual Studio for the First Time: Selecting the Profile
The Start Page: Where Your Developing Endeavors Begin
Beginning Development Experience—Creating New Projects
Managing Templates
Modifying Templates
Migrating from Previous Versions of Visual Studio to Visual Studio 2010
Upgrading Projects created with Visual Studio 2003 Through 2008
Upgrading Visual Basic 6.0 Applications to Visual Studio 2010
Multitargeting of Visual Basic Applications by Using Visual Studio 2010
The History of Multitargeting
Multitargeting for New Projects
Changing the Target Framework for Applications
Understanding Profiles
Client Profile is Default for Client Projects
Interesting Read for Multitargeting
Limitations of Multitargeting
Lack of Round-Tripping Support
Compromised Design Time Compatibility
Non-Optimal Experience with Mixed Target Solutions
Third-Party User Controls
Zooming In the New and Improved WPF-Based IDE
Managing Screen Real Estate
Split Window
Horizontal and Vertical Tab Group
Multimonitor Support or Tear-Away Windows
Persistence of Window Layout
Common Use Scenarios
Normal View
Windows In Float
Docking the Windows
Searching, Understanding, and Navigating Code
Navigate To
Smart Searching Capabilities
Navigating Between Code Blocks
Highlighting and Navigating Between Symbol References
Changing the Highlight Color
Disabling Highlight References
Regions and Outlining
Architecture Explorer
Sequence Diagram
Class Diagram
Coding Bottom Up
Declare First Mode
Consume First Mode
The Generate From Usage Feature
Customizing Types by Using the Generate New Type Dialog
Extending Visual Studio
Managing Visual Studio Extensions
Extension Types
4. Introduction to Windows Forms—Designers and Code Editor by Example
Case Example: the DVD Cover Generator
Specifications for “Covers”
Creating a New Project
Designing Forms with the Windows Forms Designer
Positioning Controls
Guidelines and the Margin/Padding Properties of Controls
Adjusting the Size and Position of Controls
Selecting Multiple Controls and Specifying the Reference Control
Performing Common Tasks on Controls by Using Smart Tags
Dynamically Arranging Controls at Runtime
Anchoring Controls with the Anchor Property
Adjusting Controls Proportionately to Form Size Changes with TableLayoutPanel
Creating Columns and Rows for the TableLayoutPanel
Arranging Controls in the Cells of the TableLayoutPanel
Anchoring Controls in the TableLayoutPanel
Spanning Rows or Columns of the TableLayoutPanel
Automatic Scrolling of Controls in Containers
Selecting Controls That Users Can’t Reach with the Mouse
Selecting Controls with the Properties Window
Determining the Tab Order of Controls
Using the Name, Text, and Caption Properties
Specifying Accelerator Keys
Setting up Accept and Cancel Buttons for a Form
Adding Multiple Forms to a Project
What’s Next?
Naming Conventions for Controls in this Book
Functions for Control Layout in the Designer
Keyboard Shortcuts for Positioning Controls
The Code Editor
Setting the Editor Display to the Correct Size
Many Roads Lead to the Code Editor
IntelliSense—The Strongest Workhorse in the Coding Stable
Filtering Elements in the Completion List
Displaying Element Parameter Information
Multiple Command Lines, Implicit Line Continuation, and Parameter Information
Automatic Completion of Structure Keywords and Code Indentation
Error Detection in the Code Editor
Simple Error Detection in the Editor
Editor Support for Runtime Errors
Forcing Type Safety: Error Correction Options for Type Conflicts
XML Documentation Comments for IntelliSense for Customized Objects and Classes
Adding New Code Files to the Project
Refactoring Code
Refactoring Code (Adjusting Class Names) by Renaming Project Files or Object Properties
Code Snippets Library
Inserting Code Snippets with the Help of Connections
Saving Application Settings with the Settings Designer
Setting Up Settings Variables
Using Settings Variables in Code
Binding of Settings Values with Form and Control Properties
Where Are Settings Stored?
Congratulations!
5. Introduction to Windows Presentation Foundation
What Is the Windows Presentation Foundation?
What’s So New About WPF?
25 Years of Windows, 25 Years of Drawn Buttons
Games and Protagonists
How WPF Brings Designers and Developers Together
Extensible Application Markup Language
Event Handling in WPF and Visual Basic
XAML Syntax Overview
ImageResizer—a Practical WPF Example
Defining Grid Columns and Rows for Arranging Controls
Inserting a New Row Retroactively
The Main Menu
Binding Events to Controls
Loading the Default Settings
Organization Is Everything: Making the Output Path Freely Definable
Making Final Preparations: Adding Pictures
On to the Finish Line: Reducing Picture Size
Adding a Project to an Existing Solution and Setting References
The Heart of the Program: Image Resizing
From Coach to Business Class
6. The Essential .NET Data Types
Numeric Data Types
Defining and Declaring Numeric Data Types
Delegating Numeric Calculations to the Processor
Numeric Data Types at a Glance
Byte
SByte
Short
UShort
Integer
UInteger
Long
ULong
Single
Double
Decimal
The Numeric Data Types at a Glance
Avoiding Single and Double Rounding Errors
Methods Common to all Numeric Types
Converting Strings into Values and Avoiding Culture-Dependant Errors
Performance and Rounding Issues
Determining the Minimum and Maximum Values of a Numeric Type
Special Functions for all Floating-Point Types
Infinity
Not a Number: NaN
Converting with TryParse
Special Functions for the Decimal Type
The Char Data Type
The String Data Type
Strings—Yesterday and Today
Declaring and Defining Strings
Handling Empty and Blank Strings
Automatic String Construction
Assigning Special Characters to a String
Memory Requirements for Strings
No Strings Attached, or Are There? Strings are Immutable!
Memory Optimization for Strings
Determining String Length
Retrieving Parts of a String
Padding Strings
Find and Replace Operations
Trimming Strings
Splitting Strings
Iterating through Strings
StringBuilder vs. String: When Performance Matters
Performance Comparison: String vs. StringBuilder
The Boolean Data Type
Converting to and from Numeric Data Types
Converting to and from Strings
The Date Data Type
TimeSpan: Manipulating Time and Date Differences
A Library with Useful Functions for Date Manipulation
Converting Strings to Date Values
Conversions with Parse
Conversion with ParseExact
.NET Equivalents of Base Data Types
The GUID Data Type
Constants and Read-Only Fields (Read-Only Members)
Constants
Read-Only Fields
II. Object-Oriented Programming
7. A Brief Introduction to Object-Oriented Programming
Using Classes and Objects: When and Why?
Mini Address Book—the Procedural Version
8. Class Begins
What Is a Class?
Instantiating Classes with New
Initializing Public Fields During Instantiation
New or Not New: About Objects and Reference Types
Nothing
Nothing as a Null Reference Pointer
Nothing and Default Values
Using Classes
Value Types
Creating a Value Type with a Structure
Assigning a Value Type to a Variable
9. First Class Programming
Using Properties
Assigning Values to Properties
Pre-Allocating Default Property Values for Autoimplemented Properties
Passing Arguments to Properties
Default Properties
Avoid the Ultimate Property-No-Go
Public Variables or Properties—a Question of Faith?
Class Constructors: Defining What Happens in New
Parameterized Constructors
Class Methods with Sub and Function
Overloading Methods, Constructors, and Properties
Using Optional Parameters
Mutual Calling of Overloaded Methods
Mutual Calling of Overloaded Constructors
Overloading Property Procedures with Parameters
Specifying Variable Scope with Access Modifiers
Access Modifiers and Classes
Access Modifiers and Procedures (Subs, Functions, Properties)
Access Modifiers and Variables
Different Access Modifiers for Property Accessors
Static Elements
Static Methods
Static Properties
Distributing Class Code over Multiple Code Files by Using Partial
Partial Class Code for Methods and Properties
10. Class Inheritance and Polymorphism
Reusing Classes Through Inheritance
Initializing Field Variables for Classes Without Default Constructors
Overriding Methods and Properties
Overriding Existing Methods and Properties of .NET Framework Classes
Polymorphism
A Simple Example of Polymorphism
Using Polymorphism in Real World Applications
Polymorphism and the Use of Me, MyClass, and MyBase
Abstract Classes and Virtual Procedures
Declaring a Class as Abstract with MustInherit
Declaring a Method or Property of an Abstract Class as Virtual with MustOverride
Interfaces
Editor Support for Abstract Classes and Interfaces
The Pitfalls of Automatic Code Completion with Interfaces or Abstract Classes
Editor Support for Abstract Classes
Interfaces that Implement Interfaces
Binding Multiple Interfaces in a Class
The Built-In Members of the Object Type
Returning the String Representation of an Object with ToString
Comparing Objects
Equals, Is, and IsNot in Real World Scenarios
The Methods and Properties of Object: An Overview
Shadowing of Class Procedures
Shadows as Interruptor of the Class Hierarchy
Special Form “Module” in Visual Basic
Singleton Classes and Self-Instantiating Classes
11. Developing Value Types
A Practical Example of Structures
Passing Value and Reference Parameters
Constructors and Default Instantiations of Value Types
No Default Constructor Code for Value Types
When to Use Value Types—When to Use Reference Types
Targeted Memory Assignment for Structure Members with the Attributes StructLayout and FieldOffset
12. Typecasting and Boxing Value Types
Converting Primitive Types
Converting to and from Strings
Converting Strings by Using the Parse and ParseExact Method
Converting Into Strings by Using the ToString Method
Catching Type Conversion Failures
Casting Reference Types by Using DirectCast
TryCast—Determining Whether Casting Is Possible
IsAssignableFrom—Casting on the Fly
Boxing Value Types
What DirectCast Cannot Do
To Box or Not to Box
Changing the Values of Interface-Boxed Value Types
13. Dispose, Finalize, and the Garbage Collector
The Garbage Collector in .NET
How the Garbage Collector Works
The Speed in Allocating Memory for New Objects
Finalize
When Finalize Does Not Take Place
Dispose
Implementing a High Resolution Timer as IDisposable
Visual Basic Editor Support for Inserting a Disposable Pattern
Targeted Object Release with Using
14. Operators for Custom Types
Introduction to Operator Procedures
Preparing a Structure or Class for Operator Procedures
Implementing Operators
Overloading Operator Procedures
Implementing Comparison Operators
Implementing Type Conversion Operators for Use with CType
Implementing True and False Evaluation Operators
Problem Handling for Operator Procedures
Beware When Using Reference Types!
Implementable Operators: an Overview
15. Events, Delegates, and Lambda Expressions
Consuming Events with WithEvents and Handles
Raising Events
Events Cannot Be Inherited—the Detour Via Onxxx
Providing Event Parameters
The Event Source: sender
Detailed Event Information: EventArgs
Delegates
Passing Delegates to Methods
Lambda Expressions
Single-Line Expression Lambdas and Multi-Line Statement Lambdas
Embedding Events Dynamically with AddHandler
Implementing Your Own Event Handlers
16. Enumerations
Introduction to Enumerations
Determining the Values of Enumeration Elements
Duplicate Values Are Allowed!
Determining the Types of Enumeration Elements
Retrieving the Types of Enumeration Elements at Runtime
Converting Enumerations to Other Types
Converting to Numeric Values and Vice Versa
Parsing Strings into Enumerations
Flags Enumerations
Querying Flags Enumerations
17. Developing with Generics
Introduction
Generics: Using One Code Base for Different Types
Solution Approaches
Standardizing the Code Base of a Type by Using Generics
Constraints
Constraining Generic Types to a Specific Base Class
Constraining a Generic Type to Specific Interfaces
Constraining a Generic Type to Classes with a Default Constructor
Constraining a Generic Class to Value Types
Combining Constraints and Specifying Multiple Type Parameters
18. Advanced Types
Nullable Value Types
Be Careful When Using Boolean Expressions Based on Nullables
Special Characteristics of Nullable During Boxing
The Difference Between Nothing and Nothing as a Default Value
Generic Delegates
Action(Of T)
Function(Of T)
Tuple(Of T)
Type Variance
Extension Methods
The Main Application Area of Extension Methods
Using Extension Methods to Simplify Collection Initializers
III. Programming with .NET Framework Data Structures
19. Arrays and Collections
Array Basics
Initializing Arrays
Changing Array Dimensions at Runtime
The Magic of ReDim
Pre-Allocating Values of Array Elements in Code
Type Inference When Using Array Initializers
Dominant Types
Multidimensional Arrays and Jagged Arrays
Jagged Arrays
Important Array Properties and Methods
Determining the Number of Array Elements by Using Length
Sorting Arrays with Array.Sort
Reversing the Array Order with Array.Reverse
Searching a Sorted Array with Array.BinarySearch
Implementing Sort and BinarySearch Custom Classes
Implementing Class Comparability with IComparable
Using Lambdas with Array Methods
Enumerators
Custom Enumerators with IEnumerable
Collection Basics
Initializing Collections
Using Extension Methods to Simplify Collection Initializers
Important Collections of .NET Framework
ArrayList: Universal Storage for Objects
Type-Safe Collections Based on CollectionBase
Hashtables: Fast Lookup for Objects
Using Hashtables
Processing Speed of Hashtables
Why the Access Time to Hashtable Elements Is Almost Constant...
... And Why You Should Know About It
Using Custom Classes as Key
Keys Must Be Immutable
Enumerating Data Elements in a Hashtable
The DictionaryBase Class
Queue: the FIFO Principle
Stack: the LIFO Principle
SortedList: Keeping Elements Permanently Sorted
Generic Collections
List(Of ) Collections and Lambda Expressions
ForEach and the Generic Action Delegate
Sort and the Generic Comparison Delegate
Find and the Generic Predicate Delegate
KeyedCollection: Key/Dictionary Collections with Additional Index Queries
Linking Elements with LinkedList(Of )
20. Serialization
Introduction to Serialization Techniques
Serializing with SoapFormatter and BinaryFormatter
Universal SOAP File Serializer and Deserializer
Universal Binary File Serializer and Deserializer
File Serializer Functionality
Shallow and Deep Object Cloning
The Universal DeepClone Method
Serializing Objects with Circular References
Serializing Objects of Different Versions When Using BinaryFormatter and SoapFormatter Classes
XML Serialization
Checking the Version Independence of the XML File
Serialization Problems with KeyedCollection
21. Attributes and Reflection
Introduction to Attributes
Using Attributes with ObsoleteAttribute
Visual Basic-Specific Attributes
Introduction to Reflection
The Type Class as the Origin for All Type Examinations
Class Analysis Functions Provided by a Type Object
Object Hierarchy of MemberInfo and Casting to a Specific Info Type
Determining Property Values with PropertyInfo at Runtime
Creating Custom Attributes and Recognizing Them at Runtime
Determining Custom Attributes at Runtime
IV. Development Simplifications in Visual Basic 2010
22. Using My as a Shortcut to Common Framework Functions
Visual Basic 2010 Simplifications Using the Example of the DotNetCopy Backup Tool
DotNetCopy Options: /Autostart and /Silent
The Principle Functionality of DotNetCopy
The My Namespace
Calling Forms Without Instantiation
Reading Command-Line Arguments with My.Application.CommandLineArgs
Targeted Access to Resources with My.Resources
Creating and Managing Resource Elements
Retrieving Resources with My.Resources
Writing Localizable Applications with Resource Files and the My Namespace
Simplified File Operations with My.Computer.FileSystem
Using Application Settings with My.Settings
Saving Application Settings with User Scope
23. The Application Framework
Application Framework Options
A Windows XP Look and Feel for Your Applications—Enabling Visual XP Styles
Preventing Multiple Application Starts—Creating a Single Instance Application
Save My.Settings Automatically on Shutdown
Specifying the User Authentication Mode
Specifying the End of Your Application—the Shutdown Mode
Displaying a Splash Dialog when Starting Complex Applications—Start Screen
Adding a Code File to Handle Application Events (Start, End, Network Status, Global Exceptions)
V. Language-Integrated Query—LINQ
24. Introduction to LINQ (Language-Integrated Query)
Getting Started with LINQ
LINQ: Based on Extension Methods
The Where Method
The Select Method
Anonymous Types
Type Inference for Generic Type Parameters
Combining LINQ Extension Methods
Simplified Use of LINQ Extension Methods with the LINQ Query Syntax
25. LINQ to Objects
Getting Started with LINQ to Objects
Anatomy of a LINQ Query
LINQ Query Performance
Concatenating LINQ Queries and Delayed Execution
Cascading Queries
Parallelizing LINQ Queries with AsParallel
Guidelines for Creating LINQ Queries
Forcing Query Execution with ToArray or ToList
Combining Multiple Collections
Combining Collections Implicitly
Combining Collections Explicitly
Grouping Collections
Grouping Collections from Multiple Collections
Group Join
Aggregate Functions
Returning Multiple Different Aggregations
Combining Grouped Queries and Aggregations
26. LINQ to XML
Getting Started with LINQ to XML
Processing XML Documents—Yesterday and Today
XML Literals: Using XML Directly in Code
Including Expressions in XML Literals
Creating XML Documents with LINQ
Querying XML Documents with LINQ to XML
IntelliSense Support for LINQ To XML Queries
Using Prefixes (fleet and article)
27. LINQ to Entities: Programming with Entity Framework
Prerequisites for Testing the Examples
Downloading and Installing SQL Server 2008 R2 Express Edition with Advanced Services
Installing the AdventureWorks Sample Databases
The Working Principle of an Entity Data Model
LINQ to Entities: the First Practical Example
Changing the Name of the Entity Set
Changing the Entity Container Name Retroactively
Editing the .edmx-File as XML Outside the Designer
Querying an Entity Model
Querying Data with LINQ to Entities Queries
How Queries Get to the Data Provider—Entity SQL (eSQL)
A Closer Look at Generated SQL Statements
Lazy Loading and Eager Loading in Entity Framework
Loading Data Manually and Retroactively During Lazy Loading
Using Eager Loading for Certain Relationships
Avoiding Anonymous Result Collections in Join Queries via Select
Compiled Queries
Modifying, Saving, and Deleting Data
Saving Data Modifications to the Database by Using SaveChanges
Inserting Related Data into Data Tables
Deleting Data from Tables
Concurrency Checks
Updating a Data Model from a Database
Model-First Design
Inheritance in the Conceptual Data Model
Executing T-SQL Commands Directly in the Object Context
Working with Stored Procedures
Looking Ahead
VI. Parallelizing Applications
28. Programming with the Task Parallel Library (TPL)
Introduction to Threading
Various Options for Starting a Thread
Using the Thread Class
Background Threads Always End When the Main Application Ends
Simplifying Thread Start With Multi-Line Lambdas
Calling Delegates Asynchronously
Using the Task Class
Using a Thread Pool’s Thread directly
How to Access Windows Controls from Non-UI Threads
Parallelization with Parallel.For and Parallel.ForEach
Parallel.For
Example: Parallelizing the ImageResizer
Parallel.ForEach
Using ParallelLoopStates—Exit For for Parallel.For and Parallel.ForEach
Avoiding Errors When Parallelizing Loops
Working with Tasks
Waiting on Task Completion—WaitOne, WaitAny, and WaitAll
Tasks with and Without Return Values
How To Avoid Freezing the User Interface While Waiting For Tasks To Finish
Cancelling Tasks by Using CancellationToken
Synchronizing Threads
Synchronizing Threads with SyncLock
The Monitor Class
Monitor—Wait—Pulse
Synchronizing Limited Resources with Mutex
What’s Next?
A.
Klaus Löffelmann
Sarika Calla Purohit
Index
About the Authors
← Prev
Back
Next →
← Prev
Back
Next →