Contents

Introduction

Part I: The C# Language

Chapter 1: .NET Architecture

The Relationship of C# to .NET

The Common Language Runtime

A Closer Look at Intermediate Language

Assemblies

.NET Framework Classes

Namespaces

Creating .NET Applications Using C#

The Role of C# in the .NET Enterprise Architecture

Summary

Chapter 2: C# Basics

Before We Start

Your First C# Program

Variables

Predefined Data Types

Flow Control

Enumerations

Arrays

Namespaces

The Main() Method

More on Compiling C# Files

Console I/O

Using Comments

The C# Preprocessor Directives

C# Programming Guidelines

Summary

Chapter 3: Objects and Types

Classes and Structs

Class Members

Anonymous Types

Structs

Partial Classes

Static Classes

The Object Class

Extension Methods

Summary

Chapter 4: Inheritance

Types of Inheritance

Implementation Inheritance

Modifiers

Interfaces

Summary

Chapter 5: Arrays

Simple Arrays

Multidimensional Arrays

Jagged Arrays

Array Class

Array and Collection Interfaces

Enumerations

Summary

Chapter 6: Operators and Casts

Operators

Type Safety

Comparing Objects for Equality

Operator Overloading

User-Defined Casts

Summary

Chapter 7: Delegates and Events

Delegates

Events

Summary

Chapter 8: Strings and Regular Expressions

System.String

Regular Expressions

Summary

Chapter 9: Generics

Overview

Creating Generic Classes

Generic Classes’ Features

Generic Interfaces

Generic Methods

Generic Delegates

Other Generic Framework Types

Summary

Chapter 10: Collections

Collection Interfaces and Types

Lists

Queues

Stacks

Linked Lists

Sorted Lists

Dictionaries

HashSet

Bit Arrays

Performance

Summary

Chapter 11: Language Integrated Query

LINQ Overview

Standard Query Operators

Expression Trees

LINQ Providers

Summary

Chapter 12: Memory Management and Pointers

Memory Management Under the Hood

Freeing Unmanaged Resources

Unsafe Code

Summary

Chapter 13: Reflection

Custom Attributes

Reflection

Summary

Chapter 14: Errors and Exceptions

Exception Classes

Catching Exceptions

User-Defined Exception Classes

Summary

Part II: Visual Studio

Chapter 15: Visual Studio 2008

Working with Visual Studio 2008

Refactoring

Multi-Targeting

WPF, WCF, WF, and More

Summary

Chapter 16: Deployment

Designing for Deployment

Deployment Options

Deployment Requirements

Deploying the .NET Runtime

Simple Deployment

Installer Projects

ClickOnce

Summary

Part III: Base Class Libraries

Chapter 17: Assemblies

What Are Assemblies?

Creating Assemblies

Dynamic Loading and Creating Assemblies

Application Domains

Shared Assemblies

Configuring .NET Applications

Versioning

Summary

Chapter 18: Tracing and Events

Tracing

Event Logging

Performance Monitoring

Summary

Chapter 19: Threading and Synchronization

Overview

Asynchronous Delegates

The Thread Class

Thread Pools

Threading Issues

Synchronization

Timers

COM Apartments

Event-Based Asynchronous Pattern

Summary

Chapter 20: Security

Authentication and Authorization

Encryption

Access Control to Resources

Code Access Security

Managing Security Policies

Summary

Chapter 21: Localization

Namespace System.Globalization

Resources

Windows Forms Localization Using Visual Studio

Localization with ASP.NET

Localization with WPF

A Custom Resource Reader

Creating Custom Cultures

Summary

Chapter 22: Transactions

Overview

Database and Entity Classes

Traditional Transactions

System.Transactions

Isolation Level

Custom Resource Managers

Transactions with Windows Vista and Windows Server 2008

Summary

Chapter 23: Windows Services

What Is a Windows Service?

Windows Services Architecture

System.ServiceProcess Namespace

Creating a Windows Service

Monitoring and Controlling the Service

Troubleshooting

Power Events

Summary

Chapter 24: Interoperability

.NET and COM

Marshaling

Using a COM Component from a .NET Client

Using a .NET Component from a COM Client

Platform Invoke

Summary

Part IV: Data

Chapter 25: Manipulating Files and the Registry

Managing the File System

Moving, Copying, and Deleting Files

Reading and Writing to Files

Reading Drive Information

File Security

Reading and Writing to the Registry

Reading and Writing to Isolated Storage

Summary

Chapter 26: Data Access

ADO.NET Overview

Using Database Connections

Commands

Fast Data Access: The Data Reader

Managing Data and Relationships: The DataSet Class

XML Schemas: Generating Code with XSD

Populating a DataSet

Persisting DataSet Changes

Working with ADO.NET

Summary

Chapter 27: LINQ to SQL

LINQ to SQL and Visual Studio 2008

How Objects Map to LINQ Objects

Working Without the O/R Designer

Custom Objects and the O/R Designer

Querying the Database

Stored Procedures

Summary

Chapter 28: Manipulating XML

XML Standards Support in .NET

Introducing the System.Xml Namespace

Using System.Xml Classes

Reading and Writing Streamed XML

Using the DOM in .NET

Using XPathNavigators

XML and ADO.NET

Serializing Objects in XML

Summary

Chapter 29: LINQ to XML

LINQ to XML and .NET 3.5

New XML Objects from the .NET Framework 3.5

Using LINQ to Query XML Documents

Working Around the XML Document

Using LINQ to SQL with LINQ to XML

Summary

Chapter 30: .NET Programming with SQL Server

.NET Runtime Host

Microsoft.SqlServer.Server

User-Defined Types

Stored Procedures

User-Defined Functions

Triggers

XML Data Type

Summary

Part V: Presentation

Chapter 31: Windows Forms

Creating a Windows Form Application

Control Class

Standard Controls and Components

Forms

Summary

Chapter 32: Data Binding

The DataGridView Control

DataGridView Class Hierarchy

Data Binding

Visual Studio .NET and Data Access

Summary

Chapter 33: Graphics with GDI+

Understanding Drawing Principles

Measuring Coordinates and Areas

A Note About Debugging

Drawing Scrollable Windows

World, Page, and Device Coordinates

Colors

The Safety Palette

Pens and Brushes

Drawing Shapes and Lines

Displaying Images

Issues When Manipulating Images

Drawing Text

Simple Text Example

Fonts and Font Families

Example: Enumerating Font Families

Editing a Text Document: The CapsEditor Sample

Printing

Summary

Chapter 34: Windows Presentation Foundation

Overview

Shapes

Transformation

Brushes

Controls

Layout

Event Handling

Styles, Templates, and Resources

Summary

Chapter 35: Advanced WPF

Data Binding

Command Bindings

Animations

Adding 3-D Features in WPF

Windows Forms Integration

WPF Browser Application

Summary

Chapter 36: Add-Ins

System.AddIn Architecture

Add-In Sample

Summary

Chapter 37: ASP.NET Pages

ASP.NET Introduction

ASP.NET Web Forms

ADO.NET and Data Binding

Application Configuration

Summary

Chapter 38: ASP.NET Development

User and Custom Controls

Master Pages

Site Navigation

Security

Themes

Web Parts

Summary

Chapter 39: ASP.NET AJAX

What Is Ajax?

What Is ASP.NET AJAX?

Using ASP.NET AJAX

Summary

Chapter 40: Visual Studio Tools for Office

VSTO Overview

VSTO Fundamentals

Building VSTO Solutions

Example Application

VBA Interoperability

Summary

Part VI: Communication

Chapter 41: Accessing the Internet

The WebClient Class

WebRequest and WebResponse Classes

Displaying Output as an HTML Page

Utility Classes

Lower-Level Protocols

Summary

Chapter 42: Windows Communication Foundation

WCF Overview

Simple Service and Client

Contracts

Service Implementation

Binding

Hosting

Clients

Duplex Communication

Summary

Chapter 43: Windows Workflow Foundation

Hello World

Activities

Custom Activities

Workflows

The Workflow Runtime

Workflow Services

Integration with Windows Communication Foundation

Hosting Workflows

The Workflow Designer

Summary

Chapter 44: Enterprise Services

Overview

Creating a Simple COM+ Application

Deployment

Component Services Explorer

Client Application

Transactions

Sample Application

Integrating WCF and Enterprise Services

Summary

Chapter 45: Message Queuing

Overview

Message Queuing Products

Message Queuing Architecture

Message Queuing Administrative Tools

Programming Message Queuing

Course Order Application

Receiving Results

Transactional Queues

Message Queuing with WCF

Message Queue Installation

Summary

Chapter 46: Directory Services

The Architecture of Active Directory

Administration Tools for Active Directory

Programming Active Directory

Searching for User Objects

Account Management

DSML

Summary

Chapter 47: Peer-to-Peer Networking

Peer-to-Peer Networking Overview

Microsoft Windows Peer-to-Peer Networking

Building P2P Applications

Summary

Chapter 48: Syndication

Overview of System.Servicemodel.Syndication

Syndication Reader

Offering Syndication Feeds

Summary

Part VII: Appendices

Appendix A: ADO.NET Entity Framework

Appendix B: C#, Visual Basic, and C++/CLI

Appendix C: Windows Vista and Windows Server 2008

Index

Professional C# 2008

Published by

Wiley Publishing, Inc.

10475 Crosspoint Boulevard

Indianapolis, IN 46256

www.wiley.com

Copyright © 2008 by Wiley Publishing, Inc., Indianapolis, Indiana

Published simultaneously in Canada

ISBN: 978-0-470-19137-8

Library of Congress Cataloging-in-Publication Data is available from the publisher.

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permissions.

Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Website is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Website may provide or recommendations it may make. Further, readers should be aware that Internet Websites listed in this work may have changed or disappeared between when this work was written and when it is read.

For general information on our other products and services please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. All other trademarks are the property of their respective owners. Wiley Publishing, Inc. is not associated with any product or vendor mentioned in this book.

Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.

To my brother George – moving strong from basketball to coding (they’re practically the same thing, aren’t they?). Congrats and keep moving forward in C# land!

—Bill Evjen

for Donna

—Karli Watson

To my parents, Joan and Donald Skinner, for their ever present love, support, and encouragement. The world was made a sweeter place by their being in it and their memory will be cherished forever. Thanks Mum & Dad — you were brilliant.

“Love is as strong as death. Many waters cannot quench love, neither can the floods drown it.” (Song of Songs 8: 6-7)

—Morgan Skinner

About the Authors

Christian Nagel of thinktecture is a software architect and developer who offers training and consulting on how to design and develop Microsoft .NET solutions. He looks back on more than 20 years of software development experience. Christian started his computing career with PDP 11 and VAX/VMS platforms, covering a variety of languages and platforms. Since the year 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 for ASP.NET. Christian speaks at international conferences such as TechEd and Tech Days, and supports .NET user groups with INETA Europe. You can contact Christian via his Web sites, www.christiannagel.com and www.thinktecture.com.

Bill Evjen, Microsoft MVP is an active proponent of .NET Technologies and community-based learning initiatives for .NET. He has been actively involved with .NET since the first bits were released in 2000. In the same year, Bill founded the St. Louis .NET User Group (www.stlnet.org), one of the world’s first such groups. Bill is also the founder and former executive director of the International .NET Association (www.ineta.org), which represents more than 450,000 members worldwide.

Based in St. Louis, Missouri, Bill is an acclaimed author (more than 15 books to date) and speaker on ASP.NET and SML Web services. In addition to writing and speaking at conferences such as DevConnections, VSLive, and TechEd, Bill works closely with Microsoft as a Microsoft regional director. Bill is the technical architect for Lipper (www.lipperweb.com), a wholly owned subsidiary of Reuters, the international news and financial services company. He graduated from Western Washington University in Bellingham, Washington with a Russian language degree. When he isn’t tinkering on the computer, he can usually be found at his summer house in Toivakka, Finland. You can reach Bill at evjen@yahoo.cpm.

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#. You can reach Morgan at www.morganskinner.com.

Jay Glynn started writing software nearly 20 years ago, writing applications for the PICK operating system using PICK basic. Since then, he has created software using Paradox PAL and Object PAL, Delphi, VBA, Visual Basic, C, C++, Java, and of course, C#. He is currently a project coordinator and architect for a large financial services company in Nashville, Tennessee, working on software for the TabletPC platform. You can contact Jay at jlsglynn@hotmail.com.

Karli Watson is a freelance author and a technical consultant of 3form Ltd (www.3form.net) and Boost .net, and an associate technologist at Content Master (www.contentmaster.com). He started out with the intention of becoming a world-famous nanotechnologist, so perhaps one day you might recognize his name as he receives a Nobel Prize. For now, though, Karli’s main academic interest is the .NET Framework, and all the boxes of tricks it contains. A snowboarding enthusiast, Karli also loves cooking, spends far too much time playing Anarchy Online and EVE, and wishes he had a cat. As yet, nobody has seen fit to publish Karli’s first novel, but the rejection letters make an attractive pile. If he ever puts anything up there, you can visit Karli online at http://www.karliwatson.com.

Credits

Acquisitions Editor

Katie Mohr

Development Editors

Ami Frank Sullivan

Lori Cerreto

Technical Editors

Michael Erickson

Doug Holland

Production Editor

Daniel Scribner

Copy Editor

Kim Cofer

Nancy Rapaport

Editorial Manager

Mary Beth Wakefield

Production Manager

Tim Tate

Vice President and Executive Group Publisher

Richard Swadley

Vice President and Executive Publisher

Joseph B. Wikert

Project Coordinator, Cover

Lynsey Stanford

Proofreaders

Word One:

Edward Moyer

Jen Larsen

Amy Rasmussen

Corina Copp

Scott Klemp

Joshua Chase

Indexer

Ron Strauss

Acknowledgments

Bill Evjen:

The .NET Framework 3.5 release came quickly for us writers and it wouldn’t have been possible to produce this book as fast as they came out if it weren’t for the dedication of the teams built for it. Tremendous thanks to Katie Mohr for being more than patient with me in getting this and some other .NET 3.5 books out the door. Also, big thanks go out to Ami Sullivan for getting at me and helping me be somewhat on schedule. Other big thanks go to all the editors of the book including Lori Cerreto, Daniel Scribner, and the copyeditors.

Finally, to the ones that paid the biggest price for this writing session — my wife, Tuija, and the three kids: Sofia, Henri, and Kalle. Thanks for all you do!

Karli Watson:

Thanks to all at Wiley for helping me through this project and reigning in my strange British stylings, to assorted clients for giving me the time to write, and to Donna for keeping me sane and coping with my temperamental back. Thanks also to friends and family for being patient with my deadline-laden lifestyle.

Introduction

If we were to describe the C# language and its associated environment, the .NET Framework, as the most important new technology for developers for many years, we would not be exaggerating. .NET is designed to provide a new environment within which you can develop almost any application to run on Windows, whereas C# is a new programming language that has been designed specifically to work with .NET. Using C# you can, for example, write a dynamic Web page, an XML Web service, a component of a distributed application, a database access component, a classic Windows desktop application, or even a new smart client application that allows for online/offline capabilities. This book covers the .NET Framework 3.5. If you are coding using version 1.0, 1.1, 2.0, or even 3.0, there may be sections of the book that will not work for you. We try to notify you of items that are new to the .NET Framework 3.5 specifically.

Don’t be fooled by the .NET label. The NET bit in the name is there to emphasize Microsoft’s belief that distributed applications, in which the processing is distributed between client and server, are the way forward, but C# is not just a language for writing Internet or network-aware applications. It provides a means for you to code up almost any type of software or component that you might need to write for the Windows platform. Between them, C# and .NET are set both to revolutionize the way that you write programs, and to make programming on Windows much easier than it has ever been.

That’s quite a substantial claim, and it needs to be justified. After all, we all know how quickly computer technology changes. Every year Microsoft brings out new software, programming tools, or versions of Windows, with the claim that these will be hugely beneficial to developers. So what’s different about .NET and C#?

The Significance of .NET and C#

In order to understand the significance of .NET, it is useful to remind ourselves of the nature of many of the Windows technologies that have appeared in the past 10 years or so. Although they may look quite different on the surface, all of the Windows operating systems from Windows 3.1 (introduced in 1992) through Windows Server 2008 have the same familiar Windows API at their core. As we’ve progressed through new versions of Windows, huge numbers of new functions have been added to the API, but this has been a process of evolving and extending the API rather than replacing it.

The same can be said for many of the technologies and frameworks that we’ve used to develop software for Windows. For example, COM (Component Object Model) originated as OLE (Object Linking and Embedding). At the time, it was, to a large extent, simply a means by which different types of Office documents could be linked, so that, for example, you could place a small Excel spreadsheet in your Word document. From that it evolved into COM, DCOM (Distributed COM), and eventually COM+ — a sophisticated technology that formed the basis of the way almost all components communicated, as well as implementing transactions, messaging services, and object pooling.

Microsoft chose this evolutionary approach to software for the obvious reason that it is concerned about backward compatibility. Over the years, a huge base of third-party software has been written for Windows, and Windows wouldn’t have enjoyed the success it has had if every time Microsoft introduced a new technology it broke the existing code base!

Although backward compatibility has been a crucial feature of Windows technologies and one of the strengths of the Windows platform, it does have a big disadvantage. Every time some technology evolves and adds new features, it ends up a bit more complicated than it was before.

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!