cover

Table of Contents

Title Page

Copyright

Dedication

About the Authors

About the Technical Editor

Credits

Acknowledgments

Introduction

Who This Book Is For

What's New in This Edition

How This Book Is Structured

What You Need to Use This Book

Conventions

Source Code

Errata

p2p.wrox.com

Part I: The C# Language

Chapter 1: Introducing C#

What is the .NET Framework?

What is C#?

Visual Studio 2010

Summary

Chapter 2: Writing a C# Program

The Development Environments

Console Applications

Windows Forms Applications

Summary

Chapter 3: Variables and Expressions

Basic C# Syntax

Basic C# Console Application Structure

Variables

Expressions

Summary

Chapter 4: Flow Control

Boolean Logic

The goto Statement

Branching

Looping

Summary

Chapter 5: More About Variables

Type Conversion

Complex Variable Types

String Manipulation

Summary

Chapter 6: Functions

Defining and Using Functions

Variable Scope

The Main() Function

Struct Functions

Overloading Functions

Delegates

Summary

Chapter 7: Debugging and Error Handling

Debugging in VS and VCE

Error Handling

Summary

Chapter 8: Introduction to Object-Oriented Programming

What Is Object-Oriented Programming?

OOP Techniques

OOP in Windows Applications

Summary

What You Learned in this Chapter

Chapter 9: Defining Classes

Class Definitions in C#

System.Object

Constructors and Destructors

OOP Tools in VS and VCE

Class Library Projects

Interfaces Versus Abstract Classes

Struct Types

Shallow Copying Versus Deep Copying

Summary

Chapter 10: Defining Class Members

Member Definitions

Additional Class Member Topics

Interface Implementation

Partial Class Definitions

Partial Method Definitions

Example Application

The Call Hierarchy Window

Summary

Chapter 11: Collections, Comparisons, and Conversions

Collections

Comparisons

Conversions

Summary

Chapter 12: Generics

What Are Generics?

Using Generics

Defining Generic Types

Variance

Summary

Chapter 13: Additional OOP Techniques

The :: Operator and the Global Namespace Qualifier

Custom Exceptions

Events

Expanding and Using CardLib

Summary

Chapter 14: C# Language Enhancements

Initializers

Type Inference

Anonymous Types

Dynamic Lookup

Advanced Method Parameters

Extension Methods

Lambda Expressions

Summary

Part II: Windows Programming

Chapter 15: Basic Windows Programming

Controls

The Button Control

The Label and LinkLabel Controls

The TextBox Control

The RadioButton and CheckBox Controls

The RichTextBox Control

The ListBox and CheckedListBox Controls

The ListView Control

The TabControl Control

Summary

Chapter 16: Advanced Windows Forms Features

Menus and Toolbars

Toolbars

SDI and MDI Applications

Building MDI Applications

Creating Controls

Summary

Chapter 17: Deploying Windows Applications

Deployment Overview

ClickOnce Deployment

Visual Studio Setup and Deployment Project Types

Microsoft Windows Installer Architecture

Creating an Installation Package for the MDI Editor

Building the Project

Installation

Summary

Part III: Web Programming

Chapter 18: ASP.NET Web Programming

Overview of Web Applications

ASP.NET Runtime

Creating a Simple Page

Server Controls

ASP.NET Postback

ASP.NET AJAX Postback

Input Validation

State Management

Styles

Master Pages

Site Navigation

Authentication and Authorization

Reading from and Writing to a SQL Server Database

Summary

Chapter 19: Web Services

Where to Use Web Services

Application Architecture

Web Services Architecture

Web Services and the .NET Framework

Creating a Simple ASP.NET Web Service

Testing the Web Service

Implementing a Windows Client

Calling the Service Asynchronously

Implementing an ASP.NET Client

Passing Data

Summary

Chapter 20: Deploying Web Applications

Internet Information Services

IIS Configuration

Copying a Website

Publishing a Web Application

Windows Installer

Summary

Part IV: Data Access

Chapter 21: File System Data

Streams

The Classes for Input and Output

Serialized Objects

Monitoring the File System

Summary

Chapter 22: XML

XML Documents

Using XML in Your Application

Summary

Chapter 23: Introduction to LINQ

First LINQ Query

Using the LINQ Method Syntax

Ordering Query Results

orderby Clause

Ordering Using Method Syntax

Querying a Large Data Set

Aggregate Operators

Querying Complex Objects

Projection: Creating New Objects in Queries

Projection: Method Syntax

Select Distinct Query

Any and All

Ordering by Multiple Levels

Multi-Level Ordering Method Syntax: ThenBy

Group Queries

Take and Skip

First and FirstOrDefault

Set Operators

Joins

Summary

Chapter 24: Applying LINQ

LINQ Varieties

Using LINQ with Databases

Installing SQL Server and the Northwind Sample Data

First LINQ to Database Query

Navigating Database Relationships

Using LINQ with XML

LINQ to XML Functional Constructors

Saving and Loading an XML Document

Working with XML Fragments

Generating XML from Databases

How to Query an XML Document

Using LINQ to XML Query Members

Summary

Part V: Additional Techniques

Chapter 25: Windows Presentation Foundation

What Is WPF?

Anatomy of a Basic WPF Application

WPF Fundamentals

Programming with WPF

Summary

Chapter 26: Windows Communication Foundation

What Is WCF?

WCF Concepts

WCF Programming

Summary

Chapter 27: Windows Workflow Foundation

Hello World

Workflows and Activities

Arguments and Variables

Custom Activities

Summary

Appendix A: Exercise Solutions

Chapter 3 Solutions

Chapter 4 Solutions

Chapter 5 Solutions

Chapter 6 Solutions

Chapter 7 Solutions

Chapter 8 Solutions

Chapter 9 Solutions

Chapter 10 Solutions

Chapter 11 Solutions

Chapter 12 Solutions

Chapter 13 Solutions

Chapter 14 Solutions

Chapter 15 Solutions

Chapter 16 Solutions

Chapter 17 Solutions

Chapter 18 Solutions

Chapter 19 Solutions

Chapter 20 Solutions

Chapter 21 Solutions

Chapter 22 Solutions

Chapter 23 Solutions

Chapter 24 Solutions

Chapter 25 Solutions

Chapter 26 Solutions

Answers to Chapter 27 Exercises

Index

Advertisement

Title Page

for Donna

—KARLI WATSON

About the Authors

KARLI WATSON is consultant at Infusion Development (www.infusion.com), a technology architect at Boost.net (www.boost.net), and a freelance IT specialist, author, and developer. For the most part, he immerses himself in .NET (in particular C# and lately WPF) and has written numerous books in the field for several publishers. He specializes in communicating complex ideas in a way that is accessible to anyone with a passion to learn, and spends much of his time playing with new technology to find new things to teach people about.

During those (seemingly few) times where he isn't doing the above, Karli will probably be wishing he was hurtling down a mountain on a snowboard. Or possibly trying to get his novel published. Either way, you'll know him by his brightly colored clothes. You can also find him tweeting online at www.twitter.com/karlequin, and maybe one day he'll get around to making himself a website. Karli authored chapters 1 through 14, 21, 25 and 26.

CHRISTIAN NAGEL is a Microsoft Regional Director and Microsoft MVP, an associate of Thinktecture, and owner of CN Innovation. He is a software architect and developer who offers training and consulting on how to develop Microsoft .NET solutions. He looks back on more than 25 years of software development experience. Christian started his computing career with PDP 11 and VAX/VMS systems, covering a variety of languages and platforms. Since 2000, when .NET was just a technology preview, he has been working with various .NET technologies to build numerous .NET solutions. With his profound knowledge of Microsoft technologies, he has written numerous .NET books, and is certified as a Microsoft Certified Trainer and Professional Developer. Christian speaks at international conferences such as TechEd and Tech Days, and started INETA Europe to support .NET user groups. You can contact Christian via his web sites, www.cninnovation.com and www.thinktecture.com and follow his tweets on www.twitter.com/christiannagel. Christian wrote chapters 17 through 20.

JACOB HAMMER PEDERSEN is a Senior Application Developer at Elbek & Vejrup. He just about started programming when he was able to spell the word ‘BASIC', which, incidentally is the first programming language he ever used. He started programming the PC in the early '90s, using Pascal but soon changed his focus to C++, which still holds his interest. In the mid '90s his focus changed again, this time to Visual Basic. In the summer of 2000 he discovered C# and has been happily exploring it ever since. Primarily working on the Microsoft platforms, his other expertise includes MS Office development, SQL Server, COM and Visual Basic.Net.

A Danish citizen, Jacob works and lives in Aarhus, Denmark. He authored chapters 15, 16, and 22.

JON D. REID is a software engineering manager at Metrix LLC, an ISV of field service management software for the Microsoft environment. He has co-authored a variety .NET books, including Beginning Visual C# 2008, Beginning C# Databases: From Novice to Professional, Pro Visual Studio .NET, and many others. Jon wrote chapters 23 and 24.

MORGAN SKINNER began his computing career at a young age on the Sinclair ZX80 at school, where he was underwhelmed by some code a teacher had written and so began programming in assembly language. Since then he's used all sorts of languages and platforms, including VAX Macro Assembler, Pascal, Modula2, Smalltalk, X86 assembly language, PowerBuilder, C/C++, VB, and currently C# (of course). He's been programming in .NET since the PDC release in 2000, and liked it so much he joined Microsoft in 2001. He now works in premier support for developers and spends most of his time assisting customers with C#. Morgan wrapped up the book by authoring chapter 27. You can reach Morgan at www.morganskinner.com.

About the Technical Editor

A “blue-badge” .NET architect and developer at Intel Corporation since March 2007, Doug Holland is part of the Visual Computing Group and is presently working within an advanced tools and development team with an emphasis on chipset and driver testing. Doug Holland holds a Master's Degree in Software Engineering from Oxford University and has been awarded both the Microsoft MVP and Intel Black Belt Developer awards. Outside of work, Doug enjoys spending time with his wife and four children; and is also an officer in the Civil Air Patrol/U.S. Air Force Auxiliary. Beyond architecting and developing software you can often find Doug at the local airport flying Cessnas over the California landscape.

Credits

Acquisitions Editor

Paul Reese

Development Editor

Maryann Steinhart

Project Editor

Ami Frank Sullivan

Technical Editor

Doug Holland

Production Editor

Rebecca Anderson

Copy Editor

Luann Rouff

Editorial Director

Robyn B. Siesky

Editorial Manager

Mary Beth Wakefield

Associate Director of Marketing

David Mayhew

Production Manager

Tim Tate

Vice President and Executive Group Publisher

Richard Swadley

Vice President and Executive Publisher

Barry Pruett

Associate Publisher

Jim Minatel

Project Coordinator, Cover

Lynsey Stanford

Proofreader

Josh Chase, Word One

Indexer

J & J Indexing

Cover Designer

Michael E. Trent

Cover Image

© Lisa Loyd/istockphoto

Acknowledgments

FROM KARLI WATSON: Thanks to all at Wiley for their support and assistance on this project, as well as their understanding and flexibility in dealing with an author who never seems to have enough time to write. Special thanks to my editor for this book, Ami Sullivan, for adding sparkle and making this book shine. Also, thanks to friends, family, and work colleagues for understanding why I haven't have time for much socializing lately, and to Donna, as always, for all her support and for putting up with all the late nights.

FROM CHRISTIAN NAGEL: To my two girls Angela and Stephanie. It's great to have you. Thanks for your great support and the big love you gave me during the hardest time of my life in 2009. Without you I couldn't have made it through. Stephanie, while not born yet, you were my biggest motivation during that time. I love you both!

Also, a big thank you to my co-authors and the team at Wrox/Wiley for getting a great book out.

Introduction

C# is a relatively new language that was unveiled to the world when Microsoft announced the first version of its .NET Framework in July 2000. Since then its popularity has rocketed, and it has arguably become the language of choice for both Windows and Web developers who use the .NET Framework. Part of the appeal of C# comes from its clear syntax, which derives from C/C++ but simplifies some things that have previously discouraged some programmers. Despite this simplification, C# has retained the power of C++, and there is now no reason not to move into C#. The language is not difficult and it's a great one to learn elementary programming techniques with. This ease of learning, combined with the capabilities of the .NET Framework, make C# an excellent way to start your programming career.

The latest release of C#, C# 4, which is included with version 4 of the .NET Framework, builds on the existing successes and adds even more attractive features. The latest release of Visual Studio (Visual Studio 2010), and the Express line of development tools (including Visual C# 2010 Express) also bring many tweaks and improvements to make your life easier and dramatically increase your productivity.

This book is intended to teach you about all aspects of C# programming, from the language itself, through Windows and Web programming, to making use of data sources, and finally to some new and advanced techniques. You'll also learn about the capabilities of Visual C# 2010 Express, Visual Web Developer 2010 Express, and Visual Studio 2010, and all the ways that these products can aid your application development.

The book is written in a friendly, mentor-style fashion, with each chapter building on previous ones, and every effort is made to ease you into advanced techniques painlessly. At no point will technical terms appear from nowhere to discourage you from continuing; every concept is introduced and discussed as required. Technical jargon is kept to a minimum; but where it is necessary, it too is properly defined and laid out in context.

The authors of this book are all experts in their field, and are all enthusiastic in their passion for both the C# language and the .NET Framework. Nowhere will you find a group of people better qualified to take you under their collective wing and nurture your understanding of C# from first principles to advanced techniques. Along with the fundamental knowledge it provides, this book is packed full of helpful hints, tips, exercises, and full-fledged example code (available for download at p2p.wrox.com) that you will find yourself returning to repeatedly as your career progresses.

We pass this knowledge on without begrudging it, and hope that you will be able to use it to become the best programmer you can be. Good luck, and all the best!

Who This Book Is For

This book is for everyone who wants to learn how to program in C# using the .NET Framework. The early chapters cover the language itself, assuming no prior programming experience. If you have programmed in other languages before, then much of the material in these chapters will be familiar. Many aspects of C# syntax are shared with other languages, and many structures are common to practically all programming languages (such as looping and branching structures). However, even if you are an experienced programmer you will benefit from looking through these chapters to learn the specifics of how these techniques apply to C#.

If you are new to programming, you should start from the beginning. If you are new to the .NET Framework but know how to program, you should read Chapter 1 and then skim through the next few chapters before continuing with the application of the C# language. If you know how to program but haven't encountered an object-oriented programming language before, you should read the chapters from Chapter 8 onward.

Alternatively, if you already know the C# language you may wish to concentrate on the chapters dealing with the most recent .NET Framework and C# language developments, specifically the chapters on collections, generics, and C# 4 language enhancements (Chapters 11 to 14), or skip the first section of the book completely and start with Chapter 15.

The chapters in this book have been written with a dual purpose in mind: They can be read sequentially to provide a complete tutorial in the C# language, and they can be dipped into as required as reference material.

In addition to the core material, starting with Chapter 3 each chapter also includes a selection of exercises at the end, which you can work through to ensure that you have understood the material. The exercises range from simple multiple choice or true/false questions to more complex exercises that require you to modify or build applications. The answers to all the exercises are provided as a download from the book's Web page at www.wrox.com.

What's New in This Edition

This book has been given plenty of love and attention to coincide with the release of C# 4 and .NET 4. Every chapter has been given an overhaul, with less relevant material removed, and new material added. All of the code has been tested against the latest version of the development tools used, and all of the screenshots have been retaken in Windows 7 to provide the most current windows and dialogs.

Although we hate to admit our own fallibility, any errors from previous editions have been fixed, and many other reader comments have been addressed. Hopefully, we haven't introduced many new errors, but any that may have slipped through our web of experts will be corrected online as soon as we find them.

New highlights of this edition include the following:

How This Book Is Structured

This book is divided into six sections:

The following sections describe the chapters in the five major parts of this book.

The C# Language (Chapters 1–14)

Chapter 1 introduces you to C# and how it fits into the .NET landscape. You'll learn the fundamentals of programming in this environment, and how Visual C# 2010 Express (VCE) and Visual Studio 2010 (VS) fit in.

Chapter 2 starts you off with writing C# applications. You'll look at the syntax of C# and put the language to use with sample command-line and Windows applications. These examples will demonstrate just how quick and easy it can be to get up and running, and along the way you'll be introduced to the VCE and VS development environments and the basic windows and tools that you'll be using throughout the book.

Next you'll learn more about the basics of the C# language. You'll learn what variables are and how to manipulate them in Chapter 3. You'll enhance the structure of your applications with flow control (looping and branching) in Chapter 4, and see some more advanced variable types such as arrays in Chapter 5. In Chapter 6 you'll start to encapsulate your code in the form of functions, which make it much easier to perform repetitive operations and make your code much more readable.

By the beginning of Chapter 7 you'll have a handle on the fundamentals of the C# language, and will focus on debugging your applications. This involves looking at outputting trace information as your applications are executed, and at how VS can be used to trap errors and lead you to solutions for them with its powerful debugging environment.

From Chapter 8 onward you'll learn about object-oriented programming (OOP), starting with a look at what this term means, and an answer to the eternal question “What is an object?” OOP can seem quite difficult at first. The whole of Chapter 8 is devoted to demystifying it and explaining what makes it so great, and you won't actually deal with much C# code until the very end of the chapter.

Everything changes in Chapter 9, when you put theory into practice and start using OOP in your C# applications. This is where the true power of C# lies. You'll start by looking at how to define classes and interfaces, and then move on to class members (including fields, properties, and methods) in Chapter 10. At the end of that chapter you'll start to assemble a card game application, which is developed over several chapters, and will help to illustrate OOP.

Once you've learned how OOP works in C#, Chapter 11 moves on to look at common OOP scenarios, including dealing with collections of objects, and comparing and converting objects. Chapter 12 takes a look at a very useful feature of C# that was introduced in .NET 2.0: generics, which enables you to create very flexible classes. Next, Chapter 13 continues the discussion of the C# language and OOP with some additional techniques, notably events, which become very important in, for example, Windows programming. Finally, Chapter 14 focuses on C# language features that were introduced with versions 3.0 and 4 of the language.

Windows Programming (Chapters 15–17)

Chapter 15 starts by introducing you to what is meant by Windows programming, and looks at how this is achieved in VCE and VS. Again, you'll start with the basics and build up your knowledge in both this chapter and Chapter 16, which demonstrates how you can use the wealth of controls supplied by the .NET Framework in your applications. You'll quickly understand how .NET enables you to build Windows applications in a graphical way, and assemble advanced applications with the minimum of effort and time.

Chapter 17 discusses how to deploy your applications, including how to make installation programs that enable your users to get up and running with your applications in double-quick time.

Web Programming (Chapters 18–20)

This section is structured in a similar way to the Windows programming section. It starts with Chapter 18, which describes the controls that make up the simplest of Web applications, and how you can fit them together and make them perform tasks using ASP.NET. The chapter then moves on to look at more advanced techniques, ASP.NET AJAX, versatile controls, and state management in the context of the Web, as well as how to conform to Web standards.

Chapter 19 is an excursion into the wonderful world of Web services, which provide programmatic access to information and capabilities across the Internet. Web services enable you to expose complex data and functionality to Web and Windows applications in a platform-independent way. This chapter discusses how to use and create Web services, and the additional tools that .NET provides, including security.

Finally, Chapter 20 examines the deployment of Web applications and services, in particular the features of VS and VWD that enable you to publish applications to the Web with the click of a button.

Data Access (Chapters 21–24)

Chapter 21 looks at how your applications can save and retrieve data to disk, both as simple text files and as more complex representations of data. You'll also learn how to compress data, how to work with legacy data such as comma-separated value (CSV) files, and how to monitor and act on file system changes.

In Chapter 22 you'll learn about the de facto standard for data exchange—namely, XML. By this point in the book, you'll have touched on XML several times in preceding chapters, but this chapter lays out the ground rules and shows you what all the excitement is about.

The remainder of this part looks at LINQ, which is a query language built in to the latest versions of the .NET Framework. You start in Chapter 23 with a general introduction to LINQ, and then you will use LINQ to access a database and other data in Chapter 24.

Additional Techniques (Chapters 25–27)

Finally, in this part of the book you will look at some exciting new technologies that have emerged with the most recent .NET Framework releases. In Chapter 25 you will get to play with Windows Presentation Foundation (WPF) and see how it promises enormous changes to both Windows and Web development. Chapter 26 looks at Windows Communication Foundation (WCF), which extends and enhances the concept of Web services to an enterprise-level communication technology. The last chapter of the book, Chapter 27, looks at Windows Workflow Foundation (WF). WF enables you to implement workflow functionality in your applications, meaning you can define operations that are performed in a specific order controlled by external interactions, which is very useful for many types of applications.

What You Need to Use This Book

The code and descriptions of C# and the .NET Framework in this book apply to .NET 4. You don't need anything other than the Framework to understand this aspect of the book, but many of the examples require a development tool. This book uses Visual C# 2010 Express as its primary development tool, although some chapters use Visual Web Developer 2010 Express. In addition, some functionality is available only in Visual Studio 2010, which is noted where appropriate.

Conventions

To help you get the most from the text and keep track of what's happening, we've used a number of conventions throughout the book.

warning

Warning

Boxes with this icon hold important, not-to-be forgotten information that is directly relevant to the surrounding text.

note

Note

Notes, tips, hints, tricks, and asides to the current discussion are accompanied by this icon treatment.

As for styles in the text:

We use a monofont type with no highlighting for most code examples.
We use bolded monofont to emphasize code that is of particular importance in
the present context.

Source Code

As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All of the source code used in this book is available for download at www.wrox.com. Once at the site, simply locate the book's title (either by using the Search box or by using one of the title lists) and click the Download Code link on the book's detail page to obtain all the source code for the book.

download

Code snippets that are downloadable from wrox.com are easily identified with an icon; the filename of the code snippet follows in a code note that appears after the code, much like the one that follows this paragraph. If it is an entire code listing, the filename should appear in the listing title.

Code snippet filename

note

Note

Because many books have similar titles, you may find it easiest to search by ISBN; this book's ISBN is 978-0-470-50226-6.

Once you download the code, just decompress it with your favorite compression tool. Alternately, you can go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.

Errata

Every effort is made to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, such as a spelling mistake or a faulty piece of code, your feedback is welcome. By sending in errata, you might save another reader hours of frustration, and at the same time you will help us provide even higher quality information.

To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view all errata that has been submitted for this book and posted by Wrox editors. A complete book list, including links to each book's errata, is also available at www.wrox.com/misc-pages/booklist.shtml.

If you don't spot “your” error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. Once the information is checked, a message is posted to the book's errata page and the problem is fixed in subsequent editions of the book.

p2p.wrox.com

For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a Web-based system for you to post messages relating to Wrox books and related technologies and to interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.

At http://p2p.wrox.com you will find a number of different forums that will help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps:

1. Go to p2p.wrox.com and click the Register link.

2. Read the terms of use and click Agree.

3. Complete the required information to join as well as any optional information you wish to provide and click Submit.

4. You will receive an e-mail with information describing how to verify your account and complete the joining process.

note

Note

You can read messages in the forums without joining P2P but in order to post your own messages, you must join.

Once you join, you can post new messages and respond to messages other users post. You can read messages at any time on the Web. If you would like to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.

For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.

Part I

The C# Language

Chapter 1: Introducing C#

Chapter 2: Writing a C# Program

Chapter 3: Variables and Expressions

Chapter 4: Flow Control

Chapter 5: More About Variables

Chapter 6: Functions

Chapter 7: Debugging and Error Handling

Chapter 8: Introduction to Object-Oriented Programming

Chapter 9: Defining Classes

Chapter 10: Defining Class Members

Chapter 11: Collections, Comparisons, and Conversions

Chapter 12: Generics

Chapter 13: Additional OOP Techniques

Chapter 14: C# Language Enhancements