Visual C#® 2012 Programming
Karli Watson
Jacob Vibe Hammer John
D.Reid Morgan Skinner
Daniel Kemper
Christian Nagel
WILEY
John Wiley & Sons, Inc.
INTRODUCTION xxxi
CHAPTER1: INTRODUCING C# 3
What Is the .NET Framework? 3
What's in the .NET Framework? 4
Writing Applications Using
the .NET Framework 4CILandJIT 4
Assemblies 5
Managed
Code 5Garbage
Collection 6Fitting It
Together
6Linking
7What Is C#? 7
Applications
You Can Write with C# 8C# in this Book 8
Visual Studio 2012 8
Visual Studio
Express
2012 Products 9Solutions 9
Summary
10CHAPTER 2: WRITINGAC# PROGRAM 13
The Visual Studio 2012
Development
Environment 14Console
Applications
16The Solution
Explorer
18The
Properties
Window 19The Error List Window 19
Desktop Applications
20Summary
23CHAPTER3: VARIABLES ANDEXPRESSIONS 25
Basic
C# Syntax
26Basic
C#
ConsoleApplication
Structure 28Variables 29
Simple
Types 29CONTENTS
Variable
Naming
33Naming Conventions 34
LiteralValues 34
Variable Declaration and Assignment 36
Expressions
37Mathematical
Operators
37Assignment Operators
41Operator
Precedence 42Namespaces
42Summary
45CHAPTER 4: FLOW CONTROL 49
Boolean
Logic
49Boolean Assignment Operators 52
BitwiseOperators 53
Operator
PrecedenceUpdated
57The
goto
Statement 58Branching
59The
Ternary
Operator 59The if Statement 59
Checking
More ConditionsUsing
if Statements 62The switch Statement 63
Looping
65do
Loops
66while
Loops
68for
Loops
70Interrupting Loops
74Infinite
Loops
75Summary
75CHAPTER 5: MORE ABOUT VARIABLES 79
Type
Conversion 80Implicit
Conversions 80Explicit
Conversions 81Explicit
ConversionsUsing
the Convert Commands 84Complex
VariableTypes
86Enumerations 87
Defining Enumerations 87
Structs 90
Defining
Structs 90Arrays
92Declaring Arrays
93foreach
Loops
95Multidimensional
Arrays
96Arrays
ofArrays 97String Manipulation
98Summary
102CHAPTER 6: FUNCTIONS 105
Defining
andUsing Functions
106Return Values 108
Parameters 109
Parameter
Matching
111Parameter
Arrays
111Reference and Value Parameters 113
Out Parameters 115
Variable
Scope
116Variable
Scope
in Other Structures 118Parameters and Return ValuesversusGlobal Data 120
The
Main()
Function 121Struct Functions 123
Overloading
Functions 124Using Delegates
125Summary
128CHAPTER 7: DEBUGGING AND ERROR HANDLING 131
Debugging
in Visual Studio 132Debugging
in Nonbreak(Normal)
Mode 132Outputting Debugging
Information 133Tracepoints
137Diagnostics Output
VersusTracepoints
139Debugging
in Break Mode 140Entering
Break Mode 140Monitoring
Variable Content 142Stepping ThroughCode 144
Immediate and CommandWindows 146
The Call Stack Window 146
Error
Handling
147try...catch...finally
147Listing
andConfiguring Exceptions
152XVI
CONTENTS
Noteson
Exception Handling
152Summary
153CHAPTER 8: INTRODUCTION TO OBJECT-ORIENTED
PROGRAMMING 157
What Is
Object-Oriented Programming?
158What Isan
Object?
158Properties
and Fields 159Methods 160
Everything's
anObject
161The Life
Cycle
ofanObject
161Constructors 161
Destructors 162
Staticand Instance Class Members 162
Static Constructors 162
Static Classes 163
OOP
Techniques
163Interfaces 163
Disposable Objects
164Inheritance 165
Polymorphism
167Interface
Polymorphism
168Relationships
BetweenObjects
168Containment 168
Collections 169
Operator Overloading
169Events 170
Reference
Types
Versus ValueTypes
170OOP in
Desktop Applications
171Summary
174CHAPTER 9: DEFINING CLASSES 177
Class Definitions in C# 177
Interface Definitions 180
System.Object
182Constructors and Destructors 184
Constructor Execution
Sequence
185OOP Tools in Visual Studio 188
TheClass View Window 188
The
Object
Browser 190Adding
Classes 191Hi
Class
Diagrams
192Class
Library Projects
193Interfaces Versus Abstract Classes
196
Struct
Types
198Shallow
Copying
VersusDeep Copying
200Summary
200CHAPTER 10: DEFINING CLASS MEMBERS 203
Member Definitions 203
Defining
Fields 204Defining Methods 204
Defining Properties
205Adding
Members from aClassDiagram
210Adding
Methods 210Adding Properties
212Adding
Fields 212Refactoring
Members 212Automatic
Properties
213Additional Class Member
Topics
213Hiding
Base Class Methods 213Calling OverriddenorHidden BaseClass Methods 215
The this
Keyword
216Using
NestedType
Definitions 216Interface
Implementation
218Implementing
Interfaces in Classes 219Explicit
Interface MemberImplementation
220Additional
Property
Accessors 220Partial Class Definitions 221
Partial Method Definitions 222
Example Application
224Planning
theApplication
224The Card Class 224
The Deck Class 224
Writing
the ClassLibrary
224Adding
the Suit and Rank Enumerations 225Adding
the Card Class 226Adding
the Deck Class 227A Client
Application
for the Class Library 230The Call
Hierarchy
Window 231Summary
232xia
CHAPTER
11:COLLECTIONS, COMPARISONS,
AND CONVERSIONS 235
Collections
236Using Collections 236
Defining
Collections 241Indexers 242
Adding aCardsCollectionto CardLib 244
Keyed
Collections andDictionary
247Iterators 248
Iterators and Collections 252
Deep
Copying
253Adding
Deep Copying
toCardLib 255Comparisons
256Type Comparisons
256Boxing
andUnboxing
257The is Operator 258
ValueComparisons 260
Operator
Overloading 261Adding
Operator Overloads to CardLib 265TheIComparable and
IComparer
Interfaces 269Sorting
Collections 271Conversions
274Overloading
Conversion Operators 274The as
Operator
275Summary
276CHAPTER 12: GENERICS 279
What AreGenerics? 280
Using
Generics 281Nullable Types 281
Operators and Nullable
Types
282The??
Operator
283The
System.Collections.Generic Namespace
287List<T> 287
Sortingand Searching Generic Lists 289
Dictionary<K,
V> 294Modifying
CardLib to Usea GenericCollection Class 295Defining
GenericTypes
296Defining
GenericClasses 296The default
Keyword
298Constraining Types
298Inheriting
from Generic Classes 304Generic
Operators
305Generic Structs 306
Defining
Generic Interfaces 306Defining
Generic Methods 306Defining
GenericDelegates
308Variance 308
Covariance 309
Contravariance 310
Summary
310CHAPTER 13: ADDITIONAL OOP TECHNIQUES 313
The::
Operator
and the GlobalNamespace
Qualifier 313Custom
Exceptions
315Adding
CustomExceptions
to CardLib 315Events 316
What Isan Event? 316
Handling
Events 317Defining
Events 319Multipurpose
Event Handlers 323The EventHandler and Generic EventHandler<T>
Types
325Return Values and Event Handlers 326
Anonymous
Methods 326Expanding
andUsing
CardLib 327A Card Game Client forCardLib 327
Attributes
334Reading
Attributes 334Creating
Attributes 335Summary
336CHAPTER 14: C# LANGUAGE ENHANCEMENTS 339
Initializers 340
Object
Initializers 340Collection Initializers 342
Type
Inference 344Anonymous Types
346Dynamic Lookup
350The
dynamic Type
350IDynamicMetaObjectProvider
354XXi
CONTENTS
Advanced
Method
Parameters 354Optional
Parameters 354Optional ParameterValues 355
TheOptionalAttribute Attribute 356
Optional
Parameter Order 356Named Parameters 356
Named andOptional Parameter Guidelines 360
Extension Methods 360
Lambda
Expressions
364Anonymous
MethodsRecap
364Lambda
Expressions
forAnonymous Methods 365Lambda
Expression
Parameters 368Lambda
Expression
StatementBodies 368Lambda Expressionsas
Delegates
andExpression
Trees 369Lambda
Expressions
and Collections 370Caller Information Attributes 372
Summary
375PART II: WINDOWS PROGRAMMING
CHAPTER 15: BASIC DESKTOP PROGRAMMING 381
XAML 382
Separation
of Concerns 382XAML in Action 383
Namespaces
383Code-Behind Files 384
The
Playground
384WPF Controls 385
Properties
386Dependency Properties 387
Attached
Properties
388Events 388
Handling
Events 389Routed Events 390
Routed Commands 390
Control
Types
392Control
Layout
393StackOrder 393
Alignment, Margins, Padding,
and Dimensions 393Border 394
Canvas 394
ii
DockPanel 395
StackPanel 397
WrapPanel
398Grid 398
The Game Client 401
The About Window 401
Designing
the User Interface 401The
Image
Control 401The Label Control 402
The TextBlock Control 402
The Button Control 402
The
Options
Window 405TheTextBox Control 406
TheCheckBox Control 406
The RadioButton Control 407
The ComboBox Control 408
The TabControl 409
Handling
Events in theOptions
Window 411Data
Binding
413The DataContext 414
Binding
to LocalObjects
414Static
Binding
to ExternalObjects
414Dynamic Binding
to ExternalObjects
415StartingaGame 418
TheListBox Control 418
Summary
421CHAPTER 16: ADVANCED DESKTOP PROGRAMMING 425
The Main Window 425
The Menu Control 426
Routed Commands with Menus 426
Creating
andStyling
Controls 429Styles
430Templates
430Value Converters 434
The IValueConverter Interface 434
ValueConversionAttribute 434
Triggers 435
Animations 436
Timelineswithout
Key
Frames 436Timelineswith
Key
Frames 437XXM
WPF User Controls 438
Implementing
DependencyProperties
439Putting
It AllTogether
447Refactoring
the Domain Model 447The View Models 451
Completing
the Game 459Summary
466CHAPTER 17: WINDOWS STORE APPS 469
Getting
Started 469Windows 8Developer License 470
How to Get the License 470
Windows Store
Apps
versusDesktop Applications
471Developing
Windows StoreApps
472View Modes 472
Full-Screen Mode 473
Snapped
Mode 473Fill Mode 473
Screen Orientation 473
The
Missing Caption
Bar 473Menus and Toolbars 473
TheAppBar 474
Charms 475
Tiles andBadges 476
App
Lifetime 476Lock Screen
Apps
476App Development
476WPF and Windows Store
App
XAML Differences 476Namespace Changes
477Effects 477
Opacity
Mask 477Style Triggers
477Commands 478
Templates
andPages
478Blank
Page
478Basic
Page
478Grouped
Items and GroupDetailsPages
478ItemDetails
Page
479Items andSplit
Pages
479SandboxedApps
479Disk Access 479
Serialization,
Streams, andAsync Programming
480Navigation
BetweenPages
483Managing
State 485Converting KarliCards,
Part 1 485Creating
the CardLib Project 486Convertingthe View Models 489
Visual
Changes
493Drop
Shadow andOpacity
Masks 493Style Triggers
493Converting
User Controls 493Common Elements of Windows Store
Apps
499The
AppBar
Control 500The
Settings
Panel 501Tiles, Badges,
andSplash
Screens 503Converting KarliCards,
Part 2 504The Windows Store 509
Checkingthe Store Requirements 509
Summary
510CHAPTER 18: DEPLOYING DESKTOP APPLICATIONS 513
Deployment
Overview 514ClickOnce Deployment
514Implementing
ClickOnceDeployment
515Installing
theApplication
withClickOnce 522Creating
andUsing Updates
of theApplication
524InstallShield
Limited
Edition 524The
Project
Assistant 524Step 1:
Application
Information 525Step
2: InstallationRequirements 525Step
3: Installation Architecture 526Step
4:Application
Files 526Step
5:Application
Shortcuts 527Step
6:Application Registry
528Step
7: Installation Interview 528Summary
530CHAPTER 19: ASP.NET WEB PROGRAMMING 535
Overviewof Web
Applications
536ASP.NET Runtime 536
Creating
aSimple Page
536XXV
CONTENTS
Server Controls 544
ASP.NET
Postback
545ASP.NET AJAX Postback 550
Input Validation
553State
Management 557
Client-Side State
Management
558ViewState 558
Cookie 559
Server-SideState
Management
560Session 560
Application
561Cache 562
Styles
562Master
Pages 566
Site
Navigation 571
Authentication and
Authorization
573Authentication
Configuration
574Using Security
Controls 577Reading from
andWriting
toa SQL Server Database 580Summary
589CHAPTER 20: DEPLOYING WEB APPLICATIONS 591
Internet
InformationServices
591IIS
Configuration
592Copying
a Website594
Publishing
a WebApplication 597
Summary 600
PART IV: DATA
ACCESS
CHAPTER 21: FILE SYSTEM DATA 605
Streams 605
The Classes for
Input
andOutput
606The File and
Directory
Classes 607The Filelnfo Class 608
The
Directorylnfo
Class 610Path Names and Relative Paths 611
The FileStream
Object
611FilePosition 612
Reading
Data 613Writing
Data 615The StreamWriter
Object
617The StreamReader
Object
618Reading
Data 620Delimited Files 621
Asynchronous
File Access 625Reading
andWriting Compressed
Files 625Serialized
Objects
628Monitoring
the FileSystem
632Summary 636
CHAPTER 22: XML 639
XML Documents 640
XML Elements 640
Attributes 641
The XML Declaration 641
The Structure ofan XML Document 642
XML
Namespaces
642Well-Formed and Valid XML 643
Validating
XML Documents 644Schemas 644
The XSD
dialog
box shown in the XmlDocumentClass 645Using
XML in YourApplication
647XML Document
Object
Model 647The XmlDocument Class 648
The XmlElement Class 648
Changing
the Values of Nodes 652Selecting
Nodes 656XPath 657
Summary
661CHAPTER 23: INTRODUCTION TO LINQ 663
First LINQ
Query
664Declaring
aVariable forResultsUsing
thevarKeyword
665Specifying
the Data Source: from Clause 666Specify
Condition: whereClause 666Selecting
Items: selectClause 666Finishing Up: Using
the foreachLoop
667Deferred
Query
Execution 667Using
the LINQ MethodSyntax
667LINQ Extension Methods 667
Query Syntax
versusMethodSyntax
668xxvti
CONTENTS
Ordering Query
Results 669Understanding
theorderby
Clause 670Ordering Using
MethodSyntax
671Querying
aLarge
Data Set 672Using Aggregate Operators
674Querying Complex Objects
678Projection: Creating
NewObjects
in Queries 681Projection:
MethodSyntax
682Using
theSelect DistinctQuery
683Using
theAny
and All Methods 684Ordering by Multiple
Levels 685Multi-Level Ordering
MethodSyntax: ThenBy
687Using Group Queries
687Using
TakeandSkip 689
Using
Firstand FirstOrDefault 691Using
theLINQ
SetOperators
692Using
Joins 694Summary
696CHAPTER 24: APPLYING LINQ 699
LINQ Varieties 699
Using
LINQ with Databases 700Installing
SQL Server and the NorthwindSample
Data 700Installing
SQL ServerExpress
701Installing
the NorthwindSample
Database 701First LINQto Database
Query
701Navigating
DatabaseRelationships
704Using
LINQ with XML 706LINQto
XML
Functional Constructors 707Constructing
XML Element Text withStrings
710Saving
andLoading
anXML
Document 710LoadingXML from a
String
712ContentsofaSavedXMLDocument 713
Working
with XMLFragments
713Generating
XML from Databases 715How to
Query
an XML Document 717Using
LINQtoXMLQuery
Members 718Elements!)
718Descendants!)
719Attributes!)
721Summary
723Hi
CHAPTER 25: WINDOWS COMMUNICATION FOUNDATION 727
What Is WCF? 728
WCF
Concepts
728WCF Communication Protocols 729
Addresses,
Endpoints,
andBindings
729Contracts 731
Message
Patterns 732Behaviors 732
Hosting
732WCF
Programming
733The WCF Test Client 740
Defining
WCF Service Contracts 742Data Contracts 743
Service Contracts 743
Operation
Contracts 744Message
Contracts 745Fault Contracts 745
Self-Hosted WCF Services 750
Summary
756CHAPTER 26: WINDOWS WORKFLOW FOUNDATION 759
Hello World 759
Workflows and Activities 761
If Activity 761
WhileActivity 762
Sequence
Activity
762Arguments
and Variables 763Custom Activities 767
Workflow Extensions 769
Activity
Validation 773Activity Designers
774Summary
776APPENDIX A: EXERCISE SOLUTIONS 779
INDEX 827
xxlss