CONTENTS

INTRODUCTION xlix

PART I: THE C# LANGUAGE

CHAPTER 1: .NET ARCHITECTURE 3

The Relationship of C# to .NET 3 The 4 Platform Independence 4 Performance Improvement 4 Language Interoperability 5 A Closer Look at Intermediate Language 7 Support for Object Orientation and Interfaces 7 Distinct Value and Reference Types 8 Strong Data Typing 8 Error Handling with Exceptions 13 Use of Attributes 13 Assemblies 14 Private Assemblies 14 Shared Assemblies 15 Refl ection 15 Parallel Programming 15 Asynchronous Programming 16 .NET Framework Classes 16 Namespaces 17 Creating .NET Applications Using C# 17 Creating ASP.NET Applications 17 Windows Presentation Foundation (WPF) 19 Windows 8 AppsCOPYRIGHTED MATERIAL 20 Windows Services 20 Windows Communication Foundation 20 Windows Workfl ow Foundation 20 The Role of C# in the .NET Enterprise Architecture 21 Summary 21

fftoc.inddtoc.indd xxvv 003/10/123/10/12 44:01:01 PPMM CONTENTS

CHAPTER 2: CORE C# 23

Fundamental C# 24 Your First C# Program 24 The Code 24 Compiling and Running the Program 24 A Closer Look 25 Variables 27 Initialization of Variables 27 Type Inference 28 Variable Scope 29 Constants 31 Predefi ned Data Types 31 Value Types and Reference Types 31 CTS Types 33 Predefi ned Value Types 33 Predefi ned Reference Types 35 Flow Control 37 Conditional Statements 37 Loops 40 Jump Statements 43 Enumerations 43 Namespaces 45 The using Directive 46 Namespace Aliases 47 The Main() Method 47 Multiple Main() Methods 47 Passing Arguments to Main() 48 More on Compiling C# Files 49 Console I/O 50 Using Comments 52 Internal Comments within the Source Files 52 XML Documentation 52 The C# Preprocessor Directives 54 #defi ne and #undef 54 #if, #elif, #else, and #endif 55 #warning and #error 56 #region and #endregion 56 #line 56 #pragma 57 C# Programming Guidelines 57 Rules for Identifi ers 57

xvi

fftoc.inddtoc.indd xvixvi 003/10/123/10/12 4:014:01 PMPM CONTENTS

Usage Conventions 58 Summary 63

CHAPTER 3: OBJECTS AND TYPES 65

Creating and Using Classes 65 Classes and Structs 66 Classes 66 Data Members 67 Function Members 67 readonly Fields 78 Anonymous Types 79 Structs 80 Structs Are Value Types 81 Structs and Inheritance 82 Constructors for Structs 82 Weak References 82 Partial Classes 83 Static Classes 85 The Object Class 85 System.Object Methods 85 The ToString() Method 86 Extension Methods 87 Summary 88

CHAPTER 4: INHERITANCE 89

Inheritance 89 Types of Inheritance 89 Implementation Versus Interface Inheritance 90 Multiple Inheritance 90 Structs and Classes 90 Implementation Inheritance 90 Virtual Methods 91 Hiding Methods 92 Calling Base Versions of Functions 93 Abstract Classes and Functions 94 Sealed Classes and Methods 94 Constructors of Derived Classes 95 Modifi ers 99 Visibility Modifi ers 99 Other Modifi ers 100 Interfaces 100

xvii

fftoc.inddtoc.indd xviixvii 003/10/123/10/12 4:014:01 PMPM CONTENTS

Defi ning and Implementing Interfaces 101 Derived Interfaces 104 Summary 105

CHAPTER 5: GENERICS 107

Generics Overview 107 Performance 108 Type Safety 109 Binary Code Reuse 109 Code Bloat 110 Naming Guidelines 110 Creating Generic Classes 110 Generics Features 114 Default Values 114 Constraints 115 Inheritance 117 Static Members 118 Generic Interfaces 118 Covariance and Contra-variance 119 Covariance with Generic Interfaces 120 Contra-Variance with Generic Interfaces 121 Generic Structs 122 Generic Methods 124 Generic Methods Example 125 Generic Methods with Constraints 125 Generic Methods with Delegates 126 Generic Methods Specialization 127 Summary 128

CHAPTER 6: ARRAYS AND TUPLES 129

Multiple Objects of the Same and Diff erent Types 129 Simple Arrays 130 Array Declaration 130 Array Initializati on 130 Accessing Array Elements 131 Using Reference Types 131 Multidimensional Arrays 132 Jagged Arrays 133 Array Class 134 Creating Arrays 134

xviii

fftoc.inddtoc.indd xviiixviii 003/10/123/10/12 4:014:01 PMPM CONTENTS

Copying Arrays 136 Sorting 136 Arrays as Parameters 139 Array Covariance 139 ArraySegment 139 Enumerations 140 IEnumerator Interface 141 foreach Statement 141 yield Statement 141 Tuples 146 Structural Comparison 147 Summary 149

CHAPTER 7: OPERATORS AND CASTS 151

Operators and Casts 151 Operators 151 Operator Shortcuts 153 Operator Precedence 157 Type Safety 157 Type Conversions 158 Boxing and Unboxing 161 Comparing Objects for Equality 162 Comparing Reference Types for Equality 162 Comparing Value Types for Equality 163 Operator Overloading 163 How Operators Work 164 Operator Overloading Example: The Vector Struct 165 Which Operators Can You Overload? 171 User-Defi ned Casts 172 Implementing User-Defi ned Casts 173 Multiple Casting 178 Summary 181

CHAPTER 8: DELEGATES, LAMBDAS, AND EVENTS 183

Referencing Methods 183 Delegates 184 Declaring Delegates 185 Using Delegates 186 Simple Delegate Example 189 Action and Func Delegates 190 BubbleSorter Example 191

xix

fftoc.inddtoc.indd xixxix 003/10/123/10/12 4:014:01 PMPM CONTENTS

Multicast Delegates 193 Anonymous Methods 197 Lambda Expressions 198 Parameters 199 Multiple Code Lines 199 Closures 199 Closures with Foreach Statements 200 Events 201 Event Publisher 201 Event Listener 203 Weak Events 204 Summary 208

CHAPTER 9: STRINGS AND REGULAR EXPRESSIONS 209

Examining System.String 210 Building Strings 211 StringBuilder Members 214 Format Strings 215 Regular Expressions 221 Introduction to Regular Expressions 221 The RegularExpressionsPlayaround Example 222 Displaying Results 225 Matches, Groups, and Captures 226 Summary 228

CHAPTER 10: COLLECTIONS 229

Overview 229 Collection Interfaces and Types 230 Lists 231 Creating Lists 232 Read-Only Collections 241 Queues 241 Stacks 245 Linked Lists 247 Sorted List 251 Dictionaries 253 Key Type 254 Dictionary Example 255 Lookups 259 Sorted Dictionaries 260 Sets 260

xx

fftoc.inddtoc.indd xxxx 003/10/123/10/12 4:014:01 PMPM CONTENTS

Observable Collections 262 Bit Arrays 263 BitArray 263 BitVector32 266 Concurrent Collections 268 Creating Pipelines 269 Using BlockingCollection 272 Using ConcurrentDictionary 273 Completing the Pipeline 275 Performance 276 Summary 278

CHAPTER 11: LANGUAGE INTEGRATED QUERY 279

LINQ Overview 279 Lists and Entities 280 LINQ Query 283 Extension Methods 284 Deferred Query Execution 285 Standard Query Operators 287 Filtering 289 Filtering with Index 289 Type Filtering 290 Compound from 290 Sorting 291 Grouping 292 Grouping with Nested Objects 293 Inner Join 294 Left Outer Join 295 Group Join 296 Set Operations 299 Zip 300 Partitioning 301 Aggregate Operators 302 Conversion Operators 303 Generation Operators 304 Parallel LINQ 305 Parallel Queries 305 Partitioners 306 Cancellation 306 Expression Trees 307 LINQ Providers 310 Summary 310

xxi

fftoc.inddtoc.indd xxixxi 003/10/123/10/12 4:014:01 PMPM CONTENTS

CHAPTER 12: DYNAMIC LANGUAGE EXTENSIONS 313

Dynamic Language Runtime 313 The Dynamic Type 314 Dynamic Behind the Scenes 315 Hosting the DLR ScriptRuntime 318 DynamicObject and ExpandoObject 321 DynamicObject 321 ExpandoObject 322 Summary 324

CHAPTER 13: ASYNCHRONOUS PROGRAMMING 325

Why Asynchronous Programming Is Important 325 Asynchronous Patterns 326 Synchronous Call 333 Asynchronous Pattern 334 Event-Based Asynchronous Pattern 335 Task-Based Asynchronous Pattern 336 Foundation of Asynchronous Programming 338 Creating Tasks 338 Calling an Asynchronous Method 338 Continuation with Tasks 339 Synchronization Context 339 Using Multiple Asynchronous Methods 340 Converting the Asynchronous Pattern 341 Error Handling 341 Handling Exceptions with Asynchronous Methods 342 Exceptions with Multiple Asynchronous Methods 343 Using AggregateException Information 343 Cancellation 344 Starting a Cancellation 344 Cancellation with Framework Features 345 Cancellation with Custom Tasks 345 Summary 346

CHAPTER 14: MEMORY MANAGEMENT AND POINTERS 347

Memory Management 347 Memory Management Under the Hood 348 Value Data Types 348 Reference Data Types 349 Garbage Collection 351

xxii

fftoc.inddtoc.indd xxiixxii 003/10/123/10/12 4:014:01 PMPM CONTENTS

Freeing Unmanaged Resources 353 Destructors 353 The IDisposable Interface 354 Implementing IDisposable and a Destructor 356 Unsafe Code 357 Accessing Memory Directly with Pointers 357 Pointer Example: PointerPlayground 366 Using Pointers to Optimize Performance 370 Summary 374

CHAPTER 15: REFLECTION 375

Manipulating and Inspecting Code at Runtime 375 Custom Attributes 376 Writing Custom Attributes 376 Custom Attribute Example: WhatsNewAttributes 380 Using Refl ection 382 The System.Type Class 382 The TypeView Example 385 The Assembly Class 386 Completing the WhatsNewAttributes Example 388 Summary 391

CHAPTER 16: ERRORS AND EXCEPTIONS 393

Introduction 393 Exception Classes 394 Catching Exceptions 395 Implementing Multiple Catch Blocks 398 Catching Exceptions from Other Code 401 System.Exception Properties 401 What Happens If an Exception Isn’t Handled? 402 Nested try Blocks 402 User-Defi ned Exception Classes 404 Catching the User-Defi ned Exceptions 405 Throwing the User-Defi ned Exceptions 407 Defi ning the User-Defi ned Exception Classes 410 Caller Information 411 Summary 413

xxiii

fftoc.inddtoc.indd xxiiixxiii 003/10/123/10/12 4:014:01 PMPM CONTENTS

PART II: VISUAL STUDIO

CHAPTER 17: VISUAL STUDIO 2012 417

Working with Visual Studio 2012 417 Project File Changes 420 Visual Studio Editions 420 Visual Studio Settings 421 Creating a Project 421 Multi-Targeting the .NET Framework 422 Selecting a Project Type 423 Exploring and Coding a Project 426 Solution Explorer 426 Working with the Code Editor 432 Learning and Understanding Other Windows 433 Arranging Windows 437 Building a Project 437 Building, Compiling, and Making 437 Debugging and Release Builds 438 Selecting a Confi guration 440 Editing Confi gurations 440 Debugging Your Code 441 Setting Breakpoints 441 Using Data Tips and Debugger Visualizers 442 Monitoring and Changing Variables 444 Exceptions 444 Multithreading 445 IntelliTrace 446 Refactoring Tools 446 Architecture Tools 448 Dependency Graph 448 Layer Diagram 449 Analyzing Applications 450 Sequence Diagram 451 Profi ler 451 Concurrency Visualizer 453 Code Analysis 454 Code Metrics 455 Unit Tests 455

xxiv

fftoc.inddtoc.indd xxivxxiv 003/10/123/10/12 4:014:01 PMPM CONTENTS

Creating Unit Tests 456 Running Unit Tests 456 Expecting Exceptions 458 Testing All Code Paths 458 External Dependencies 459 Fakes Framework 461 Windows 8, WCF, WF, and More 463 Building WCF Applications with Visual Studio 2012 463 Building WF Applications with Visual Studio 2012 464 Building Windows 8 Apps with Visual Studio 2012 464 Summary 466

CHAPTER 18: DEPLOYMENT 467

Deployment as Part of the Application Life Cycle 467 Planning for Deployment 468 Overview of Deployment Options 468 Deployment Requirements 469 Deploying the .NET Runtime 469 Traditional Deployment 469 xcopy Deployment 470 xcopy and Web Applications 471 471 ClickOnce 471 ClickOnce Operation 472 Publishing a ClickOnce Application 472 ClickOnce Settings 474 Application Cache for ClickOnce Files 475 Application Installation 475 ClickOnce Deployment API 476 Web Deployment 477 Web Application 477 Confi guration Files 477 Creating a Web Deploy Package 478 Windows 8 Apps 479 Creating an App Package 480 Windows App Certifi cation Kit 481 Sideloading 482 Windows Deployment API 482 Summary 484

xxv

fftoc.inddtoc.indd xxvxxv 003/10/123/10/12 4:014:01 PMPM CONTENTS

PART III: FOUNDATION

CHAPTER 19: ASSEMBLIES 487

What are Assemblies? 487 Assembly Features 488 Assembly Structure 489 Assembly Manifests 489 Namespaces, Assemblies, and Components 490 Private and Shared Assemblies 490 Satellite Assemblies 490 Viewing Assemblies 491 Creating Assemblies 491 Creating Modules and Assemblies 491 Assembly Attributes 492 Creating and Loading Assemblies Dynamically 494 Application Domains 497 Shared Assemblies 501 Strong Names 501 Integrity Using Strong Names 502 502 Creating a Shared Assembly 503 Creating a Strong Name 503 Installing the Shared Assembly 504 Using the Shared Assembly 504 Delayed Signing of Assemblies 505 References 506 Native Image Generator 507 Confi guring .NET Applications 508 Confi guration Categories 509 Binding to Assemblies 510 Versioning 511 Version Numbers 511 Getting the Version Programmatically 512 Binding to Assembly Versions 512 Publisher Policy Files 513 Runtime Version 514 Sharing Assemblies Between Diff erent Technologies 515 Sharing Source Code 515 Portable Class Library 516 Summary 517

xxvi

fftoc.inddtoc.indd xxvixxvi 003/10/123/10/12 4:014:01 PMPM CONTENTS

CHAPTER 20: DIAGNOSTICS 519

Diagnostics Overview 519 Code Contracts 520 Preconditions 521 Postconditions 522 Invariants 523 Purity 524 Contracts for Interfaces 524 Abbreviations 525 Contracts and Legacy Code 526 Tracing 526 Trace Sources 527 Trace Switches 528 Trace Listeners 529 Filters 531 Correlation 532 Tracing with ETW 535 Event Logging 536 Event-Logging Architecture 537 Event-Logging Classes 538 Creating an Event Source 539 Writing Event Logs 540 Resource Files 540 Performance Monitoring 544 Performance-Monitoring Classes 544 Performance Counter Builder 544 Adding PerformanceCounter Components 547 perfmon.exe 549 Summary 550

CHAPTER 21: TASKS, THREADS, AND SYNCHRONIZATION 551

Overview 552 Parallel Class 553 Looping with the Parallel.For Method 553 Looping with the Parallel.ForEach Method 556 Invoking Multiple Methods with the Parallel.Invoke Method 557 Tasks 557 Starting Tasks 557 Futures—Results from Tasks 560

xxvii

fftoc.inddtoc.indd xxviixxvii 003/10/123/10/12 4:014:01 PMPM CONTENTS

Continuation Tasks 561 Task Hierarchies 561 Cancellation Framework 562 Cancellation of Parallel.For 562 Cancellation of Tasks 564 Thread Pools 565 The Thread Class 566 Passing Data to Threads 567 Background Threads 568 Thread Priority 569 Controlling Threads 570 Threading Issues 570 Race Conditions 570 Deadlocks 573 Synchronization 575 The lock Statement and Thread Safety 575 Interlocked 580 Monitor 581 SpinLock 582 WaitHandle 582 Mutex 583 Semaphore 584 Events 586 Barrier 589 ReaderWriterLockSlim 590 Timers 593 Data Flow 594 Using an Action Block 594 Source and Target Blocks 595 Connecting Blocks 596 Summary 598

CHAPTER 22: SECURITY 601

Introduction 601 Authentication and Authorization 602 Identity and Principal 602 Roles 603 Declarative Role-Based Security 604 Claims 605 Client Application Services 606

xxviii

fftoc.inddtoc.indd xxviiixxviii 003/10/123/10/12 4:014:01 PMPM CONTENTS

Encryption 610 Signature 612 Key Exchange and Secure Transfer 614 Access Control to Resources 617 619 Security Transparency Level 2 620 Permissions 620 Distributing Code Using Certifi cates 625 Summary 626

CHAPTER 23: INTEROP 627

.NET and COM 627 Metadata 628 Freeing Memory 629 Interfaces 629 Method Binding 630 Data Types 630 Registration 631 Threading 631 Error Handling 632 Events 633 Marshaling 633 Using a COM Component from a .NET Client 634 Creating a COM Component 634 Creating a Runtime Callable Wrapper 639 Using the RCW 640 Using the COM Server with Dynamic Language Extensions 642 Threading Issues 642 Adding Connection Points 643 Using a .NET Component from a COM Client 645 COM Callable Wrapper 645 Creating a .NET Component 646 Creating a Type Library 647 COM Interop Attributes 649 COM Registration 650 Creating a COM Client Application 651 Adding Connection Points 653 Creating a Client with a Sink Object 654 Platform Invoke 655 Summary 659

xxix

fftoc.inddtoc.indd xxixxxix 003/10/123/10/12 4:014:01 PMPM CONTENTS

CHAPTER 24: MANIPULATING FILES AND THE REGISTRY 661

File and the Registry 661 Managing the File System 662 .NET Classes That Represent Files and Folders 663 The Path Class 665 A FileProperties Sample 666 Moving, Copying, and Deleting Files 670 FilePropertiesAndMovement Sample 670 Looking at the Code for FilePropertiesAndMovement 671 Reading and Writing to Files 673 Reading a File 673 Writing to a File 675 Streams 676 Buff ered Streams 678 Reading and Writing to Binary Files Using FileStream 678 Reading and Writing to Text Files 682 Mapped Memory Files 688 Reading Drive Information 689 File Security 691 Reading ACLs from a File 691 Reading ACLs from a Directory 692 Adding and Removing ACLs from a File 694 Reading and Writing to the Registry 695 The Registry 695 The .NET Registry Classes 697 Reading and Writing to Isolated Storage 700 Summary 703

CHAPTER 25: TRANSACTIONS 705

Introduction 705 Overview 706 Transaction Phases 707 ACID Properties 707 Database and Entity Classes 708 Traditional Transactions 709 ADO.NET Transactions 710 System.EnterpriseServices 711 System.Transactions 712 Committable Transactions 713 Transaction Promotion 715 Dependent Transactions 717

xxx

fftoc.inddtoc.indd xxxxxx 003/10/123/10/12 4:014:01 PMPM CONTENTS

Ambient Transactions 719 Isolation Level 725 Custom Resource Managers 727 Transactional Resources 728 File System Transactions 733 Summary 736

CHAPTER 26: NETWORKING 737

Networking 737 The WebClient Class 738 Downloading Files 738 Basic WebClient Example 739 Uploading Files 740 WebRequest and WebResponse Classes 740 Authentication 742 Working with Proxies 742 Asynchronous Page Requests 743 Displaying Output As an HTML Page 743 Allowing Simple Web Browsing from Your Applications 744 Launching Internet Explorer Instances 745 Giving Your Application More IE-Type Features 746 Printing Using the WebBrowser Control 751 Displaying the Code of a Requested Page 751 The WebRequest and WebResponse Classes Hierarchy 753 Utility Classes 753 URIs 753 IP Addresses and DNS Names 754 Lower-Level Protocols 756 Using SmtpClient 757 Using the TCP Classes 758 The TcpSend and TcpReceive Examples 759 TCP versus UDP 761 The UDP Class 761 The Socket Class 762 WebSockets 765 Summary 768

CHAPTER 27: WINDOWS SERVICES 771

What Is a Windows Service? 771 Windows Services Architecture 773 Service Program 773

xxxi

fftoc.inddtoc.indd xxxixxxi 003/10/123/10/12 4:014:01 PMPM CONTENTS

Service Control Program 774 Service Confi guration Program 774 Classes for Windows Services 774 Creating a Windows Service Program 775 Creating Core Functionality for the Service 775 QuoteClient Example 779 Windows Service Program 782 Threading and Services 786 Service Installation 786 Installation Program 786 Monitoring and Controlling Windows Services 791 MMC Snap-in 791 net.exe Utility 792 sc.exe Utility 792 Visual Studio Server Explorer 792 Writing a Custom Service Controller 792 Troubleshooting and Event Logging 800 Summary 801

CHAPTER 28: LOCALIZATION? 803

Global Markets 803 Namespace System.Globalization 804 Unicode Issues 804 Cultures and Regions 805 Cultures in Action 809 Sorting 815 Resources 816 Creating Resource Files 816 Resource File Generator 816 ResourceWriter 817 Using Resource Files 818 The System.Resources Namespace 821 Localization Using Visual Studio 821 Changing the Culture Programmatically 825 Using Custom Resource Messages 827 Automatic Fallback for Resources 827 Outsourcing Translations 828 Localization with ASP.NET Web Forms 829 Localization with WPF 830 .NET Resources with WPF 831 XAML Resource Dictionaries 832

xxxii

fftoc.inddtoc.indd xxxiixxxii 003/10/123/10/12 4:014:01 PMPM CONTENTS

A Custom Resource Reader 835 Creating a DatabaseResourceReader 836 Creating a DatabaseResourceSet 837 Creating a DatabaseResourceManager 838 Client Application for DatabaseResourceReader 839 Creating Custom Cultures 839 Localization with Windows Store Apps 840 Using Resources 841 Localization with the Multilingual App Toolkit 842 Summary 843

CHAPTER 29: CORE XAML 845

Uses of XAML 845 XAML Foundation 846 How Elements Map to .NET Objects 846 Using Custom .NET Classes 847 Properties as Attributes 849 Properties as Elements 849 Essential .NET Types 849 Using Collections with XAML 850 Calling Constructors with XAML Code 850 Dependency Properties 851 Creating a Dependency Property 851 Coerce Value Callback 852 Value Changed Callbacks and Events 853 Bubbling and Tunneling Events 854 Attached Properties 857 Markup Extensions 859 Creating Custom Markup Extensions 859 XAML-Defi ned Markup Extensions 861 Reading and Writing XAML 861 Summary 862

CHAPTER 30: MANAGED EXTENSIBILITY FRAMEWORK 863

Introduction 863 MEF Architecture 864 MEF Using Attributes 865 Convention-Based Part Registration 870 Defi ning Contracts 871 Exporting Parts 873

xxxiii

fftoc.inddtoc.indd xxxiiixxxiii 003/10/123/10/12 4:014:01 PMPM CONTENTS

Creating Parts 873 Exporting Properties and Methods 877 Exporting Metadata 879 Using Metadata for Lazy Loading 881 Importing Parts 882 Importing Collections 883 Lazy Loading of Parts 885 Reading Metadata with Lazyily Instantiated Parts 886 Containers and Export Providers 887 Catalogs 890 Summary 891

CHAPTER 31: WINDOWS RUNTIME 893

Overview 893 Comparing .NET and Windows Runtime 894 Namespaces 894 Metadata 896 Language Projections 897 Windows Runtime Types 899 Windows Runtime Components 900 Collections 900 Streams 900 Delegates and Events 901 Async 902 Windows 8 Apps 903 The Life Cycle of Applications 905 Application Execution States 905 Suspension Manager 906 Navigation State 907 Testing Suspension 908 Page State 908 Application Settings 910 Webcam Capabilities 912 Summary 914

PART IV: DATA

CHAPTER 32: CORE ADO.NET 917

ADO.NET Overview 917 Namespaces 918 Shared Classes 919

xxxiv

fftoc.inddtoc.indd xxxivxxxiv 003/10/123/10/12 4:014:01 PMPM CONTENTS

Database-Specifi c Classes 919 Using Database Connections 920 Managing Connection Strings 921 Using Connections Effi ciently 922 Transactions 924 Commands 925 Executing Commands 926 Calling Stored Procedures 929 Fast Data Access: The Data Reader 932 Asynchronous Data Access: Using Task and Await 934 Managing Data and Relationships: The DataSet Class 936 Data Tables 936 Data Relationships 942 Data Constraints 943 XML Schemas: Generating Code with XSD 946 Populating a DataSet 951 Populating a DataSet Class with a Data Adapter 951 Populating a DataSet from XML 952 Persisting DataSet Changes 953 Updating with Data Adapters 953 Writing XML Output 955 Working with ADO.NET 956 Tiered Development 957 Key Generation with SQL Server 958 Naming Conventions 960 Summary 961

CHAPTER 33: ADO.NET 963

Programming with the Entity Framework 963 Entity Framework Mapping 965 Logical Layer 965 Conceptual Layer 967 Mapping Layer 968 Connection String 969 Entities 970 Object Context 973 Relationships 975 Table per Hierarchy 975 Table per Type 977 Lazy, Delayed, and Eager Loading 978 Querying Data 979 Entity SQL 979

xxxv

fftoc.inddtoc.indd xxxvxxxv 003/10/123/10/12 4:014:01 PMPM CONTENTS

Object Query 981 LINQ to Entities 983 Writing Data to the Database 984 Object Tracking 984 Change Information 985 Attaching and Detaching Entities 987 Storing Entity Changes 987 Using POCO Objects 988 Defi ning Entity Types 988 Creating the Data Context 989 Queries and Updates 990 Using the Code First Programming Model 990 Defi ning Entity Types 990 Creating the Data Context 991 Creating the Database and Storing Entities 991 The Database 992 Query Data 992 Customizing Database Generation 993 Summary 994

CHAPTER 34: MANIPULATING XML 995

XML 995 XML Standards Support in .NET 996 Introducing the System.Xml Namespace 996 Using System.Xml Classes 997 Reading and Writing Streamed XML 998 Using the XmlReader Class 998 Validating with XmlReader 1002 Using the XmlWriter Class 1003 Using the DOM in .NET 1005 Using the XmlDocument Class 1006 Using XPathNavigators 1009 The System.Xml.XPath Namespace 1009 The System.Xml.Xsl Namespace 1013 XML and ADO.NET 1018 Converting ADO.NET Data to XML 1019 Converting XML to ADO.NET Data 1024 Serializing Objects in XML 1025 Serialization without Source Code Access 1031 LINQ to XML and .NET 1034 Working with Diff erent XML Objects 1034

xxxvi

fftoc.inddtoc.indd xxxvixxxvi 003/10/123/10/12 4:014:01 PMPM CONTENTS

XDocument 1034 XElement 1035 XNamespace 1036 XComment 1038 XAttribute 1039 Using LINQ to Query XML Documents 1040 Querying Static XML Documents 1040 Querying Dynamic XML Documents 1041 More Query Techniques for XML Documents 1043 Reading from an XML Document 1043 Writing to an XML Document 1044 Summary 1046

PART V: PRESENTATION

CHAPTER 35: CORE WPF 1049

Understanding WPF 1050 Namespaces 1050 Class Hierarchy 1051 Shapes 1053 Geometry 1054 Transformation 1056 Brushes 1058 SolidColorBrush 1058 LinearGradientBrush 1058 RadialGradientBrush 1059 DrawingBrush 1059 ImageBrush 1060 VisualBrush 1060 Controls 1061 Simple Controls 1061 Content Controls 1062 Headered Content Controls 1063 Items Controls 1064 Headered Items Controls 1065 Decoration 1065 Layout 1066 StackPanel 1066 WrapPanel 1067 Canvas 1067 DockPanel 1067

xxxvii

fftoc.inddtoc.indd xxxviixxxvii 003/10/123/10/12 4:014:01 PMPM CONTENTS

Grid 1068 Styles and Resources 1069 Styles 1070 Resources 1071 System Resources 1072 Accessing Resources from Code 1072 Dynamic Resources 1073 Resource Dictionaries 1074 Triggers 1075 Property Triggers 1075 MultiTrigger 1077 Data Triggers 1077 Templates 1078 Control Templates 1079 Data Templates 1082 Styling a ListBox 1083 ItemTemplate 1084 Control Templates for ListBox Elements 1085 Animations 1087 Timeline 1087 Nonlinear Animations 1090 Event Triggers 1090 Keyframe Animations 1092 Visual State Manager 1093 Visual States 1094 Transitions 1095 3-D 1096 Model 1097 Cameras 1098 Lights 1098 Rotation 1099 Summary 1100

CHAPTER 36: BUSINESS APPLICATIONS WITH WPF 1101

Introduction 1101 Menu and Ribbon Controls 1102 Menu Controls 1102 Ribbon Controls 1103 Commanding 1105 Defi ning Commands 1106 Defi ning Command Sources 1106 Command Bindings 1107

xxxviii

fftoc.inddtoc.indd xxxviiixxxviii 003/10/123/10/12 4:014:01 PMPM CONTENTS

Data Binding 1107 BooksDemo Application Content 1108 Binding with XAML 1109 Simple Object Binding 1112 Change Notifi cation 1113 Object Data Provider 1116 List Binding 1118 Master Details Binding 1120 MultiBinding 1120 Priority Binding 1122 Value Conversion 1123 Adding List Items Dynamically 1125 Adding Tab Items Dynamically 1126 Data Template Selector 1127 Binding to XML 1129 Binding Validation and Error Handling 1130 TreeView 1137 DataGrid 1141 Custom Columns 1143 Row Details 1144 Grouping with the DataGrid 1144 Live Shaping 1146 Summary 1152

CHAPTER 37: CREATING DOCUMENTS WITH WPF 1153

Introduction 1153 Text Elements 1154 Fonts 1154 TextEff ect 1155 Inline 1156 Block 1158 Lists 1159 Tables 1160 Anchor to Blocks 1161 Flow Documents 1162 Fixed Documents 1166 XPS Documents 1169 Printing 1171 Printing with the PrintDialog 1171 Printing Visuals 1172 Summary 1173

xxxix

fftoc.inddtoc.indd xxxixxxxix 003/10/123/10/12 4:014:01 PMPM CONTENTS

CHAPTER 38: WINDOWS STORE APPS 1175

Overview 1175 Windows 8 Modern UI Design 1176 Content, Not Chrome 1176 Fast and Fluid 1177 Readability 1178 Sample Application Core Functionality 1178 Files and Directories 1179 Application Data 1180 Application Pages 1184 App Bars 1189 Launching and Navigation 1190 Layout Changes 1193 Storage 1196 Defi ning a Data Contract 1196 Writing Roaming Data 1198 Reading Data 1199 Writing Images 1200 Reading Images 1202 Pickers 1203 Sharing Contract 1204 Sharing Source 1204 Sharing Target 1206 Tiles 1209 Summary 1210

CHAPTER 39: CORE ASP.NET 1211

.NET Frameworks for Web Applications 1211 ASP.NET Web Forms 1212 ASP.NET Web Pages 1212 ASP.NET MVC 1213 Web Technologies 1213 HTML 1213 CSS 1213 JavaScript and jQuery 1214 Hosting and Confi guration 1214 Handlers and Modules 1217 Creating a Custom Handler 1218 ASP.NET Handlers 1219

xl

fftoc.inddtoc.indd xlxl 003/10/123/10/12 4:014:01 PMPM CONTENTS

Creating a Custom Module 1219 Common Modules 1221 Global Application Class 1222 Request and Response 1222 Using the HttpRequest Object 1223 Using the HttpResponse Object 1224 State Management 1224 View State 1225 Cookies 1225 Session 1226 Application 1229 Cache 1229 Profi les 1230 Membership and Roles 1234 Confi guring Membership 1234 Using the Membership API 1236 Enabling the Roles API 1237 Summary 1237

CHAPTER 40: ASP.NET WEB FORMS 1239

Overview 1239 ASPX Page Model 1240 Adding Controls 1241 Using Events 1241 Working with Postbacks 1242 Using Auto-Postbacks 1243 Doing Postbacks to Other Pages 1243 Defi ning Strongly Typed Cross-Page Postbacks 1244 Using Page Events 1244 ASPX Code 1246 Server-Side Controls 1248 Master Pages 1249 Creating a Master Page 1249 Using Master Pages 1251 Defi ning Master Page Content from Content Pages 1252 Navigation 1253 Site Map 1253 Menu Control 1254 Menu Path 1254

xli

fftoc.inddtoc.indd xlixli 003/10/123/10/12 4:014:01 PMPM CONTENTS

Validating User Input 1254 Using Validation Controls 1254 Using a Validation Summary 1255 Validation Groups 1256 Accessing Data 1256 Using the Entity Framework 1257 Using the Entity Data Source 1257 Sorting and Editing 1260 Customizing Columns 1260 Using Templates with the Grid 1261 Customizing Object Context Creation 1263 Object Data Source 1264 Security 1265 Enabling Forms Authentication 1266 Login Controls 1266 Ajax 1267 What Is ASP.NET AJAX? 1268 ASP.NET AJAX Website Example 1271 ASP.NET AJAX-Enabled Website Confi guration 1274 Adding ASP.NET AJAX Functionality 1275 Summary 1281

CHAPTER 41: ASP.NET MVC 1283

ASP.NET MVC Overview 1283 Defi ning Routes 1285 Adding Routes 1286 Route Constraints 1286 Creating Controllers 1287 Action Methods 1287 Parameters 1287 Returning Data 1288 Creating Views 1290 Passing Data to Views 1290 Razor Syntax 1291 Strongly Typed Views 1292 Layout 1293 Partial Views 1295 Submitting Data from the Client 1298 Model Binder 1299 Annotations and Validation 1300 HTML Helpers 1301

xlii

fftoc.inddtoc.indd xliixlii 003/10/123/10/12 4:014:01 PMPM CONTENTS

Simple Helpers 1301 Using Model Data 1302 Defi ne HTML Attributes 1303 Create Lists 1303 Strongly Typed Helpers 1304 Editor Extensions 1305 Creating Custom Helpers 1305 Templates 1305 Creating a Data-Driven Application 1306 Defi ning a Model 1306 Creating Controllers and Views 1307 Action Filters 1312 Authentication and Authorization 1313 Model for Login 1313 Controller for Login 1313 Login View 1315 ASP.NET Web API 1316 Data Access Using Entity Framework Code-First 1316 Defi ning Routes for ASP.NET Web API 1317 Controller Implementation 1317 Client Application Using jQuery 1319 Summary 1320

CHAPTER 42: ASP.NET DYNAMIC DATA 1321

Overview 1321 Creating Dynamic Data Web Applications 1322 Confi guring Scaff olding 1323 Exploring the Result 1323 Customizing Dynamic Data Websites 1326 Controlling Scaff olding 1326 Customizing Templates 1327 Confi guring Routing 1332 Summary 1334

PART VI: COMMUNICATION

CHAPTER 43: WINDOWS COMMUNICATION FOUNDATION 1337

WCF Overview 1337 SOAP 1339 WSDL 1339

xliii

fftoc.inddtoc.indd xliiixliii 003/10/123/10/12 4:014:01 PMPM CONTENTS

REST 1340 JSON 1340 Creating a Simple Service and Client 1340 Defi ning Service and Data Contracts 1341 Data Access 1343 Service Implementation 1344 WCF Service Host and WCF Test Client 1345 Custom Service Host 1346 WCF Client 1348 Diagnostics 1349 Sharing Contract Assemblies with the Client 1351 Contracts 1352 Data Contract 1353 Versioning 1353 Service and Operation Contracts 1354 Message Contract 1355 Fault Contract 1355 Service Behaviors 1356 Binding 1360 Standard Bindings 1360 Features of Standard Bindings 1362 Web Socket 1363 Hosting 1366 Custom Hosting 1366 WAS Hosting 1367 Preconfi gured Host Classes 1367 Clients 1368 Using Metadata 1368 Sharing Types 1369 Duplex Communication 1370 Contract for Duplex Communication 1370 Service for Duplex Communication 1371 Client Application for Duplex Communication 1372 Routing 1372 Sample Application 1373 Routing Interfaces 1374 WCF Routing Service 1374 Using a Router for Failover 1375 Bridging for Protocol Changes 1376 Filter Types 1377 Summary 1377

xliv

fftoc.inddtoc.indd xlivxliv 003/10/123/10/12 4:014:01 PMPM CONTENTS

CHAPTER 44: WCF DATA SERVICES 1379

Overview 1379 Custom Hosting with CLR Objects 1380 CLR Objects 1381 Data Model 1382 Data Service 1383 Hosting the Service 1383 Additional Service Operations 1385 HTTP Client Application 1385 Queries with URLs 1388 Using WCF Data Services with the ADO.NET Entity Framework 1390 ASP.NET Hosting and EDM 1390 Using the WCF Data Service Client Library 1391 Summary 1398

CHAPTER 45: WINDOWS WORKFLOW FOUNDATION 1399

A Workfl ow Overview 1399 Hello World 1400 Activities 1401 If Activity 1402 InvokeMethod Activity 1403 Parallel Activity 1403 Delay Activity 1404 Pick Activity 1404 Custom Activities 1405 Activity Validation 1406 Designers 1406 Custom Composite Activities 1408 Workfl ows 1411 Arguments and Variables 1411 Workfl owApplication 1412 Hosting WCF Workfl ows 1416 Workfl ow Versioning 1419 Hosting the Designer 1420 Summary 1424

CHAPTER 46: PEER-TO-PEER NETWORKING 1425

Peer-to-Peer Networking Overview 1425 Client-Server Architecture 1426 P2P Architecture 1426

xlv

fftoc.inddtoc.indd xlvxlv 003/10/123/10/12 4:014:01 PMPM CONTENTS

P2P Architectural Challenges 1427 P2P Terminology 1428 P2P Solutions 1428 Peer Name Resolution Protocol (PNRP) 1429 PNRP IDs 1429 PNRP Clouds 1430 PNRP Since Windows 7 1431 Building P2P Applications 1431 Registering Peer Names 1432 Resolving Peer Names 1433 Code Access Security in System.Net.PeerToPeer 1434 Sample Application 1434 Summary 1437

CHAPTER 47: MESSAGE QUEUING 1439

Overview 1440 When to Use Message Queuing 1441 Message Queuing Features 1442 Message Queuing Products 1442 Message Queuing Architecture 1443 Messages 1443 Message Queue 1443 Message Queuing Administrative Tools 1444 Creating Message Queues 1444 Message Queue Properties 1444 Programming Message Queuing 1445 Creating a Message Queue 1445 Finding a Queue 1446 Opening Known Queues 1447 Sending a Message 1448 Receiving Messages 1450 Course Order Application 1452 Course Order Class Library 1452 Course Order Message Sender 1454 Sending Priority and Recoverable Messages 1456 Course Order Message Receiver 1457 Receiving Results 1462 Acknowledgment Queues 1462 Response Queues 1463 Transactional Queues 1463 Message Queuing with WCF 1464

xlvi

fftoc.inddtoc.indd xlvixlvi 003/10/123/10/12 4:014:01 PMPM CONTENTS

Entity Classes with a Data Contract 1465 WCF Service Contract 1466 WCF Message Receiver Application 1466 WCF Message Sender Application 1469 Message Queue Installation 1470 Summary 1471

INDEX 1473

xlvii

fftoc.inddtoc.indd xlviixlvii 003/10/123/10/12 4:014:01 PMPM