C# 2010 All-In-One For Dummies

by Bill Sempf, Chuck Sphar,  and Stephen Randy Davis

8 IN BOOK 1

Basics of C# Programming
Object Oriented C#
Designing for C#
A Tour of Visual Studio®
Windows Programming
Web Programming
Service Oriented Development
C# 4.0

e-books shop
e-books shop
Purchase Now !
Just with Paypal



Book Details
 Price
 2.00 USD
 Pages
 867 p
 File Size
 12,319 KB
 File Type
 PDF format
 ISBN
 978-0-470-56348-9
 Copyright   
 2010 by Wiley Publishing, Inc  

About the Author
Hi, my name is Bill Sempf, and I am a software architect. Although I used to
hate the term architect, it’s clearly the only thing out there that defi nes what
I do. My breadth of experience includes business and technical analysis,
software design, development, testing, server management and maintenance,
and security. In my 17 years of professional experience, I have participated
in the creation of well over 200 applications for large and small companies,
managed the software infrastructure of two Internet service providers,
coded complex software happily in every environment imaginable, and made
mainframes talk to cellphones. In short, I make the technology products that
people are using every day play nicely together.

I started playing with computers in 1979 and haven’t looked back since. In
1985 I was helping my father (also named Bill) manage Apple IIe systems at
the local library. Since then I have built applications for the likes of Bank
One, Lucent Technologies, Nationwide Insurance, and Sears, Roebuck and
Co. I am the author of Visual Basic 2008 For Dummies and Visual Basic 2005
For Dummies; a coauthor of Effective Visual Studio.NET, Professional ASP.
NET Web Services, and Professional VB.NET; a frequent contributor to MSDN,
Builder.com, Hardcore Web Services, Cloud Computing Journal, Inside Web
Development Journal, and Intranet Journal; and have recently been an invited
speaker for the ACM and IEEE, DevEssentials, the International XML Web
Services Expo, and the Association of Information Technology Professionals.
I am a graduate of The Ohio State University with a bachelor’s of science
degree in business administration, a Microsoft Certifi ed Professional, a
Certifi ed Internet Business Strategist, and a Certifi ed Internet Webmaster. My
company is Products Of Innovative New Technology (usually called POINT),
and you can reach me at bill@pointWeb.net.

Chuck Sphar escaped the Microsoft C++ documentation camps after six
years of hard labor as a senior technical writer. You can reach Chuck for
praise and minor nits at csharp@chucksphar.com. His C# material Web
page (references throughout the book) is csharp102.info.

Stephen R. Davis, who goes by the name Randy, lives with his wife and son
near Dallas, Texas.

Introduction
C# 2010 All-in-One For Dummies represents a different way of looking
at programming languages. Rather than present the standard For
Dummies format, which includes only 350 pages on quite a large subject, the
book was expanded to include a broader scope and just a few pages were added.

So, although you find all the original C# For Dummies goodness in this
book, you also find discussions about Visual Studio, Windows Presentation
Foundation (WPF), service-oriented development, Web development, and a
host of other topics. This book is a one-stop shop for a C# developer.
The C# programming language is a powerful and, at some nine years old,
relatively mature descendant of the earlier C, C++, and Java languages.

Programming with C# is lots of fun, as you’re about to find out in this book.
Microsoft created C# as a major part of its .NET initiative. The company
turned over the specifications for the C# language to the ECMA (pronounced
“ek-ma”) international standards committee in the summer of 2000 so that
any company can, in theory, come up with its own version of C# written to
run on any operating system, on any machine larger than a calculator.

When the first edition of this book was published, the Microsoft C# compiler
was the only game in town, and its Visual Studio .NET suite of tools was the
only way to program C# (other than at the Windows command line). Since
then, however, Visual Studio has undergone three major revisions — the
latest is Visual Studio 2010. And, at least two other players have entered the C# game.

You can now write and compile C# programs on Windows and a variety of
Unix-based machines using implementations of .NET and C#, such as Mono
(www. mono-project.com), an open source software project sponsored
by Novell Corporation. Version 1.2 was released in November 2006. Though
Mono lags Microsoft .NET by half a version or so, it appears to be moving
fast, having implemented basically all of .NET 1.1 and much of .NET 2.0,
along with those versions of C#.

Both Mono and a less well developed competitor, Portable .NET (www.dotgnu.org/pnet.htm), 
claim to run C# programs on Windows and a
variety of Unix flavors, including Linux and the Apple Macintosh operating
system. At the time of this writing, Portable .NET reaches the greater number
of flavors, whereas Mono boasts a more complete .NET implementation.
So choosing between them can be complicated, depending on your project,
your platform, and your goals. (Books about programming for these platforms
are becoming available already. Check online booksellers.)
Open source software is written by collaborating groups of volunteer
programmers and is usually free to the world.

A description of how to make C# and other .NET languages portable to other
operating systems is far beyond the scope of this book. But you can expect
that within a few years, the C# Windows programs you discover how to write
in this book will run on all sorts of hardware under all sorts of operating
systems — matching the claim of Sun Microsystems’ Java language to run
on any machine. That’s undoubtedly a good thing, even for Microsoft. The
road to that point is still under construction, so it’s no doubt riddled with
potholes and obstacles to true universal portability for C#. But it’s no longer
just Microsoft’s road.

For the moment, however, Microsoft Visual Studio has the most mature
versions of C# and .NET and the most feature-filled toolset for programming
with them.

Note: Though three authors contributed to this book, saying I rather than we
throughout the main text seemed more economical, so that’s what we (or I)
do throughout.

What’s New in C# 4.0
Although much of C# 4.0 is still virtually the same as the previous version,
this new version adds some exciting new features, most of which revolve
around COM Interop, to assist with Office development. The big new
additions that this book covers include these topics:
✦ Dynamic types: Functional programming is all the rage these days, with
the cool kids programming in Ruby and Haskell. Functional programming
certainly has some benefits that have a place in the more tightly
woven world of C#, and dynamic typing is one of them. As supported
in C++ and Visual Basic, dynamic types allow runtime declaration when
you don’t know the type of a variable and then have the compiler figure
it out. Properly used, dynamic typing is quite powerful; poorly used, it’s
quite dangerous.
✦ Named and optional parameters: In C# 3.0, you had to provide a value
for every parameter in a method call. In C# 4.0 — again, to optimize
interactions with COM — you can mark parameters as optional and
accept outside objects that have optional parameters.
✦ Variance in generics: Although objects in previous versions of C# are
variant, generic collections of objects are invariant. This statement
means that although the compiler accepts an apple when you’re asked
for a fruit, it doesn’t accept a basket of apples when you’re asked for a
basket of fruit. This issue is fixed in C# 4.0.

Leaving aside a few of the more esoteric and advanced additions, we
mention a few smaller items here and there as appropriate. (Don’t worry if
parts of this introduction are Geek to you. You’ll get there.)
Because the features of C# 4.0 all tie together for use in a single major
operation — COM Interop — we bundled discussions of these features in
the back of this book, in Book VIII. Throughout this book, we have updated
chapters from the original C# 3.0 material wherever it seemed appropriate.

Table of Contents
Introduction ................................................................. 1
What’s New in C# 4.0 .......................................................................................2
About This Book ..............................................................................................3
What You Need in Order to Use This Book ..................................................3
How to Use This Book .....................................................................................4
How This Book Is Organized ..........................................................................4
Book I: The Basics of C# Programming ...............................................5
Book II: Object-Oriented C# Programming .........................................5
Book III: Designing for C# ......................................................................5
Book IV: A Tour of Visual Studio ..........................................................5
Book V: Windows Development with WPF .........................................5
Book VI: Web Development with ASP.NET .........................................6
Book VII: Service-Oriented Development ............................................6
Book VIII: New Features in C# 4.0 ........................................................6
Icons Used in This Book .................................................................................6
Conventions Used in This Book .....................................................................7
About this book’s Web site ...................................................................7
Where to Go from Here ...................................................................................8
Book I: Basics of C# Programming
Chapter 1: Creating Your First C# Console Application
Getting a Handle on Computer Languages, C#, and .NET ........................11
What’s a program? ...............................................................................12
What’s C#? ............................................................................................12
What’s .NET?.........................................................................................13
What is Visual Studio 2010? What about Visual C#? .......................14
Creating Your First Console Application ....................................................14
Creating the source program .............................................................15
Taking it out for a test drive ...............................................................18
Making Your Console App Do Something ...................................................19
Reviewing Your Console Application ..........................................................20
The program framework .....................................................................20
Comments .............................................................................................21
The meat of the program ....................................................................21
Introducing the Toolbox Trick .....................................................................22
Saving code in the Toolbox ................................................................23
Reusing code from the Toolbox .........................................................23
Chapter 2: Living with Variability — Declaring
Value-Type Variables
Declaring a Variable ......................................................................................25
What’s an int? .................................................................................................26
Rules for declaring variables ..............................................................27
Variations on a theme: Different types of int ...................................27
Representing Fractions .................................................................................28
Handling Floating-Point Variables ...............................................................29
Declaring a fl oating-point variable .....................................................30
Converting some more temperatures ...............................................31
Examining some limitations of fl oating-point variables ..................31
Using the Decimal Type: Is It an Integer or a Float? ..................................32
Declaring a decimal .............................................................................33
Comparing decimals, integers, and fl oating-point types ................33
Examining the bool Type: Is It Logical? ......................................................34
Checking Out Character Types ....................................................................34
The char variable type ........................................................................34
Special chars ........................................................................................35
The string type .....................................................................................35
What’s a Value Type? ....................................................................................36
Comparing string and char ...........................................................................37
Calculating Leap Years: DateTime ...............................................................38
Declaring Numeric Constants ......................................................................40
Changing Types: The Cast ............................................................................41
Letting the C# Compiler Infer Data Types ..................................................42
Chapter 3: Pulling Strings
The Union Is Indivisible, and So Are Strings ..............................................46
Performing Common Operations on a String .............................................47
Comparing Strings .........................................................................................48
Equality for all strings: The Compare( ) method .............................48
Would you like your compares with or without case?....................51
What If I Want to Switch Case? ....................................................................52
Distinguishing between all-uppercase and all-lowercase strings ....52
Converting a string to upper- or lowercase ......................................52
Looping through a String ..............................................................................53
Searching Strings ...........................................................................................54
Can I fi nd it? ..........................................................................................54
Is my string empty? .............................................................................55
Getting Input from the Command Line .......................................................55
Trimming excess white space ............................................................55
Parsing numeric input .........................................................................56
Handling a series of numbers .............................................................58
Joining an array of strings into one string ........................................60
Controlling Output Manually .......................................................................60
Using the Trim( ) and Pad( ) methods ...............................................61
Using the Concatenate( ) method ......................................................63
Let’s Split( ) that concatenate program ............................................64
Formatting Your Strings Precisely ..............................................................65
StringBuilder: Manipulating Strings More Effi ciently ................................69
Chapter 4: Smooth Operators
Performing Arithmetic ..................................................................................73
Simple operators ..................................................................................73
Operating orders ..................................................................................74
The assignment operator ....................................................................75
The increment operator ......................................................................76
Performing Logical Comparisons — Is That Logical? ...............................77
Comparing fl oating-point numbers: Is your fl oat
bigger than mine? .....................................78
Compounding the confusion with compound
logical operations ...................................79
Matching Expression Types at TrackDownAMate.com ............................80
Calculating the type of an operation .................................................81
Assigning types ....................................................................................82
Chapter 5: Getting Into the Program Flow
Branching Out with if and switch ................................................................86
Introducing the if statement ...............................................................86
Examining the else statement ............................................................89
Avoiding even the else ........................................................................90
Nesting if statements ...........................................................................90
Running the switchboard....................................................................92
Here We Go Loop-the-Loop ..........................................................................95
Looping for a while ..............................................................................95
Doing the do . . . while loop ................................................................99
Breaking up is easy to do ....................................................................99
Looping until you get it right ............................................................100
Focusing on scope rules ...................................................................103
Looping a Specifi ed Number of Times with for .......................................104
An example .........................................................................................105
Why do you need another loop? ......................................................105
Nesting Loops ..............................................................................................106
Don’t goto Pieces .........................................................................................107
Chapter 6: Lining Up Your Ducks with Collections 
The C# Array ................................................................................................109
The argument for the array ..............................................................110
The fi xed-value array .........................................................................110
The variable-length array .................................................................112
The Length property .........................................................................114
Initializing an array ............................................................................115
A Loop Made foreach Array ....................................................................115
Sorting Arrays of Data .................................................................................116
New Feature: Using var for Arrays ............................................................120
Loosening Up with C# Collections .............................................................121
Understanding Collection Syntax ..............................................................122
Figuring out <T> .................................................................................123
Going generic ......................................................................................124
Using Lists ....................................................................................................124
Using Dictionaries .......................................................................................126
Array and Collection Initializers ................................................................128
Initializing arrays ...............................................................................128
Initializing collections .......................................................................129
Using Sets .....................................................................................................130
On Not Using Old-Fashioned Collections .................................................134
Chapter 7: Stepping through Collections
Iterating through a Directory of Files ........................................................135
Iterating foreach Collections: Iterators .....................................................141
Accessing a collection: The general problem ................................141
Letting C# access data foreach container ......................................143
Accessing Collections the Array Way: Indexers ......................................145
Indexer format ....................................................................................145
An indexer program example ...........................................................146
Looping Around the Iterator Block ...........................................................150
Iterating days of the month: A fi rst example ..................................154
What a collection is, really ...............................................................155
Iterator syntax gives up so easily ....................................................156
Iterator blocks of all shapes and sizes ............................................158
Where you can put your iterator .....................................................161
Chapter 8: Buying Generic
Writing a New Prescription: Generics .......................................................169
Generics are type-safe .......................................................................170
Generics are effi cient .........................................................................171
Classy Generics: Writing Your Own ..........................................................171
Shipping packages at OOPs ..............................................................172
Queuing at OOPs: PriorityQueue .....................................................172
Unwrapping the package ..................................................................177
Touring Main( ) ...................................................................................178
Writing generic code the easy way ..................................................179
Saving PriorityQueue for last ...........................................................180
Using a (nongeneric) Simple Factory class ....................................182
Tending to unfi nished business .......................................................184
Chapter 9: Some Exceptional Exceptions
Using an Exceptional Error-Reporting Mechanism .................................187
About try blocks ................................................................................189
About catch blocks ............................................................................189
About fi nally blocks ...........................................................................190
What happens when an exception is thrown .................................190
Throwing Exceptions Yourself ...................................................................192
Knowing What Exceptions Are For ............................................................192
Can I Get an Exceptional Example? ...........................................................193
Knowing what makes the example exceptional .............................194
Tracing the stack ...............................................................................195
Assigning Multiple catch Blocks ................................................................196
Planning Your Exception-Handling Strategy ............................................198
Some questions to guide your planning .........................................198
Guidelines for code that handles errors well .................................199
How to analyze a method for possible exceptions ........................200
How to fi nd out which methods throw which exceptions............203
Grabbing Your Last Chance to Catch an Exception ................................203
Book II: Object-Oriented C# Programming
Chapter 1: Object-Oriented Programming: What’s It All About?
Object-Oriented Concept #1: Abstraction ................................................207
Preparing procedural nachos...........................................................208
Preparing object-oriented nachos ...................................................209
Object-Oriented Concept #2: Classifi cation .............................................209
Why Classify? ...............................................................................................210
Object-Oriented Concept #3: Usable Interfaces ......................................211
Object-Oriented Concept #4: Access Control ..........................................212
How C# Supports Object-Oriented Concepts ..........................................212
Chapter 2: Showing Some Class
Defi ning a Class and an Object ..................................................................215
Defi ning a class ...................................................................................216
What’s the object? .............................................................................217
Accessing the Members of an Object ........................................................218
An Object-Based Program Example ..........................................................218
Discriminating between Objects ................................................................220
Can You Give Me References? ....................................................................221
Classes That Contain Classes Are the Happiest
Classes in the World ................................................................................223
Generating Static in Class Members .........................................................224
Defi ning const and readonly Data Members .......................................225
Chapter 3: We Have Our Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .227
Defi ning and Using a Method .....................................................................227
A Method Example for Your Files ..............................................................229
Having Arguments with Methods ..............................................................236
Passing an argument to a method ...................................................236
Passing multiple arguments to methods ........................................237
Matching argument defi nitions with usage ....................................238
Overloading a method doesn’t mean giving it too much to do ...239
Implementing default arguments .....................................................240
Returning Values after Christmas .............................................................243
Returning a value via return postage ..............................................243
Defi ning a method with no value .....................................................244
Chapter 4: Let Me Say This about this . . . . . . . . . . . . . . . . . . . . . . . .247
Passing an Object to a Method ..................................................................247
Defi ning Methods .........................................................................................249
Defi ning a static method ...................................................................249
Defi ning an instance method ............................................................250
Expanding a method’s full name ......................................................252
Accessing the Current Object ....................................................................253
What is the this keyword? ..............................................................254
When is this explicit? ......................................................................255
What happens when you don’t have this? ...................................257
Chapter 5: Holding a Class Responsible . . . . . . . . . . . . . . . . . . . . . . . .261
Restricting Access to Class Members .......................................................261
A public example of public BankAccount .......................................262
Jumping ahead — other levels of security .....................................264
Why You Should Worry about Access Control ........................................265
Accessor methods .............................................................................266
Access control to the rescue — an example ..................................266
So what? ..............................................................................................269
Defi ning Class Properties ...........................................................................270
Static properties ................................................................................271
Properties with side effects ..............................................................272
New feature: Letting the compiler write properties for you ........272
Accessors with access levels ...........................................................273
Getting Your Objects Off to a Good Start — Constructors ....................273
The C#-Provided Constructor ....................................................................274
Replacing the Default Constructor ............................................................275
Constructing something ....................................................................276
Executing the constructor from the debugger ...............................278
Initializing an object directly with an initializer ............................281
Seeing that construction stuff with initializers ..............................282
New feature: Initializing an object without a constructor ............283
Chapter 6: Inheritance: Is That All I Get? . . . . . . . . . . . . . . . . . . . . . . . .285
Class Inheritance .........................................................................................286
Why You Need Inheritance .........................................................................287
Inheriting from a BankAccount Class (A More Complex Example) ......288
IS_A versus HAS_A — I’m So Confused_A ................................................291
The IS_A relationship ........................................................................291
Gaining access to BankAccount by using containment ................292
The HAS_A relationship ....................................................................293
When to IS_A and When to HAS_A ............................................................293
Other Features That Support Inheritance ................................................294
Substitutable classes .........................................................................294
Invalid casts at run time....................................................................295
Avoiding invalid conversions with the is operator .......................296
Avoiding invalid conversions with the as operator ......................297
The object Class ..........................................................................................297
Inheritance and the Constructor ...............................................................298
Invoking the default base class constructor ..................................298
Passing arguments to the base class constructor —
mama sang base .............................................................................300
Getting specifi c with base .................................................................301
The Updated BankAccount Class ..............................................................302
Chapter 7: Poly-what-ism? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .307
Overloading an Inherited Method .............................................................308
It’s a simple case of method overloading .......................................308
Different class, different method .....................................................308
Peek-a-boo — hiding a base class method .....................................309
Calling back to base ...........................................................................313
Polymorphism ..............................................................................................314
Using the declared type every time (Is that so wrong?) ...............316
Using is to access a hidden method polymorphically ................318
Declaring a method virtual and overriding it .................................319
Getting the most benefi t from polymorphism —
the do-to-each trick ........................................................................321
The Class Business Card: ToString( ) ........................................................321
C# During Its Abstract Period ....................................................................322
Class factoring ....................................................................................322
The abstract class: Left with nothing but a concept .....................327
How do you use an abstract class? .................................................328
Creating an abstract object — not! ..................................................330
Sealing a Class ..............................................................................................330
Chapter 8: Interfacing with the Interface. . . . . . . . . . . . . . . . . . . . . . . .333
Introducing CAN_BE_USED_AS ..................................................................333
Knowing What an Interface Is ....................................................................335
How to implement an interface ........................................................335
How to name your interface .............................................................336
Why C# includes interfaces ..............................................................336
Mixing inheritance and interface implementation ........................336
And he-e-e-re’s the payoff .................................................................337
Using an Interface ........................................................................................338
As a method return type ...................................................................338
As the base type of an array or collection ......................................339
As a more general type of object reference ...................................339
Using the C# Predefi ned Interface Types .................................................339
Looking at a Program That CAN_BE_USED_AS an Example ...................340
Creating your own interface at home in your spare time .............340
Implementing the incomparable IComparable<T> interface........341
Putting it all together.........................................................................343
Getting back to the Main( ) event ....................................................346
Unifying Class Hierarchies .........................................................................346
Hiding Behind an Interface .........................................................................348
Inheriting an Interface .................................................................................351
Using Interfaces to Manage Change in Object-Oriented Programs .......352
Making fl exible dependencies through interfaces .........................353
Abstract or concrete: When to use an abstract class
and when to use an interface ........................................................353
Doing HAS_A with interfaces ............................................................354
Chapter 9: Delegating Those Important Events. . . . . . . . . . . . . . . . . . .357
E.T., Phone Home — The Callback Problem ............................................357
Defi ning a Delegate ......................................................................................358
Pass Me the Code, Please — Examples .....................................................360
I delegated the example to Igor ........................................................360
First, a simple example .....................................................................361
A More Real-World Example ......................................................................362
Getting an overview of the bigger example ....................................363
Putting the app together ...................................................................363
Looking at the code ...........................................................................365
Tracking the delegate life cycle .......................................................366
Shh! Keep It Quiet — Anonymous Methods .............................................368
Stuff Happens — C# Events ........................................................................369
The Observer design pattern ...........................................................369
What’s an event? Publish/Subscribe ...............................................370
How a publisher advertises its events ............................................370
How subscribers subscribe to an event .........................................371
How to publish an event ...................................................................372
How to pass extra information to an event handler ......................372
A recommended way to raise your events .....................................373
How observers “handle” an event ...................................................374
Chapter 10: Can I Use Your Namespace in the Library? . . . . . . . . . . .377
Dividing a Single Program into Multiple Source Files .............................378
Dividing a Single Program into Multiple Assemblies ..............................379
Executable or library? .......................................................................379
Assemblies ..........................................................................................380
Executables .........................................................................................381
Class libraries .....................................................................................381
Putting Your Classes into Class Libraries ................................................382
Creating the projects for a class library .........................................382
Creating a stand-alone class library ................................................382
Adding a second project to an existing solution ...........................383
Creating classes for the library ........................................................384
Using a driver program to test a library .........................................385
Using a class library from a program ..............................................386
Going Beyond Public and Private: More Access Keywords ...................387
Internal: Eyes only at the CIA ...........................................................387
Protected: Sharing with subclasses.................................................390
Protected internal: Being a more generous protector ..................392
Putting Classes into Namespaces ..............................................................392
Declaring a namespace .....................................................................394
Relating namespaces to the access keyword story .......................395
Using fully qualifi ed names ...............................................................397
Book III: Designing for C# ......................................... 399
Chapter 1: Writing Secure Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .401
Designing Secure Software .........................................................................402
Determining what to protect ............................................................402
Documenting the components of the program ..............................402
Decomposing components into functions ......................................403
Identifying potential threats in functions .......................................403
Rating the risk ....................................................................................404
Building Secure Windows Applications ....................................................404
Authentication using Windows login ..............................................404
Encrypting information .....................................................................407
Deployment security .........................................................................407
Building Secure Web Forms Applications ................................................408
SQL Injection attacks .........................................................................409
Script exploits ....................................................................................410
Best practices for securing Web Forms applications ...................411
Using System.Security .................................................................................412
Chapter 2: Accessing Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .415
Getting to Know System.Data .....................................................................416
How the Data Classes Fit into the Framework .........................................417
Getting to Your Data ...................................................................................418
Using the System.Data Namespace ...........................................................418
Setting up a sample database schema ............................................419
Connecting to a data source .............................................................420
Working with the visual tools...........................................................425
Writing data code...............................................................................428
Using the Entity Framework .............................................................431
Chapter 3: Fishing the FileStream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .435
Going Where the Fish Are: The File Stream .............................................435
Streams................................................................................................435
Readers and writers ..........................................................................436
StreamWriting for Old Walter ....................................................................438
Using the stream: An example ..........................................................439
Revving up a new outboard StreamWriter .....................................441
Finally, we’re writing! ........................................................................442
Using some better fi shing gear: The using statement ...................445
Pulling Them Out of the Stream: Using StreamReader ...........................448
More Readers and Writers .........................................................................452
Exploring More Streams than Lewis and Clark ........................................453
Chapter 4: Accessing the Internet. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .455
Getting to Know System.Net ......................................................................456
How Net Classes Fit into the Framework ..................................................457
Using the System.Net Namespace .............................................................458
Checking the network status ............................................................459
Downloading a fi le from the Internet ...............................................460
E-mailing a status report ...................................................................462
Logging network activity...................................................................465
Chapter 5: Creating Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .469
Getting to Know System.Drawing ..............................................................469
Graphics ..............................................................................................470
Pens .....................................................................................................470
Brushes ...............................................................................................471
Text ......................................................................................................471
How the Drawing Classes Fit into the Framework ...................................472
Using the System.Drawing Namespace .....................................................473
Getting started ...................................................................................473
Setting up the project ........................................................................475
Drawing the board .............................................................................476
Book IV: A Tour of Visual Studio ................................ 479
Chapter 1: Getting Started with Visual Studio . . . . . . . . . . . . . . . . . . .481
Versioning the Versions .............................................................................481
Express ................................................................................................482
Professional ........................................................................................483
Team System ......................................................................................483
MSDN ...................................................................................................484
Academic ............................................................................................485
An edition breakdown .......................................................................485
Installing Visual Studio ...............................................................................486
Breaking Down the Projects .......................................................................488
Exploring the New Project dialog box .............................................488
Understanding solutions and projects ............................................489
A brief survey of the available project categories .........................491
Chapter 2: Using the Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .495
Designing in the Designer ...........................................................................495
Windows Presentation Foundation (WPF) .....................................496
Windows Forms..................................................................................498
Web Forms ..........................................................................................499
Class Designer ....................................................................................500
Paneling the Studio ......................................................................................502
Solution Explorer ...............................................................................502
Properties ...........................................................................................504
The Toolbox .......................................................................................505
Server Explorer ..................................................................................506
Class View ...........................................................................................508
Coding in Code View ...................................................................................509
Exercising the Code Viewer ..............................................................509
Exploring the auxiliary windows......................................................512
Using the Tools of the Trade ......................................................................514
The Tools menu .................................................................................514
Building and Debugging ....................................................................515
Refactor menu ....................................................................................515
Chapter 3: Customizing Visual Studio. . . . . . . . . . . . . . . . . . . . . . . . . . .517
Setting Options ............................................................................................518
Environment .......................................................................................518
Language .............................................................................................519
Neat stuff .............................................................................................520
Using Snippets .............................................................................................521
Using snippets ....................................................................................521
Using surround snippets ...................................................................522
Making snippets .................................................................................523
Deploying snippets ............................................................................525
Sharing snippets ................................................................................526
Hacking the Project Types .........................................................................527
Hacking Project templates ................................................................527
Hacking item templates .....................................................................530
Chapter 4: Transforming Text Templates. . . . . . . . . . . . . . . . . . . . . . . .533
Getting to Know T4 ......................................................................................533
Looking back at the DSL Tools .........................................................534
Looking ahead to what it became ....................................................534
Figuring Out When to Use T4 .....................................................................535
Replacing repetitive coding ..............................................................535
Building code based on outside data ..............................................536
Setting Up the Environment .......................................................................536
Changing the security settings .........................................................536
Creating a template from a text fi le .................................................537
Using Some of the T4 Directives ................................................................539
Setting the output ..............................................................................539
Confi guring a template ......................................................................540
Including includes ..............................................................................540
Importing items and assemblies ......................................................541
Book V: Windows Development with WPF ................... 543
Chapter 1: Introducing WPF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .545
Understanding What WPF Can Do .............................................................545
Introducing XAML ........................................................................................547
Diving In! Creating Your First WPF Application .......................................547
Declaring an application-scoped resource ....................................549
Making the application do something .............................................550
Whatever XAML Can Do, C# Can Do Better! .............................................552
Chapter 2: Understanding the Basics of WPF . . . . . . . . . . . . . . . . . . . .555
Using WPF to Lay Out Your Application ...................................................555
Arranging Elements with Layout Panels ...................................................557
The Stack Panel ..................................................................................557
The Wrap Panel ..................................................................................559
The Dock Panel ..................................................................................559
Canvas .................................................................................................560
The Uniform Grid ...............................................................................561
The Grid ..............................................................................................562
Putting it all together with a simple data entry form ....................567
Panels of honorable mention ...........................................................569
Exploring Common XAML Controls ..........................................................570
Display only controls ........................................................................570
Basic input controls ..........................................................................572
List-based controls ............................................................................574
Chapter 3: Data Binding in WPF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .579
Getting to Know Dependency Properties .................................................579
Exploring the Binding Modes .....................................................................580
Investigating the Binding Object ...............................................................581
Defi ning a binding with XAML ..........................................................581
Defi ning a binding with C# ................................................................583
Editing, Validating, Converting,
and Visualizing Your Data .......................................................................584
Validating data ...................................................................................589
Converting your data.........................................................................592
Finding Out More about WPF Data Binding .............................................599
Chapter 4: Practical WPF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .601
Commanding Attention ...............................................................................601
ICommand ...........................................................................................602
Routed commands .............................................................................602
Built-in commands .............................................................................603
Focus!...................................................................................................605
Custom commands ............................................................................605
Separation of Concerns and testability ...........................................610
Get Your ViewModel On .............................................................................612
Who cares? .........................................................................................612
Tradition! ............................................................................................613
Show me the code! .............................................................................614
Book VI: Web Development with ASP.NET .................. 627
Chapter 1: Looking at How ASP.NET Works with C#. . . . . . . . . . . . . .629
Breaking Down Web Applications .............................................................630
Questioning the Client ................................................................................632
Scripting the client.............................................................................633
Getting information back from the client .......................................633
Understanding the weaknesses of the browser .............................634
Dealing with Web Servers ...........................................................................636
Getting a PostBack (Hint: It’s not a returned package) ................636
It’s a matter of state ...........................................................................639
Chapter 2: Building Web Applications. . . . . . . . . . . . . . . . . . . . . . . . . .641
Working in Visual Studio ............................................................................642
Handling the Designer .......................................................................642
Coding in Code View..........................................................................647
Recognizing the other fi le types ......................................................651
Developing with Style ..................................................................................652
Coding behind ....................................................................................652
Scripting the experience ...................................................................653
Building in n-tier .................................................................................655
Modeling the View Controller ..........................................................656
Chapter 3: Controlling Your Development Experience . . . . . . . . . . . .659
Showing Stuff to the User ...........................................................................660
Labels versus plain old text ..............................................................660
Images .................................................................................................661
Panels and multiviews .......................................................................663
Tables ..................................................................................................663
Getting Some Input from the User .............................................................664
Using text input controls ..................................................................664
Using single-item selection controls ...............................................666
Using multiple-item selection controls ...........................................668
Using other kinds of input controls .................................................669
Submitting input with Submit buttons ............................................670
Data Binding .................................................................................................670
Setting up your markup for binding ................................................671
Data binding using the code-behind ................................................673
Using commonly bound controls.....................................................674
Styling Your Controls ..................................................................................677
Setting control properties ................................................................677
Binding styles with CSS .....................................................................678
Making Sure the Site Is Accessible ............................................................679
Control features for accessibility ....................................................680
Design considerations .......................................................................680
Constructing User Controls ........................................................................680
Making a new phone number user control .....................................681
Using your new control .....................................................................682
Adding Custom Controls ............................................................................683
Chapter 4: Leveraging the .NET Framework . . . . . . . . . . . . . . . . . . . . .685
Surfi ng Web Streams ...................................................................................686
Intercepting the request ...................................................................686
Altering content sent to clients ........................................................689
Securing with ASP.NET ...............................................................................690
Changing trusts ..................................................................................691
Fixing problems ..................................................................................692
Navigating with Site Maps ..........................................................................692
Adding a site map ..............................................................................692
Navigating a site with SiteMap .........................................................694
Managing Files ..............................................................................................695
Baking Cookies .............................................................................................696
Coding for client-side storage ..........................................................697
Wrangling cookies on the server .....................................................698
How ASP.NET manages cookies for you .........................................699
Tracing with TraceContext .........................................................................699
Chapter 5: Digging into Web Construction . . . . . . . . . . . . . . . . . . . . . .703
Managing Files ..............................................................................................704
Reviewing project types ....................................................................704
Reviewing fi le types ...........................................................................706
Organizing fi les ...................................................................................708
Mastering Master Pages ..............................................................................709
Making a master page ........................................................................709
Adding content ...................................................................................710
Testing Web Applications with Visual Studio ..........................................711
Deploying Your Masterpiece ......................................................................713
Lots of options ...................................................................................713
Copying Web sites with “Copy Web” ..............................................714
Package/Publish .................................................................................715
Book VII: Service-Oriented Development ..................... 717
Chapter 1: Getting Acquainted with Web Services . . . . . . . . . . . . . . .719
Understanding Web Services .....................................................................719
Loosely coupled .................................................................................721
Contract driven ..................................................................................722
Chunky versus chatty ........................................................................724
Building Service-Oriented Applications ....................................................726
Providing XML Web Services .....................................................................728
Building Three Sample Apps ......................................................................728
Chapter 2: Building Web Services with ASMX . . . . . . . . . . . . . . . . . .731
Getting to Know SOAP ................................................................................732
SOAP and standards ..........................................................................732
The WS-* standards ...........................................................................733
The impact to you ..............................................................................733
Big, fat, and slow ................................................................................734
Making an ASMX Service ............................................................................735
Creating a new service ......................................................................735
Building the code for SHARP ............................................................739
Deploying ............................................................................................741
Consuming services in your applications .......................................743
Chapter 3: Building Web Services with WCF . . . . . . . . . . . . . . . . . . . .745
Getting to Know WCF ..................................................................................746
Creating a WCF Service ...............................................................................748
Breaking it down ................................................................................748
Making a registration service ...........................................................750
Confi guring .........................................................................................752
Deploying ............................................................................................756
Consuming ..........................................................................................757
Chapter 4: Building Web Services with ReST . . . . . . . . . . . . . . . . . . .759
Getting to Know ReST .................................................................................759
Understanding the Guiding Principles of ReST .......................................760
Diving into the details of ReST .........................................................761
Changing a WCF Service to Use ReST .......................................................762
Getting the WCF service ....................................................................762
Exposing the ReST service................................................................762
Returning data in different ways ......................................................763
Book VIII: New Features in C# 4.0 ............................ 767
Chapter 1: Programming Dynamically! . . . . . . . . . . . . . . . . . . . . . . . . .769
Shifting C# Toward Dynamic Typing .........................................................770
Programming Dynamically .........................................................................772
Putting Dynamic to Use ..............................................................................774
Classic examples ................................................................................774
Making static operations dynamic ..................................................775
Understanding what’s happening under the covers .....................775
Running with the Dynamic Language Runtime ........................................776
Dynamic Ruby ....................................................................................777
Dynamic C# .........................................................................................778
Chapter 2: Improving Productivity with Named and
Optional Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .781
Optional Parameters ...................................................................................782
Reference types ..................................................................................784
Output parameters ............................................................................785
Named Parameters ......................................................................................786
Overload Resolution ...................................................................................787
Chapter 3: Helping Out with Interop . . . . . . . . . . . . . . . . . . . . . . . . . . . .789
Using Dynamic Import ................................................................................790
Working without Primary Interop Assemblies ........................................791
Skipping the Ref Statement ........................................................................793
Chapter 4: Revising Generics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .795
Variance ........................................................................................................796
Contravariance ............................................................................................796
Covariance ....................................................................................................798
Index ....................................................................... 799


Bookscreen
e-books shop

About This Book
The goal of this book is to explain C# to you. To write usable programs, you
need a specific coding environment. We’re betting that most readers will
use Microsoft Visual Studio, although we suggest alternatives. Because this
book is an All-in-One, we give you comprehensive coverage of Visual Studio in Book IV.

The original version of C# For Dummies (like all programming language
books) focused on C# as a language, not all of the things you do with C#.
This version of the book — in the mondo-size All-in-One format — covers
Windows development, Web development, service development, and .NET
Framework development, such as graphics and databases.

Our goal is to make a one-stop shop for development with Microsoft products,
though there is indeed more to the topics than fits in this book. Office
development isn’t covered, for instance. SharePoint has way too much going
on to cover it along with everything else (although Bill co-authored VSTO
For Dummies). This book is designed to handle the vast majority of C# users,
though 20 percent of our readers will be working on something that we don’t
cover. Sorry about that — we’ll try to stretch the book to 1,000 pages next time.

Another point is that every programming problem is different. Although
many different situations are covered between the covers of this book, your
specific situation is different. Some interpolation has to be taking place.
If you have a question about how your personal situation fits in, send the
author an e-mail at csharpfordummies.net and we’ll try to help.

How to Use This Book
We’ve made this book as easy to use as possible. Figuring out a new language
is hard enough — why make it any more complicated than it needs to be?
Though this book is divided into eight minibooks, we use an even easier
subdivision.

Books I and II comprise the bulk of the original C# For Dummies book,
and they cover the C# language, updated for version 4.0. Books III and IV
cover technologies that are peripheral to C#. Books V, VI, and VII cover the
three main types of development you do in C# — Windows Presentation
Foundation, Web development, and service-oriented programming. We finish
with the (thankfully short) Book VIII, about new C# 4.0 features.
If you’re brand new, start at the beginning and read the first two minibooks.
You’ll discover a lot. Really. It will seem as though you’re reading a lot of
text, but it is engaging and has interesting examples.

If you’re using the .NET Framework (which you probably are), read Book III
as well. If you’re using Visual Studio, read Book IV. (Note that we use Visual
Studio 2010 Professional edition, so if you’re using Express or Ultimate, your
screens might look slightly different.)

Finally, you can focus on your project type — Books V, VI, and VII are
specific to project type, and you can pick and choose what to read. These
three minibooks are organized more as a collection of related articles than
as discrete book units. You’ll find them easier to use that way.
Previous Post Next Post