logo资料库

Pro C# 2010 and the .NET 4 Platform(PDF清晰版).pdf

第1页 / 共1753页
第2页 / 共1753页
第3页 / 共1753页
第4页 / 共1753页
第5页 / 共1753页
第6页 / 共1753页
第7页 / 共1753页
第8页 / 共1753页
资料共1753页,剩余部分请下载后查看
Prelim
Contents at a Glance
Contents
About the Author
About the Technical Reviewer
Acknowledgments
Introduction
We’re a Team, You and I
An Overview of This Book
Obtaining This Book’s Source Code
Obtaining Updates for This Book
Contacting Me
Part 1: Introducing C# and the .NET Platform
The Philosophy of .NET
Understanding the Previous State of Affairs
Life As a C/Windows API Programmer
Life As a C++/MFC Programmer
Life As a Visual Basic 6.0 Programmer
Life As a Java Programmer
Life As a COM Programmer
The Complexity of COM Data Type Representation
The .NET Solution
Introducing the Building Blocks of the .NET Platform (the CLR, CTS, and CLS)
The Role of the Base Class Libraries
What C# Brings to the Table
Additional .NET-Aware Programming Languages
Life in a Multi-Language World
An Overview of .NET Assemblies
Single-File and Multi-File Assemblies
The Role of the Common Intermediate Language
Benefits of CIL
Compiling CIL to Platform-Specific Instructions
The Role of .NET Type Metadata
The Role of the Assembly Manifest
Understanding the Common Type System
CTS Class Types
CTS Interface Types
CTS Structure Types
CTS Enumeration Types
CTS Delegate Types
CTS Type Members
Intrinsic CTS Data Types
Understanding the Common Language Specification
Ensuring CLS Compliance
Understanding the Common Language Runtime
The Assembly/Namespace/Type Distinction
The Role of the Microsoft Root Namespace
Accessing a Namespace Programmatically
Referencing External Assemblies
Exploring an Assembly Using ildasm.exe
Viewing CIL Code
Viewing Type Metadata
Viewing Assembly Metadata (aka the Manifest)
Exploring an Assembly Using Reflector
Deploying the .NET Runtime
The .NET Client Profile Runtime
The Platform-Independent Nature of .NET
Summary
Building C# Applications
The Role of the .NET Framework 4.0 SDK
The Visual Studio 2010 Command Prompt
Building C# Applications Using csc.exe
Specifying Input and Output Targets
Referencing External Assemblies
Referencing Multiple External Assemblies
Compiling Multiple Source Files
Working with C# Response Files
The Default Response File (csc.rsp)
Building .NET Applications Using Notepad++
Building .NET Applications Using SharpDevelop
Building a Simple Test Project
Building .NET Applications Using Visual C# 2010 Express
Some Unique Features of Visual C# 2010 Express
Building .NET Applications Using Visual Studio 2010
Some Unique Features of Visual Studio 2010
Targeting the .NET Framework Using the New Project Dialog Box
Using the Solution Explorer Utility
Referencing External Assemblies
Viewing Project Properties
The Class View Utility
The Object Browser Utility
Integrated Support for Code Refactoring
Code Expansions and Surround With Technology
The Visual Class Designer
The Integrated .NET Framework 4.0 SDK Documentation System
Summary
Part 2: Core C# Programming Constructs
Core C# Programming Constructs, Part I
The Anatomy of a Simple C# Program
Variations on the Main() Method
Specifying an Application Error Code
Processing Command-Line Arguments
Specifying Command-Line Arguments with Visual Studio 2010
An Interesting Aside: Some Additional Members of the System.Environment Class
The System.Console Class
Basic Input and Output with the Console Class
Formatting Console Output
Formatting Numerical Data
Formatting Numerical Data Beyond Console Applications
System Data Types and C# Shorthand Notation
Variable Declaration and Initialization
Intrinsic Data Types and the new Operator
The Data Type Class Hierarchy
Members of Numerical Data Types
Members of System.Boolean
Members of System.Char
Parsing Values from String Data
System.DateTime and System.TimeSpan
The .NET 4.0 System.Numerics Namespace
Working with String Data
Basic String Manipulation
String Concatenation
Escape Characters
Defining Verbatim Strings
Strings and Equality
Strings Are Immutable
The System.Text.StringBuilder Type
Narrowing and Widening Data Type Conversions
Trapping Narrowing Data Conversions
Setting Project-wide Overflow Checking
The unchecked Keyword
The Role of System.Convert
Understanding Implicitly Typed Local Variables
Restrictions on Implicitly Typed Variables
Implicit Typed Data Is Strongly Typed Data
Usefulness of Implicitly Typed Local Variables
C# Iteration Constructs
The for Loop
The foreach Loop
Use of var Within foreach Constructs
The while and do/while Looping Constructs
Decision Constructs and the Relational/Equality Operators
The if/else Statement
The switch Statement
Summary
Core C# Programming Constructs, Part II
Methods and Parameter Modifiers
The Default Parameter-Passing Behavior
The out Modifier
The ref Modifier
The params Modifier
Defining Optional Parameters
Invoking Methods using Named Parameters
Understanding Method Overloading
Understanding C# Arrays
C# Array Initialization Syntax
Implicitly Typed Local Arrays
Defining an Array of Objects
Working with Multidimensional Arrays
Arrays As Arguments or Return Values
The System.Array Base Class
Understanding the Enum Type
Controlling the Underlying Storage for an Enum
Declaring Enum Variables
The System.Enum Type
Dynamically Discovering an Enum’s Name/Value Pairs
Understanding the Structure Type
Creating Structure Variables
Understanding Value Types and Reference Types
Value Types, References Types, and the Assignment Operator
Value Types Containing Reference Types
Passing Reference Types by Value
Passing Reference Types by Reference
Final Details Regarding Value Types and Reference Types
Understanding C# Nullable Types
Working with Nullable Types
The ?? Operator
Summary
Defining Encapsulated Class Types
Introducing the C# Class Type
Allocating Objects with the new Keyword
Understanding Constructors
The Role of the Default Constructor
Defining Custom Constructors
The Default Constructor Revisited
The Role of the this Keyword
Chaining Constructor Calls Using this
Observing Constructor Flow
Revisiting Optional Arguments
Understanding the static Keyword
Defining Static Methods
Defining Static Field Data
Defining Static Constructors
Defining Static Classes
Defining the Pillars of OOP
The Role of Encapsulation
The Role of Inheritance
The Role of Polymorphism
C# Access Modifiers
The Default Access Modifiers
Access Modifiers and Nested Types
The First Pillar: C#’s Encapsulation Services
Encapsulation Using Traditional Accessors and Mutators
Encapsulation Using .NET Properties
Using Properties within a Class Definition
Internal Representation of Properties
Controlling Visibility Levels of Property Get/Set Statements
Read-Only and Write-Only Properties
Static Properties
Understanding Automatic Properties
Interacting with Automatic Properties
Regarding Automatic Properties and Default Values
Understanding Object Initializer Syntax
Calling Custom Constructors with Initialization Syntax
Initializing Inner Types
Working with Constant Field Data
Understanding Read-Only Fields
Static Read-Only Fields
Understanding Partial Types
Summary
Understanding Inheritance and Polymorphism
The Basic Mechanics of Inheritance
Specifying the Parent Class of an Existing Class
Regarding Multiple Base Classes
The sealed Keyword
Revising Visual Studio Class Diagrams
The Second Pillar of OOP: The Details of Inheritance
Controlling Base Class Creation with the base Keyword
Keeping Family Secrets: The protected Keyword
Adding a Sealed Class
Programming for Containment/Delegation
Understanding Nested Type Definitions
The Third Pillar of OOP: C#’s Polymorphic Support
The virtual and override Keywords
Overriding Virtual Members Using Visual Studio 2010
Sealing Virtual Members
Understanding Abstract Classes
Understanding the Polymorphic Interface
Understanding Member Shadowing
Understanding Base Class/Derived Class Casting Rules
The C# as Keyword
The C# is Keyword
The Master Parent Class: System.Object
Overriding System.Object.ToString()
Overriding System.Object.Equals()
Overriding System.Object.GetHashCode()
Testing Your Modified Person Class
The Static Members of System.Object
Summary
Understanding Structured Exception Handling
Ode to Errors, Bugs, and Exceptions
The Role of .NET Exception Handling
The Atoms of .NET Exception Handling
The System.Exception Base Class
The Simplest Possible Example
Throwing a General Exception
Catching Exceptions
Configuring the State of an Exception
The TargetSite Property
The StackTrace Property
The HelpLink Property
The Data Property
System-Level Exceptions (System.SystemException)
Application-Level Exceptions (System.ApplicationException)
Building Custom Exceptions, Take One
Building Custom Exceptions, Take Two
Building Custom Exceptions, Take Three
Processing Multiple Exceptions
General catch Statements
Rethrowing Exceptions
Inner Exceptions
The Finally Block
Who Is Throwing What?
The Result of Unhandled Exceptions
Debugging Unhandled Exceptions Using Visual Studio
A Brief Word Regarding Corrupted State Exceptions (CSE)
Summary
Understanding Object Lifetime
Classes, Objects, and References
The Basics of Object Lifetime
The CIL of new
Setting Object References to null
The Role of Application Roots
Understanding Object Generations
Concurrent Garbage Collection under .NET 1.0 3.5
Background Garbage Collection under .NET 4.0
The System.GC Type
Forcing a Garbage Collection
Building Finalizable Objects
Overriding System.Object.Finalize()
Detailing the Finalization Process
Building Disposable Objects
Reusing the C# using Keyword
Building Finalizable and Disposable Types
A Formalized Disposal Pattern
Understanding Lazy Object Instantiation
Customizing the Creation of the Lazy Data
Summary
Part 3: Advanced C# Programming Constructs
Working with Interfaces
Understanding Interface Types
Interface Types vs. Abstract Base Classes
Defining Custom Interfaces
Implementing an Interface
Invoking Interface Members at the Object Level
Obtaining Interface References: The as Keyword
Obtaining Interface References: The is Keyword
Interfaces As Parameters
Interfaces As Return Values
Arrays of Interface Types
Implementing Interfaces Using Visual Studio 2010
Resolving Name Clashes via Explicit Interface Implementation
Designing Interface Hierarchies
Multiple Inheritance with Interface Types
Building Enumerable Types (IEnumerable and IEnumerator)
Building Iterator Methods with the yield Keyword
Building a Named Iterator
Internal Representation of an Iterator Method
Building Cloneable Objects (ICloneable)
A More Elaborate Cloning Example
Building Comparable Objects (IComparable)
Specifying Multiple Sort Orders (IComparer)
Custom Properties, Custom Sort Types
Summary
Understanding Generics
The Issues with Non-Generic Collections
The Issue of Performance
The Issue of Type Safety
The Role of Generic Type Parameters
Specifying Type Parameters for Generic Classes / Structures
Specifying Type Parameters for Generic Members
Specifying Type Parameters for Generic Interfaces
The System.Collections.Generic Namespace
Understanding Collection Initialization Syntax
Working with the List Class
Working with the Stack Class
Working with the Queue Class
Working with the SortedSet Class
Creating Custom Generic Methods
Inference of Type Parameters
Creating Custom Generic Structures and Classes
The default Keyword in Generic Code
Generic Base Classes
Constraining Type Parameters
Examples Using the where Keyword
The Lack of Operator Constraints
Summary
Delegates, Events, and Lambdas
Understanding the .NET Delegate Type
Defining a Delegate Type in C#
The System.MulticastDelegate and System.Delegate Base Classes
The Simplest Possible Delegate Example
Investigating a Delegate Object
Sending Object State Notifications using Delegates
Enabling Multicasting
Removing Targets from a Delegate’s Invocation List
Method Group Conversion Syntax
Understanding Delegate Covariance
Understanding Generic Delegates
Simulating Generic Delegates Without Generics
Understanding C# Events
The C# event Keyword
Events under the Hood
Listening to Incoming Events
Simplifying Event Registration Using Visual Studio 2010
Creating Custom Event Arguments
The Generic EventHandler Delegate
Understanding C# Anonymous Methods
Accessing Local Variables
Understanding Lambda Expressions
Dissecting a Lambda Expression
Processing Arguments Within Multiple Statements
Lambda Expressions with Multiple (or Zero) Parameters
Retrofitting the CarEvents Example Using Lambda Expressions
Summary
Advanced C# Language Features
Understanding Indexer Methods
Indexing Data Using String Values
Overloading Indexer Methods
Indexers with Multiple Dimensions
Indexer Definitions on Interface Types
Understanding Operator Overloading
Overloading Binary Operators
And What of the += and –+ Operators?
Overloading Unary Operators
Overloading Equality Operators
Overloading Comparison Operators
The Internal Representation of Overloaded Operators
Final Thoughts Regarding Operator Overloading
Understanding Custom Type Conversions
Recall: Numerical Conversions
Recall: Conversions Among Related Class Types
Creating Custom Conversion Routines
Additional Explicit Conversions for the Square Type
Defining Implicit Conversion Routines
The Internal Representation of Custom Conversion Routines
Understanding Extension Methods
Defining Extension Methods
Invoking Extension Methods on an Instance Level
Invoking Extension Methods Statically
The Scope of an Extension Method
Importing Types That Define Extension Methods
The IntelliSense of Extension Methods
Building and Using Extension Libraries
Extending Interface Types via Extension Methods
Understanding Partial Methods
A First Look at Partial Methods
Uses of Partial Methods
Understanding Anonymous Types
The Internal Representation of Anonymous Types
The Implementation of ToString() and GetHashCode()
The Semantics of Equality for Anonymous Types
Anonymous Types Containing Anonymous Types
Working with Pointer Types
The unsafe Keyword
Working with the * and & Operators
An Unsafe (and Safe) Swap Function
Field Access via Pointers (the -> Operator)
The stackalloc Keyword
Pinning a Type via the fixed Keyword
The sizeof Keyword
Summary
LINQ to Objects
LINQ Specific Programming Constructs
Implicit Typing of Local Variables
Object and Collection Initialization Syntax
Lambda Expressions
Extension Methods
Anonymous Types
Understanding the Role of LINQ
LINQ Expressions Are Strongly Typed
The Core LINQ Assemblies
Applying LINQ Queries to Primitive Arrays
Once Again, Without LINQ
Reflecting Over a LINQ Result Set
LINQ and Implicitly Typed Local Variables
LINQ and Extension Methods
The Role of Deferred Execution
The Role of Immediate Execution
Returning the Result of a LINQ Query
Returning LINQ Results via Immediate Execution
Applying LINQ Queries to Collection Objects
Accessing Contained Subobjects
Applying LINQ Queries to Nongeneric Collections
Filtering Data Using OfType()
Investigating the C# LINQ Query Operators
Basic Selection Syntax
Obtaining Subsets of Data
Projecting New Data Types
Obtaining Counts Using Enumerable
Reversing Result Sets
Sorting Expressions
LINQ As a Better Venn Diagramming Tool
Removing Duplicates
LINQ Aggregation Operations
The Internal Representation of LINQ Query Statements
Building Query Expressions with Query Operators (Revisited)
Building Query Expressions Using the Enumerable Type and Lambda Expressions
Building Query Expressions Using the Enumerable Type and Anonymous Methods
Building Query Expressions Using the Enumerable Type and Raw Delegates
Summary
Part 4: Programming with .NET Assemblies
Configuring .NET Assemblies
Defining Custom Namespaces
Resolving Name Clashes with Fully Qualified Names
Resolving Name Clashes with Aliases
Creating Nested Namespaces
The Default Namespace of Visual Studio 2010
The Role of .NET Assemblies
Assemblies Promote Code Reuse
Assemblies Establish a Type Boundary
Assemblies Are Versionable Units
Assemblies Are Self-Describing
Assemblies Are Configurable
Understanding the Format of a .NET Assembly
The Windows File Header
The CLR File Header
CIL Code, Type Metadata, and the Assembly Manifest
Optional Assembly Resources
Single-File and Multifile Assemblies
Building and Consuming a Single-File Assembly
Exploring the Manifest
Exploring the CIL
Exploring the Type Metadata
Building a C# Client Application
Building a Visual Basic Client Application
Cross-Language Inheritance in Action
Building and Consuming a Multifile Assembly
Exploring the ufo.netmodule File
Exploring the airvehicles.dll File
Consuming a Multifile Assembly
Understanding Private Assemblies
The Identity of a Private Assembly
Understanding the Probing Process
Configuring Private Assemblies
Configuration Files and Visual Studio 2010
Understanding Shared Assemblies
Understanding Strong Names
Generating Strong Names at the Command Line
Generating Strong Names using Visual Studio 2010
Installing Strongly Named Assemblies to the GAC
Viewing the .NET 4.0 GAC using Windows Explorer
Consuming a Shared Assembly
Exploring the Manifest of SharedCarLibClient
Configuring Shared Assemblies
Freezing the Current Shared Assembly
Building Shared Assembly Version 2.0.0.0
Dynamically Redirecting to Specific Versions of a Shared Assembly
Understanding Publisher Policy Assemblies
Disabling Publisher Policy
Understanding the Element
The System.Configuration Namespace
Summary
Type Reflection, Late Binding, and Attribute-Based Programming
The Necessity of Type Metadata
Viewing (Partial) Metadata for the EngineState Enumeration
Viewing (Partial) Metadata for the Car Type
Examining a TypeRef
Documenting the Defining Assembly
Documenting Referenced Assemblies
Documenting String Literals
Understanding Reflection
The System.Type Class
Obtaining a Type Reference Using System.Object.GetType()
Obtaining a Type Reference Using typeof()
Obtaining a Type Reference Using System.Type.GetType()
Building a Custom Metadata Viewer
Reflecting on Methods
Reflecting on Fields and Properties
Reflecting on Implemented Interfaces
Displaying Various Odds and Ends
Implementing Main()
Reflecting on Generic Types
Reflecting on Method Parameters and Return Values
Dynamically Loading Assemblies
Reflecting on Shared Assemblies
Understanding Late Binding
The System.Activator Class
Invoking Methods with No Parameters
Invoking Methods with Parameters
Understanding the Role of .NET Attributes
Attribute Consumers
Applying Attributes in C#
C# Attribute Shorthand Notation
Specifying Constructor Parameters for Attributes
The Obsolete Attribute in Action
Building Custom Attributes
Applying Custom Attributes
Named Property Syntax
Restricting Attribute Usage
Assembly-Level (and Module-Level) Attributes
The Visual Studio 2010 AssemblyInfo.cs File
Reflecting on Attributes Using Early Binding
Reflecting on Attributes Using Late Binding
Putting Reflection, Late Binding, and Custom Attributes in Perspective
Building an Extendable Application
Building CommonSnappableTypes.dll
Building the C# Snap-In
Building the Visual Basic Snap-In
Building an Extendable Windows Forms Application
Summary
Processes, AppDomains, and Object Contexts
The Role of a Windows Process
The Role of Threads
Interacting with Processes Under the .NET Platform
Enumerating Running Processes
Investigating a Specific Process
Investigating a Process’s Thread Set
Investigating a Process’s Module Set
Starting and Stopping Processes Programmatically
Controlling Process Startup using the ProcessStartInfo Class
Understanding .NET Application Domains
The System.AppDomain Class
Interacting with the Default Application Domain
Enumerating Loaded Assemblies
Receiving Assembly Load Notifications
Creating New Application Domains
Loading Assemblies into Custom Application Domains
Programmatically Unloading AppDomains
Understanding Object Context Boundaries
Context-Agile and Context-Bound Types
Defining a Context-Bound Object
Inspecting an Object’s Context
Summarizing Processes, AppDomains, and Context
Summary
Understanding CIL and the Role of Dynamic Assemblies
Reasons for Learning the Grammar of CIL
Examining CIL Directives, Attributes, and Opcodes
The Role of CIL Directives
The Role of CIL Attributes
The Role of CIL Opcodes
The CIL Opcode/CIL Mnemonic Distinction
Pushing and Popping: The Stack-Based Nature of CIL
Understanding Round-Trip Engineering
The Role of CIL Code Labels
Interacting with CIL: Modifying an *.il File
Compiling CIL Code Using ilasm.exe
Authoring CIL Code Using SharpDevelop
The Role of peverify.exe
Understanding CIL Directives and Attributes
Specifying Externally Referenced Assemblies in CIL
Defining the Current Assembly in CIL
Defining Namespaces in CIL
Defining Class Types in CIL
Defining and Implementing Interfaces in CIL
Defining Structures in CIL
Defining Enums in CIL
Defining Generics in CIL
Compiling the CILTypes.il file
.NET Base Class Library, C#, and CIL Data Type Mappings
Defining Type Members in CIL
Defining Field Data in CIL
Defining Type Constructors in CIL
Defining Properties in CIL
Defining Member Parameters
Examining CIL Opcodes
The .maxstack Directive
Declaring Local Variables in CIL
Mapping Parameters to Local Variables in CIL
The Hidden this Reference
Representing Iteration Constructs in CIL
Building a .NET Assembly with CIL
Building CILCars.dll
Building CILCarClient.exe
Understanding Dynamic Assemblies
Exploring the System.Reflection.Emit Namespace
The Role of the System.Reflection.Emit.ILGenerator
Emitting a Dynamic Assembly
Emitting the Assembly and Module Set
The Role of the ModuleBuilder Type
Emitting the HelloClass Type and the String Member Variable
Emitting the Constructors
Emitting the SayHello() Method
Using the Dynamically Generated Assembly
Summary
Dynamic Types and the Dynamic Language Runtime
The Role of the C# dynamic Keyword
Calling Members on Dynamically Declared Data
The Role of the Microsoft.CSharp.dll Assembly
The Scope of the dynamic keyword
Limitations of the dynamic Keyword
Practical Uses of the dynamic Keyword
The Role of the Dynamic Language Runtime (DLR)
The Role of Expression Trees
The Role of the System.Dynamic Namespace
Dynamic Runtime Lookup of Expression Trees
Simplifying Late Bound Calls Using Dynamic Types
Leveraging the dynamic Keyword to Pass Arguments
Simplifying COM Interoperability using Dynamic Data
The Role of Primary Interop Assemblies (PIAs)
Embedding Interop Metadata
Common COM Interop Pain Points
COM Interop using C# 4.0 Language Features
COM interop without C# 4.0 Language Features
Summary
Part 5: Introducing the .NET Base Class Libraries
Multithreaded and Parallel Programming
The Process/AppDomain/Context/Thread Relationship
The Problem of Concurrency
The Role of Thread Synchronization
A Brief Review of the .NET Delegate
The Asynchronous Nature of Delegates
The BeginInvoke() and EndInvoke() Methods
The System.IAsyncResult Interface
Invoking a Method Asynchronously
Synchronizing the Calling Thread
The Role of the AsyncCallback Delegate
The Role of the AsyncResult Class
Passing and Receiving Custom State Data
The System.Threading Namespace
The System.Threading.Thread Class
Obtaining Statistics About the Current Thread
The Name Property
The Priority Property
Programmatically Creating Secondary Threads
Working with the ThreadStart Delegate
Working with the ParameterizedThreadStart Delegate
The AutoResetEvent Class
Foreground Threads and Background Threads
The Issue of Concurrency
Synchronization Using the C# lock Keyword
Synchronization Using the System.Threading.Monitor Type
Synchronization Using the System.Threading.Interlocked Type
Synchronization Using the [Synchronization] Attribute
Programming with Timer Callbacks
Understanding the CLR ThreadPool
Parallel Programming under the .NET Platform
The Task Parallel Library API
The Role of the Parallel Class
Understanding Data Parallelism
The Task Class
Handling Cancelation Request
Understanding Task Parallelism
Parallel LINQ Queries (PLINQ)
Opting in to a PLINQ Query
Canceling a PLINQ Query
Summary
File I/O and Object Serialization
Exploring the System.IO Namespace
The Directory(Info) and File(Info) Types
The Abstract FileSystemInfo Base Class
Working with the DirectoryInfo Type
Enumerating Files with the DirectoryInfo Type
Creating Subdirectories with the DirectoryInfo Type
Working with the Directory Type
Working with the DriveInfo Class Type
Working with the FileInfo Class
The FileInfo.Create() Method
The FileInfo.Open() Method
The FileInfo.OpenRead() and FileInfo.OpenWrite() Methods
The FileInfo.OpenText() Method
The FileInfo.CreateText() and FileInfo.AppendText() Methods
Working with the File Type
Additional File-centric Members
The Abstract Stream Class
Working with FileStreams
Working with StreamWriters and StreamReaders
Writing to a Text File
Reading from a Text File
Directly Creating StreamWriter/StreamReader Types
Working with StringWriters and StringReaders
Working with BinaryWriters and BinaryReaders
Watching Files Programmatically
Understanding Object Serialization
The Role of Object Graphs
Configuring Objects for Serialization
Defining Serializable Types
Public Fields, Private Fields, and Public Properties
Choosing a Serialization Formatter
The IFormatter and IRemotingFormatter Interfaces
Type Fidelity Among the Formatters
Serializing Objects Using the BinaryFormatter
Deserializing Objects Using the BinaryFormatter
Serializing Objects Using the SoapFormatter
Serializing Objects Using the XmlSerializer
Controlling the Generated XML Data
Serializing Collections of Objects
Customizing the Soap/Binary Serialization Process
A Deeper Look at Object Serialization
Customizing Serialization Using ISerializable
Customizing Serialization Using Attributes
Summary
ADO.NET Part I: The Connected Layer
A High-Level Definition of ADO.NET
The Three Faces of ADO.NET
Understanding ADO.NET Data Providers
The Microsoft-Supplied ADO.NET Data Providers
A Word Regarding System.Data.OracleClient.dll
Obtaining Third-Party ADO.NET Data Providers
Additional ADO.NET Namespaces
The Types of the System.Data Namespace
The Role of the IDbConnection Interface
The Role of the IDbTransaction Interface
The Role of the IDbCommand Interface
The Role of the IDbDataParameter and IDataParameter Interfaces
The Role of the IDbDataAdapter and IDataAdapter Interfaces
The Role of the IDataReader and IDataRecord Interfaces
Abstracting Data Providers Using Interfaces
Increasing Flexibility Using Application Configuration Files
Creating the AutoLot Database
Creating the Inventory Table
Authoring the GetPetName() Stored Procedure
Creating the Customers and Orders Tables
Visually Creating Table Relationships
The ADO.NET Data Provider Factory Model
A Complete Data Provider Factory Example
A Potential Drawback with the Provide Factory Model
The Element
Understanding the Connected Layer of ADO.NET
Working with Connection Objects
Working with ConnectionStringBuilder Objects
Working with Command Objects
Working with Data Readers
Obtaining Multiple Result Sets Using a Data Reader
Building a Reusable Data Access Library
Adding the Connection Logic
Adding the Insertion Logic
Adding the Deletion Logic
Adding the Update Logic
Adding the Selection Logic
Working with Parameterized Command Objects
Specifying Parameters Using the DbParameter Type
Executing a Stored Procedure
Creating a Console UI–Based Front End
Implementing the Main() Method
Implementing the ShowInstructions() Method
Implementing the ListInventory() Method
Implementing the DeleteCar() Method
Implementing the InsertNewCar() Method
Implementing the UpdateCarPetName() Method
Implementing LookUpPetName()
Understanding Database Transactions
Key Members of an ADO.NET Transaction Object
Adding a CreditRisks Table to the AutoLot Database
Adding a Transaction Method to InventoryDAL
Testing Your Database Transaction
Summary
ADO.NET Part II: The Disconnected Layer
Understanding the Disconnected Layer of ADO.NET
Understanding the Role of the DataSet
Key Properties of the DataSet
Key Methods of the DataSet
Building a DataSet
Working with DataColumns
Building a DataColumn
Enabling Autoincrementing Fields
Adding DataColumn Objects to a DataTable
Working with DataRows
Understanding the RowState Property
Understanding the DataRowVersion Property
Working with DataTables
Inserting DataTables into DataSets
Obtaining Data in a DataSet
Processing DataTable Data Using DataTableReader Objects
Serializing DataTable/DataSet Objects As XML
Serializing DataTable/DataSet Objects in a Binary Format
Binding DataTable Objects to Windows Forms GUIs
Hydrating a DataTable from a Generic List
Deleting Rows from a DataTable
Selecting Rows Based on Filter Criteria
Updating Rows Within a DataTable
Working with the DataView Type
Working with Data Adapters
A Simple Data Adapter Example
Mapping Database Names to Friendly Names
Adding Disconnection Functionality to AutoLotDAL.dll
Defining the Initial Class Type
Configuring the Data Adapter Using the SqlCommandBuilder
Implementing GetAllInventory()
Implementing UpdateInventory()
Setting Your Version Number
Testing the Disconnected Functionality
Multitabled DataSet Objects and Data Relationships
Prepping the Data Adapters
Building the Table Relationships
Updating the Database Tables
Navigating Between Related Tables
The Windows Forms Database Designer Tools
Visually Designing the DataGridView
The Generated app.config File
Examining the Strongly Typed DataSet
Examining the Strongly Typed DataTable
Examining the Strongly Typed DataRow
Examining the Strongly Typed Data Adapter
Completing the Windows Forms Application
Isolating Strongly Typed Database Code into a Class Library
Viewing the Generated Code
Selecting Data with the Generated Code
Inserting Data with the Generated Code
Deleting Data with the Generated Code
Invoking a Stored Procedure using the Generated Code
Programming with LINQ to DataSet
The Role of the DataSet Extensions Library
Obtaining a LINQ-Compatible DataTable
The Role of the DataRowExtensions.Field() Extension Method
Hydrating New DataTables from LINQ Queries
Summary
ADO.NET Part III: The Entity Framework
Understanding the Role of Entity Framework
The Role of Entities
The Building Blocks of the Entity Framework
The Role of Object Services
The Role of the Entity Client
The Role of the *.edmx File (and Friends)
The Role of the ObjectContext and ObjectSet Classes
All Together Now!
Building and Analyzing your First EDM
Generating the *.edmx File
Reshaping the Entity Data
Viewing the Mappings
Viewing the Generated *.edmx File Data
Viewing the Generated Source Code
Enhancing the Generated Source Code
Programming Against the Conceptual Model
Deleting a Record
Updating a Record
Querying with LINQ to Entities
Querying with Entity SQL
Working with the Entity Client Data Reader Object
AutoLotDAL Version 4.0, Now with Entities
Mapping the Stored Procedure
The Role of Navigation Properties
Using Navigation Properties within LINQ to Entity Queries
Invoking a Stored Procedure
Data Binding Entities to Windows Forms GUIs
Adding the Data Binding Code
Summary
Introducing LINQ to XML
A Tale of Two XML APIs
LINQ to XML As a Better DOM
VB Literal Syntax As a Better LINQ to XML
Members of the System.Xml.Linq Namespace
The LINQ to XML Axis Methods
The Oddness of XName (and XNamespace)
Working with XElement and XDocument
Generating Documents from Arrays and Containers
Loading and Parsing XML Content
Manipulating an in Memory XML Document
Building the UI of the LINQ to XML App
Import the Inventory.xml File
Defining a LINQ to XML Helper Class
Rigging up the UI to Your Helper Class
Summary
Introducing Windows Communication Foundation
A Potpourri of Distributed Computing APIs
The Role of DCOM
The Role of COM+/Enterprise Services
The Role of MSMQ
The Role of .NET Remoting
The Role of XML Web Services
A .NET Web Service Example
Web Service Standards
Named Pipes, Sockets, and P2P
The Role of WCF
An Overview of WCF Features
An Overview of Service-Oriented Architecture
Tenet 1: Boundaries Are Explicit
Tenet 2: Services Are Autonomous
Tenet 3: Services Communicate via Contract, Not Implementation
Tenet 4: Service Compatibility Is Based on Policy
WCF: The Bottom Line
Investigating the Core WCF Assemblies
The Visual Studio WCF Project Templates
The WCF Service Website Project Template
The Basic Composition of a WCF Application
The ABCs of WCF
Understanding WCF Contracts
Understanding WCF Bindings
HTTP-Based Bindings
TCP-Based Bindings
MSMQ-Based Bindings
Understanding WCF Addresses
Building a WCF Service
The [ServiceContract] Attribute
The [OperationContract] Attribute
Service Types As Operational Contracts
Hosting the WCF Service
Establishing the ABCs Within an App.config File
Coding Against the ServiceHost Type
Specifying Base Addresses
Details of the ServiceHost Type
Details of the Element
Enabling Metadata Exchange
Building the WCF Client Application
Generating Proxy Code Using svcutil.exe
Generating Proxy Code Using Visual Studio 2010
Configuring a TCP-Based Binding
Simplifying Configuration Settings with WCF 4.0
Default Endpoints in WCF 4.0
Exposing a Single WCF Service Using Multiple Bindings
Changing Settings for a WCF Binding
The WCF 4.0 Default MEX Behavior Configuration
Refreshing the Client Proxy and Selecting the Binding
Using the WCF Service Library Project Template
Building a Simple Math Service
Testing the WCF Service with WcfTestClient.exe
Altering Configuration Files Using SvcConfigEditor.exe
Hosting the WCF Service within a Windows Service
Specifying the ABCs in Code
Enabling MEX
Creating a Windows Service Installer
Installing the Windows Service
Invoking a Service Asynchronously from the Client
Designing WCF Data Contracts
Using the Web-Centric WCF Service Project Template
Implementing the Service Contract
The Role of the *.svc File
Examining the Web.config File
Testing the Service
Summary
Introducing Windows Workflow Foundation 4.0
Defining a Business Process
The Role of WF 4.0
Building a (Painfully) Simple Workflow
Viewing the Underlying XAML
The WF 4.0 Runtime
Hosting a Workflow using WorkflowInvoker
Passing Arguments to your Workflow using WorkflowInvoker
Defining Arguments using the Workflow Designer
Hosting a Workflow using WorkflowApplication
Recap of your First Workflow
Examining the Workflow 4.0 Activities
Control Flow Activities
Flowchart Activities
Messaging Activities
The Runtime and Primitives Activities
The Transaction Activities
The Collection and Error Handling Activities
Building a Flowchart Workflow
Connecting Activities in a Flowchart
Working with the InvokeMethod Activity
Defining Workflow Wide Variables
Working with the FlowDecision Activity
Working with the TerminateWorkflow Activity
Building the “True” Condition
Working with the ForEach Activity
Completing the Application
Reflecting on What We Have Done
Isolating Workflows into Dedicated Libraries
Defining the Initial Project
Importing Assemblies and Namespaces
Defining the Workflow Arguments
Defining Workflow Variables
Working with the Assign Activity
Working with the If and Switch Activities
Building a Custom Code Activity
Consuming the Workflow Library
Retrieving the Workflow Output Argument
Summary
Part 6: Building Desktop User Interfaces with WPF
Introducing Windows Presentation Foundation and XAML
The Motivation Behind WPF
Unifying Diverse APIs
Providing a Separation of Concerns via XAML
Providing an Optimized Rendering Model
Simplifying Complex UI Programming
The Various Flavors of WPF
Traditional Desktop Applications
Navigation-Based WPF Applications
XBAP Applications
The WPF/Silverlight Relationship
Investigating the WPF Assemblies
The Role of the Application Class
Constructing an Application Class
Enumerating the Application.Windows collection
The Role of the Window Class
The Role of System.Windows.Controls.ContentControl
The Role of System.Windows.Controls.Control
The Role of System.Windows.FrameworkElement
The Role of System.Windows.UIElement
The Role of System.Windows.Media.Visual
The Role of System.Windows.DependencyObject
The Role of System.Windows.Threading.DispatcherObject
Building a WPF Application without XAML
Creating a Strongly Typed Window
Creating a Simple User Interface
Interacting with Application Level Data
Handling the Closing of a Window Object
Intercepting Mouse Events
Intercepting Keyboard Events
Building a WPF Application using Only XAML
Defining MainWindow in XAML
Defining the Application Object in XAML
Processing the XAML Files using msbuild.exe
Transforming Markup into a .NET Assembly
Mapping the Window XAML Data to C# Code
The Role of BAML
Mapping the Application XAML Data to C# Code
XAML-to-Assembly Process Summary
Understanding The Syntax of WPF XAML
Introducing Kaxaml
XAML XML Namespaces and XAML "Keywords"
Controlling Class and Member Variable Declarations
XAML Elements, XAML Attributes and Type Converters
Understanding XAML Property-Element Syntax
Understanding XAML Attached Properties
Understanding XAML Markup Extensions
Building a WPF Application using Code-Behind Files
Adding a Code File for the MainWindow Class
Adding a Code File for the MyApp Class
Processing the Code Files with msbuild.exe
Building WPF Applications Using Visual Studio 2010
The WPF Project Templates
Exploring the WPF Designer Tools
Designing the GUI of our Window
Implementing the Loaded Event
Implementing the Button’s Click Event
Implementing the Closed Event
Testing the Application
Summary
Programming with WPF Controls
A Survey of the Core WPF Controls
Working with WPF Controls Using Visual Studio 2010
The WPF Ink Controls
The WPF Document Controls
WPF Common Dialog Boxes
The Details Are in the Documentation
Controlling Content Layout Using Panels
Positioning Content Within Canvas Panels
Positioning Content Within WrapPanel Panels
Positioning Content Within StackPanel Panels
Positioning Content Within Grid Panels
Grids with GridSplitter Types
Positioning Content Within DockPanel Panels
Enabling Scrolling for Panel Types
Building a Window’s Frame Using Nested Panels
Building the Menu System
Building the ToolBar
Building the StatusBar
Finalizing the UI Design
Implementing the MouseEnter/MouseLeave Event Handlers
Implementing the Spell Checking Logic
Understanding WPF Control Commands
The Intrinsic Control Command Objects
Connecting Commands to the Command Property
Connecting Commands to Arbitrary Actions
Working with the Open and Save Commands
Building a WPF User Interface with Expression Blend
Getting to know the Key Aspects of the Blend IDE
Using the TabControl
Building the Ink API Tab
Designing the ToolBar
The RadioButton Control
The InkCanvas Control
The ComboBox Control
Saving, Loading, and Clearing InkCanvas Data
Introducing the Documents API
Block Elements and Inline Elements
Document Layout Managers
Building the Documents Tab
Populating a FlowDocument using Blend
Populating a FlowDocument Using Code
Enabling Annotations and Sticky Notes
Saving and Loading a Flow Document
Introducing the WPF Data-Binding Model
Building the Data Binding Tab
Establishing Data Bindings using Blend
The DataContext Property
Data Conversion Using IValueConverter
Establishing Data Bindings in Code
Building the DataGrid Tab
Summary
WPF Graphics Rendering Services
Understanding WPF's Graphical Rendering Services
WPF Graphical Rendering Options
Rendering Graphical Data Using Shapes
Adding Rectangles, Ellipses, and Lines to a Canvas
Removing Rectangles, Ellipses, and Lines from a Canvas
Working with Polylines and Polygons
Working with Paths
The Path "Modeling Mini Language"
WPF Brushes and Pens
Configuring Brushes Using Visual Studio 2010
Configuring Brushes in Code
Configuring Pens
Applying Graphical Transformations
A First Look at Transformations
Transforming our Canvas Data
Working with Shapes using Expression Blend
Selecting a Shape to Render from the Tool Palette
Converting Shapes to Paths
Combining Shapes
The Brush and Transformation Editors
Rendering Graphical Data Using Drawings and Geometries
Building a DrawingBrush using Geometries
Painting with the DrawingBrush
Containing Drawing Types in a DrawingImage
Generating Complex Vector Graphics using Expression Design
Exporting a Design Document to XAML
Rendering Graphical Data Using the Visual Layer
The Visual Base Class and Derived Child Classes
A First Look at using the DrawingVisual Class
Rendering Visual Data to a Custom Layout Manager
Responding to Hit Test Operations
Summary
WPF Resources, Animations, and Styles
Understanding the WPF Resource System
Working with Binary Resources
Including Loose Resource Files in a Project
Configuring the Loose Resources
Programmatically Loading an Image
Embedding Application Resources
Working with Object (Logical) Resources
The Role of the Resources Property
Defining Window-Wide Resources
The {StaticResource} Markup Extension
Changing a Resource after Extraction
The {DynamicResource} Markup Extension
Application-Level Resources
Defining Merged Resource Dictionaries
Defining a Resource-Only Assembly
Extracting Resources in Expression Blend
Understanding WPF’s Animation Services
The Role of the Animation Class Types
The To, From, and By Properties
The Role of the Timeline Base Class
Authoring an Animation in C# Code
Controlling the Pacing of an Animation
Reversing and Looping an Animation
Authoring Animations in XAML
The Role of Storyboards
The Role of Event Triggers
Animation Using Discrete Key Frames
Understanding the Role of WPF Styles
Defining and Applying a Style
Overriding Style Settings
Automatically Applying a Style with TargetType
Subclassing Existing Styles
The Role of Unnamed Styles
Defining Styles with Triggers
Defining Styles with Multiple Triggers
Animated Styles
Assigning Styles Programmatically
Generating Styles with Expression Blend
Working with Default Visual Styles
Summary
WPF Control Templates and UserControls
Understanding the Role of Dependency Properties
Examining an Existing Dependency Property
Important Notes Regarding CLR Property Wrappers
Building a Custom Dependency Property
Adding a Data Validation Routine
Responding to the Property Change
Understanding Routed Events
The Role of Routed Bubbling Events
Continuing or Halting Bubbling
The Role of Routed Tunneling Events
Logical Trees, Visual Trees and Default Templates
Programmatically Inspecting a Logical Tree
Programmatically Inspecting a Visual Tree
Programmatically Inspecting a Control’s Default Template
Building a Custom Control Template with Visual Studio 2010
Templates as Resources
Incorporating Visual Cues using Triggers
The Role of {TemplateBinding} Markup Extension
The Role of ContentPresenter
Incorporating Templates into Styles
Building Custom UserControls with Blend
Creating a UserControl Library Project
Renaming the Initial UserControl
Designing the SpinControl
Adding the Initial C# Code
Defining an Animation using Blend
Programmatically Starting our Storyboard
Creating the Jackpot Deluxe WPF Application
Extracting a UserControl from a Drawing Geometry
The Role of .NET 4.0 Visual States
Defining Visual States for the StarButton Control
Defining State Transition Timings
Viewing the Generated XAML
Changing Visual States in Code using the VisualStateManager Class
Finalizing the Jackpot Deluxe Application
Summary
Part 7: Building Web Applications with ASP.NET
Building ASP.NET Web Pages
The Role of HTTP
The HTTP Request/Response Cycle
HTTP Is a Stateless Protocol
Understanding Web Applications and Web Servers
The Role of IIS Virtual Directories
The ASP.NET Development Web Server
The Role of HTML
HTML Document Structure
The Role of an HTML Form
The Visual Studio 2010 HTML Designer Tools
Building an HTML Form
The Role of Client-Side Scripting
A Client-Side Scripting Example
Posting Back to the Web Server
Postbacks under ASP.NET
The Feature Set of the ASP.NET API
Major Features of ASP.NET 1.0-1.1
Major Features of ASP.NET 2.0
Major Features of ASP.NET 3.5 (and .NET 3.5 SP1)
Major Features of ASP.NET 4.0
Building a Single File ASP.NET Web Page
Referencing AutoLotDAL.dll
Designing the UI
Adding the Data Access Logic
The Role of ASP.NET Directives
Analyzing the “Script” Block
Analyzing the ASP.NET Control Declarations
Compilation Cycle for Single-File Pages
Building an ASP.NET Web Page using Code Files
Referencing the AutoLotDAL.dll Assembly
Updating the Code File
Compilation Cycle for Multifile Pages
Debugging and Tracing ASP.NET Pages
ASP.NET Web Sites and ASP.NET Web Applications
The ASP.NET Web Site Directory Structure
Referencing Assemblies
The Role of the App_Code Folder
The Inheritance Chain of the Page Type
Interacting with the Incoming HTTP Request
Obtaining Brower Statistics
Access to Incoming Form Data
The IsPostBack Property
Interacting with the Outgoing HTTP Response
Emitting HTML Content
Redirecting Users
The Life Cycle of an ASP.NET Web Page
The Role of the AutoEventWireup Attribute
The Error Event
The Role of the Web.config File
The ASP.NET Website Administration Utility
Summary
ASP.NET Web Controls, Master Pages and Themes
Understanding the Nature of Web Controls
Understanding Server-Side Event Handling
The AutoPostBack Property
The Control and WebControl Base Classes
Enumerating Contained Controls
Dynamically Adding and Removing Controls
Interacting with Dynamically Created Controls
Functionality of the WebControl Base Class
Major Categories of ASP.NET Web Controls
A Brief Word Regarding System.Web.UI.HtmlControls
Web Control Documentation
Building the ASP.NET Cars Web Site
Working with ASP.NET Master Pages
Working with the TreeView Control Site Navigation Logic
Establishing Bread Crumbs with the SiteMapPath Type
Working with the AdRotator
Defining the Default Content Page
Designing the Inventory Content Page
Enabling Sorting and Paging
Enabling In-Place Editing
Designing the Build-a-Car Content Page
The Role of the Validation Controls
The RequiredFieldValidator
The RegularExpressionValidator
The RangeValidator
The CompareValidator
Creating Validation Summaries
Defining Validation Groups
Working with Themes
Understanding *.skin Files
Applying Sitewide Themes
Applying Themes at the Page Level
The SkinID Property
Assigning Themes Programmatically
Summary
ASP.NET State Management Techniques
The Issue of State
ASP.NET State Management Techniques
Understanding the Role of ASP.NET View State
Demonstrating View State
Adding Custom View State Data
The Role of the Global.asax File
The Global Last-Chance Exception Event Handler
The HttpApplication Base Class
Understanding the Application/Session Distinction
Maintaining Application-Level State Data
Modifying Application Data
Handling Web Application Shutdown
Working with the Application Cache
Fun with Data Caching
Modifying the *.aspx File
Maintaining Session Data
Additional Members of HttpSessionState
Understanding Cookies
Creating Cookies
Reading Incoming Cookie Data
The Role of the Element
Storing Session Data in the ASP.NET Session State Server
Storing Session Data in a Dedicated Database
Understanding the ASP.NET Profile API
The ASPNETDB.mdf Database
Defining a User Profile Within Web.config
Accessing Profile Data Programmatically
Grouping Profile Data and Persisting Custom Objects
Summary
Programming with Windows Forms
The Windows Forms Namespaces
Building a Simple Windows Forms Application
Populating the Controls Collection
The Role of System.EventArgs and System.EventHandler
The Visual Studio Windows Forms Project Template
The Visual Designer Surface
Dissecting the Initial Form
Dissecting the Program Class
Visually Building a Menu System
The Anatomy of a Form
The Functionality of the Control Class
The Functionality of the Form Class
The Life Cycle of a Form Type
Responding to Mouse and Keyboard Activity
Determining Which Mouse Button Was Clicked
Determining Which Key Was Pressed
Designing Dialog Boxes
The DialogResult Property
Configuring the Tab Order
The Tab Order Wizard
Setting the Form’s Default Input Button
Displaying Dialog Boxes
Understanding Form Inheritance
Rendering Graphical Data Using GDI+
The System.Drawing Namespace
The Role of the Graphics Type
Obtaining a Graphics Object with the Paint Event
Invalidating the Form’s Client Area
Building a Complete Windows Forms Application
Building the Main Menu System
Defining the ShapeData Type
Defining the ShapePickerDialog Type
Adding Infrastructure to the MainWindow Type
Implementing the Tools Menu Functionality
Capturing and Rendering the Graphical Output
Implementing the Serialization Logic
Summary
Platform-Independent .NET Development with Mono
The Platform-Independent Nature of .NET
The Role of the CLI
The Mainstream CLI Distributions
The Scope of Mono
Obtaining and Installing Mono
Examining Mono’s Directory Structure
The Mono Development Languages
Working with the C# Compiler
Building Mono Applications using MonoDevelop
Microsoft-Compatible Mono Development Tools
Mono-Specific Development Tools
Using monop
Building .NET Applications with Mono
Building a Mono Code Library
Assigning CoreLibDumper.dll a Strong Name
Viewing the Updated Manifest with monodis
Installing Assemblies into the Mono GAC
Building a Console Application in Mono
Loading Your Client Application in the Mono Runtime
Building a Windows Forms Client Program
Executing Your Windows Forms Application Under Linux
Who is Using Mono?
Suggestions for Further Study
Summary
Index
¦SPECIAL CHARACTERS
AND NUMERICS
¦A
¦B
¦C
¦D
¦E
¦F
¦G
¦H
¦I
¦K
J
¦
¦L
¦M
¦N
¦O
¦P
¦Q
¦R
¦S
¦T
¦U
¦V
¦W
¦X
¦Y
Z
¦
  CYAN   MAGENTA   YELLOW   BLACK   PANTONE 123 C Andrew Troelsen, author of Pro VB 2008 and the .NET 3.5 Platform COM and .NET Interoperability Expert ASP.NET 2.0 Advanced Application Design Developer’s Workshop to COM and ATL 3.0 Companion eBook See last page for details on $10 eBook version SOURCE CODE ONLINE www.apress.com US $59.99 Shelve in: Programming | C# User level: Intermediate–Advanced BOOKS FOR PROFESSIONALS BY PROFESSIONALS® THE EXPERT’S VOICE® IN .NET Pro C# 2010 and the .NET 4 Platform, FIFTH EDITION Dear Reader, The C# language and the .NET platform have existed for quite some time and have become a mainstay of modern software development. As expected, .NET 4 brings a wealth of new APIs to the base class libraries and several new syntactical constructs to C#. For example, it is now possible to create C# methods that support optional and named arguments. As well, you are able to resolve types completely at runtime using the new dynamic keyword. As far as APIs are concerned, this edition of Pro C# 2010 and the .NET 4 Platform will cover a number of new details, including: • the Dynamic Language Runtime (DLR) • the Task Parallel Library (TPL, including PLINQ) • the ADO.NET Entity Framework (as well as LINQ to EF) • expanded coverage of the Windows Presentation Foundation (WPF) API • improved support for COM interop If you’re checking out this book for the first time, understand that it targets expe- rienced software professionals and students of computer science—so please don’t expect three chapters devoted to “variable scope” here! The mission of this text is to provide you with a rock-solid foundation in the C# programming language (including a full discussion of OOP) and the critical aspects of the .NET 4 platform. Once you digest the information presented in the book you hold in your hands, you’ll be in a perfect position to apply this knowledge to your specific program- ming assignments, and you’ll be well-equipped to explore the .NET universe on your own terms. Andrew Troelsen Microsoft MVP, Visual Developer—Visual C#; Microsoft Certified Trainer (MCT) THE APRESS ROADMAP Introducing .NET 4.0 Accelerated C# 2010 Pro C# 2010 and the .NET 4 Platform Pro ASP.NET 4 in C# 2010 Visual C# 2010 Recipes Pro Windows Azure Pro WPF in C# 2010 Pro Dynamic .NET 4.0 Applications ISBN 978-1-4302-2549-2 5 59 9 9 9 781430 225492 Companion eBook Available . Pro C N # E T 2 0 1 0 l 4 P a t f o r m t h e a n d FIFTH EDITION T r o e l s e n Pro C# 2010 and the .NET 4 Platform Exploring the .NET universe using curly brackets FIFTH EDITION Andrew Troelsen this print for content only—size & color not accurate 7.5 x 9.25 spine = 3.28125" 1752 page count 544ppi
Pro C# 2010 and the .NET 4 Platform Fifth Edition ■ ■ ■ Andrew Troelsen
Pro C# 2010 and the .NET 4 Platform, Fifth Edition Copyright © 2010 by Andrew Troelsen All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN-13 (pbk): 978-1-4302-2549-2 ISBN-13 (electronic): 978-1-4302-2550-8 Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1 Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. President and Publisher: Paul Manning Lead Editor: Ewan Buckingham Technical Reviewer: Andy Olsen Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes, Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh Coordinating Editor: Debra Kelly Copy Editors: Patrick Meader, Katie Stence, and Sharon Terdeman Compositor: folio 2 Indexer: Potomac Indexers Artist: April Milne Cover Designer: Anna Ishchenko Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. For information on translations, please e-mail rights@apress.com, or visit www.apress.com. Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/info/bulksales. The information in this book is distributed on an “as is” basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. The source code for this book is available to readers at www.apress.com.
To the memory of my wonderful grandmother, Maxine. I love you, Gerta. Rest peacefully.
Contents at a Glance Contents...................................................................................................................viii About the Author..................................................................................................... xxv About the Technical Reviewer ............................................................................... xxvi Acknowledgments ................................................................................................ xxvii Introduction ......................................................................................................... xxviii ■ ■ ■ Part 1: Introducing C# and the .NET Platform.................................................1 ■ Chapter 1: The Philosophy of .NET..........................................................................3 ■ Chapter 2: Building C# Applications .....................................................................41 ■ ■ ■ Part 2: Core C# Programming Constructs ....................................................71 ■ Chapter 3: Core C# Programming Constructs, Part I............................................73 ■ Chapter 4: Core C# Programming Constructs, Part II.........................................125 ■ Chapter 5: Defining Encapsulated Class Types...................................................167 ■ Chapter 6: Understanding Inheritance and Polymorphism.................................219 ■ Chapter 7: Understanding Structured Exception Handling .................................259 ■ Chapter 8: Understanding Object Lifetime..........................................................289 ■ ■ ■ Part 3: Advanced C# Programming Constructs ..........................................319 ■ Chapter 9: Working with Interfaces....................................................................321 ■ Chapter 10: Understanding Generics ..................................................................361 v
CONTENTS AT A GLANCE ■ Chapter 11: Delegates, Events, and Lambdas.....................................................397 ■ Chapter 12: Advanced C# Language Features ....................................................439 ■ Chapter 13: LINQ to Objects................................................................................489 ■ ■ ■ Part 4: Programming with .NET Assemblies...............................................523 ■ Chapter 14: Configuring .NET Assemblies ..........................................................525 ■ Chapter 15: Type Reflection, Late Binding, and Attribute-Based Programming......581 ■ Chapter 16: Processes, AppDomains, and Object Contexts................................625 ■ Chapter 17: Understanding CIL and the Role of Dynamic Assemblies................653 ■ Chapter 18: Dynamic Types and the Dynamic Language Runtime .....................701 ■ ■ ■ Part 5: Introducing the .NET Base Class Libraries......................................725 ■ Chapter 19: Multithreaded and Parallel Programming.......................................727 ■ Chapter 20: File I/O and Object Serialization......................................................775 ■ Chapter 21: ADO.NET Part I: The Connected Layer..............................................825 ■ Chapter 22: ADO.NET Part II: The Disconnected Layer........................................885 ■ Chapter 23: ADO.NET Part III: The Entity Framework .........................................951 ■ Chapter 24: Introducing LINQ to XML .................................................................993 ■ Chapter 25: Introducing Windows Communication Foundation .......................1013 ■ Chapter 26: Introducing Windows Workflow Foundation 4.0 ...........................1077 ■ ■ ■ Part 6: Building Desktop User Interfaces with WPF .................................1115 ■ Chapter 27: Introducing Windows Presentation Foundation and XAML ...........1117 ■ Chapter 28: Programming with WPF Controls..................................................1179 ■ Chapter 29: WPF Graphics Rendering Services ................................................1245 ■ Chapter 30: WPF Resources, Animations, and Styles.......................................1285 ■ Chapter 31: WPF Control Templates and UserControls.....................................1325 vi ■
分享到:
收藏