image

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: Core C#

Your First C# Program

Variables

Predefined Data Types

Flow Control

Enumerations

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

Classes

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: Generics

Generics Overview

Creating Generic Classes

Generics Features

Generic Interfaces

Generic Structs

Generic Methods

Summary

Chapter 6: Arrays and Tuples

Simple Arrays

Multidimensional Arrays

Jagged Arrays

Array Class

Arrays as Parameters

Enumerations

Tuples

Structural Comparison

Summary

Chapter 7: Operators and Casts

Operators

Type Safety

Comparing Objects for Equality

Operator Overloading

User-Defined Casts

Summary

Chapter 8: Delegates, Lambdas, and Events

Delegates

Lambda Expressions

Events

Summary

Chapter 9: Strings and Regular Expressions

Examining System.String

Regular Expressions

Summary

Chapter 10: Collections

Collection Interfaces and Types

Lists

Queue

Stack

Linked List

Sorted List

Dictionaries

Sets

Observable Collection

Bit Arrays

Concurrent Collections

Performance

Summary

Chapter 11: Language Integrated Query

LINQ Overview

Standard Query Operators

Parallel LINQ

Expression Trees

LINQ Providers

Summary

Chapter 12: Dynamic Language Extensions

Dynamic Language Runtime

The Dynamic Type

Hosting the DLR ScriptRuntime

DynamicObject and ExpandoObject

Summary

Chapter 13: Memory Management and Pointers

Memory Management Under the Hood

Freeing Unmanaged Resources

Unsafe Code

Summary

Chapter 14: Reflection

Custom Attributes

Using Reflection

Summary

Chapter 15: Errors and Exceptions

Exception Classes

Catching Exceptions

User-Defined Exception Classes

Summary

Part II: Visual Studio

Chapter 16: Visual Studio 2010

Working with Visual Studio 2010

Refactoring Tools

Multi-Targeting the .NET Framework

WPF, WCF, WF, and More

Summary

Chapter 17: Deployment

Planning for Deployment

Simple Deployment Options

Visual Studio 2010 Setup and Deployment Projects

ClickOnce

Visual Studio 2010 Editors

Summary

Part III: Foundation

Chapter 18: Assemblies

What Are Assemblies?

Creating Assemblies

Application Domains

Shared Assemblies

Configuring .NET Applications

Versioning

Summary

Chapter 19: Instrumentation

Code Contracts

Tracing

Event Logging

Performance Monitoring

Summary

Chapter 20: Threads, Tasks, and Synchronization

Overview

Asynchronous Delegates

The Thread Class

Thread Pools

Tasks

Parallel Class

Cancellation Framework

Threading Issues

Synchronization

Timers

Event-Based Asynchronous Pattern

Summary

Chapter 21: Security

Authentication and Authorization

Encryption

Access Control to Resources

Code Access Security

Distributing Code Using Certificates

Summary

Chapter 22: 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 23: System.Transactions

Overview

Database and Entity Classes

Traditional Transactions

System.Transactions

Isolation Level

Custom Resource Managers

Transactions with Windows 7 and Windows Server 2008

Summary

Chapter 24: Networking

The WebClient Class

WebRequest and WebResponse Classes

Displaying Output as an HTML Page

Utility Classes

Lower-Level Protocols

Summary

Chapter 25: Windows Services

What Is a Windows Service?

Windows Services Architecture

Creating a Windows Service Program

Monitoring and Controlling Windows Services

Troubleshooting and Event Logging

Summary

Chapter 26: Interop

.NET and COM

Using a COM Component from a .NET Client

Using a .NET Component from a COM Client

Platform Invoke

Summary

Chapter 27: Core XAML

Overview

Dependency Properties

Bubbling and Tunneling Events

Attached Properties

Markup Extensions

Reading and Writing XAML

Summary

Chapter 28: Managed Extensibility Framework

MEF Architecture

Contracts

Exports

Imports

Containers and Export Providers

Catalogs

Summary

Chapter 29: Manipulating Files and the Registry

Managing the File System

Moving, Copying, and Deleting Files

Reading and Writing to Files

Mapped Memory Files

Reading Drive Information

File Security

Reading and Writing to the Registry

Reading and Writing to Isolated Storage

Summary

PART IV: Data

Chapter 30: Core ADO.NET

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 31: ADO.NET Entity Framework

Overview of the ADO.NET Entity Framework

Entity Framework Mapping

Entity Client

Entities

Object Context

Relationships

Object Query

Updates

LINQ to Entities

Summary

Chapter 32: Data Services

Overview

Custom Hosting with CLR Objects

HTTP Client Application

Queries with URLs

Using WCF Data Services with the ADO.NET Entity Framework

Summary

Chapter 33: 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

LINQ to XML and .NET

Working with Different XML Objects

Using LINQ to Query XML Documents

More Query Techniques for XML Documents

Summary

Chapter 34: .NET Programming With SQL Server

.NET Runtime Host

Microsoft.SqlServer.Server

User-Defined Types

User-Defined Aggregates

Stored Procedures

User-Defined Functions

Triggers

XML Data Type

Summary

Part V: Presentation

Chapter 35: Core WPF

Overview

Shapes

Geometry

Transformation

Brushes

Controls

Layout

Styles and Resources

Triggers

Templates

Animations

Visual State Manager

3-D

Summary

Chapter 36: Business Applications With WPF

Data Binding

Commanding

TreeView

DataGrid

Summary

Chapter 37: Creating Documents with WPF

Text Elements

Flow Documents

Fixed Documents

XPS Documents

Printing

Summary

Chapter 38: Silverlight

Comparing WPF and Silverlight

Creating a Silverlight Project

Navigation

Networking

Browser Integration

Silverlight Out-of-Browser Applications

Summary

Chapter 39: Windows Forms

Creating a Windows Forms Application

Control Class

Standard Controls and Components

Forms

Summary

Chapter 40: Core ASP.NET

ASP.NET Introduction

ASP.NET Web Forms

ADO.NET and Data Binding

Application Configuration

Summary

Chapter 41: ASP.NET Features

User and Custom Controls

Master Pages

Site Navigation

Security

Themes

Web Parts

ASP.NET AJAX

What Is Ajax?

Summary

Chapter 42: ASP.NET Dynamic Data and MVC

Routing

Dynamic Data

MVC

Summary

Part VI: Communication

Chapter 43: Windows Communication Foundation

WCF Overview

Simple Service and Client

Contracts

Service Implementation

Binding

Hosting

Clients

Duplex Communication

Summary

Chapter 44: Windows Workflow Foundation 4

Hello World

Activities

Custom Activities

Workflows

Summary

Chapter 45: Peer-to-Peer Networking

Peer-to-Peer Networking Overview

Microsoft Windows Peer-to-Peer Networking

Building P2P Applications

Summary

Chapter 46: 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 47: Syndication

Overview of System.ServiceModel.Syndication

Reading Syndication Feeds Sample

Offering Syndication Feeds Sample

Summary

Appendix: Guidelines for Windows 7 and Windows Server 2008 R2

Index

Online Chapters

Chapter 48: Graphics With GDI+

Understanding Drawing Principles

Measuring Coordinates and Areas

Drawing Scrollable Windows

World, Page, and Device Coordinates

Colors

Pens and Brushes

Drawing Shapes and Lines

Displaying Images

Issues When Manipulating Images

Drawing Text

Simple Text Example

Fonts and Font Families

Enumerating Font Families Example

Editing a Text Document: The CapsEditor Example

Printing

Summary

Chapter 49: Visual Studio Tools For Office

VSTO Overview

VSTO Project Fundamentals

Building VSTO Solutions

Example Application

Summary

Chapter 50: Managed Add-In Framework

MAF Architecture

Add-In Sample

Summary

Chapter 51: Enterprise Services

Using Enterprise Services

Creating a Simple COM+ Application

Deployment

Component Services Explorer

Client Application

Transactions

Sample Application

Integrating WCF and Enterprise Services

Summary

Chapter 52: Directory Services

The Architecture of Active Directory

Administration Tools for Active Directory

Programming Active Directory

Searching for User Objects

Account Management

DSML

Summary

Chapter 53: C#, Visual Basic, C++/CLI, and F#

Namespaces

Defining Types

Methods

Static Members

Arrays

Control Statements

Loops

Exception Handling

Inheritance

Resource Management

Delegates

Events

Generics

LINQ Queries

C++/CLI Mixing Native and Managed Code

C# Specifics

Summary

Chapter 54: .NET Remoting

Why Use .NET Remoting?

.NET Remoting Terms Explained

Contexts

Remote Objects, Clients, and Servers

.NET Remoting Architecture

Configuration Files

Hosting Servers in ASP.NET

Classes, Interfaces, and Soapsuds

Asynchronous Remoting

Security with .NET Remoting

Remoting and Events

Call Contexts

Summary

Chapter 55: Web Services with ASP.NET

SOAP

WSDL

Web Services

Extending the Event-Booking Example

Exchanging Data Using SOAP Headers

Summary

Chapter 56: LINQ to SQL

LINQ to SQL Using Visual Studio 2010

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 57: Windows Workflow Foundation 3.0

Hello World

Activities

Custom Activities

Workflows

The Workflow Runtime

Workflow Services

Integration with Windows Communication Foundation

Hosting Workflows

The Workflow Designer

Moving from WF 3.x to WF 4

Summary

Image

Professional C# 4 and .NET 4

Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com

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

Published simultaneously in Canada

ISBN: 978-0-470-50225-9

Manufactured in the United States of America

10 9 8 7 6 5 4 3 2 1

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 Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, 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 Web site 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 Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites 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 (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

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

Library of Congress Control Number: 2009942439

Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, 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.

To my two girls, Angela and Stephanie

The first half of the year 2009 was the hardest time in my life — a trip through hell and back. I cannot thank Angela enough for all her love and support she gave to me. Without her I couldn’t have made it through that. Stephanie was born shortly after medical treatment and was the biggest motivation during that time.

I love you both!

—CHRISTIAN NAGEL

 

To Tuija, always.

—BILL EVJEN

 

For donna

—KARLI WATSON

 

Dedicated to my parents, Joan & Donald Skinner.

There are many things that I’d like to say to my Mum and Dad, but I’m in the privileged position of not needing to say anything to them. They were both wonderful people, are greatly missed, and the world was made a sweeter place by their being in it. Thanks Mum, thanks Dad, you were brilliant.

—MORGAN SKINNER

ABOUT THE AUTHORS

Image

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.

Image

BILL EVJEN 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 500,000 members worldwide.

Based in St. Louis, Missouri, Bill is an acclaimed author and speaker on ASP.NET and Web Services. He has authored or coauthored more than 20 books including Professional ASP.NET 4, Professional VB 2008, ASP.NET Professional Secrets, XML Web Services for ASP.NET, and Web Services Enhancements: Understanding the WSE for Enterprise Applications (all published by Wiley). In addition to writing, Bill is a speaker at numerous conferences, including DevConnections, VSLive, and TechEd. Along with these activities, Bill works closely with Microsoft as a Microsoft Regional Director and an MVP.

Bill is the Global Head of Platform Architecture for Thomson Reuters, Lipper, the international news and financial services company (www.thomsonreuters.com). 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 on Twitter at @billevjen.

Image

JAY GLYNN is the Principle Architect at PureSafety, a leading provider of results-driven software and information solutions for workforce safety and health. Jay has been developing software for over 25 years and has worked with a variety of languages and technologies including PICK Basic, C, C++, Visual Basic, C# and Java. Jay currently lives in Franklin, Tennessee with his wife and son.

Image

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. 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 round to making himself a web site.

Image

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.

 

ABOUT THE TECHNICAL EDITORS

ALEXEI GORKOV is the chief software engineer at EPAM Systems (www.epam.com), a leading software development outsourcing company in Central and Eastern Europe. He has worked with .NET since 2004 and as a front-end developer involved in development of web portals and line-of-business web applications using Microsoft technologies. Over the past four years, he has edited more than a dozen programming books from Wiley Publishing on ASP.NET, Ajax, JavaScript, CSS and XML. He lives in Saratov, Russia.

MITCHEL SELLERS is the CEO of IowaComputerGurus Inc. His extensive experience in software development has lead to a focus on proper architecture, performance, stability, and overall cost effectiveness of delivered solutions. He is the author of Professional DotNetNuke Module Programming and many technical articles, and is currently working on his next book, Visual Studio 2010 and .NET 4 Six-in-One, scheduled for publication by Wiley in early 2010. He is a regular speaker at user groups and conferences.

Mitchel is a Microsoft C# MVP and a Microsoft Certified Professional, an active participant in the .NET and DotNetNuke development communities, and a DotNetNuke Core Team member. For more information, see his resume at MitchelSellers.com.

CREDITS

ACQUISITIONS EDITOR
Paul Reese

PROJECT EDITOR
Sara Shlaer

DEVELOPMENT EDITOR
Susan Cohen

TECHNICAL EDITORS
Alexei Gorkov
Mitchel Sellers

PRODUCTION EDITOR
Kathleen Wisor

COPY EDITORS
Tricia Liebig
Foxxe Editorial Services

EDITORIAL DIRECTOR
Robyn B. Siesky

EDITORIAL MANAGER
Mary Beth Wakefield

MARKETING MANAGER
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
Word One New York

INDEXER
Robert Swanson

COVER DESIGNER
Michael E. Trent

COVER IMAGE
© Punchstock/Corbis

ACKNOWLEDGMENTS

 

THANKS TO ALL AT WILEY for your patience when I started working later on the book than I had expected and planned. Special thanks to Sara Shlaer who was of great support with the time pressure and the change of the Wrox style. Similar to the authors, she worked many weekends to get the book out on time. Many thanks!

—CHRISTIAN NAGEL

 

THANKS TO SARA SHLAER, Paul Reese, and Jim Minatel for the opportunity to work on such a great book, and to the technical editors, Alexei Gorkov and Mitchel Sellers, for their excellent work. In addition to my co-authors, I would like to thank my family for putting up with all the writing. Thank you Tuija, Sofia, Henri, and Kalle!

—BILL EVJEN

 

I WOULD LIKE TO THANK Sara Shlaer, Paul Reese, and the rest of the team at Wrox for all the help they provided. I would also like to thank my wife and son for putting up with the nights and weekends lost to the computer. They are my inspiration.

—JAY GLYNN

 

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 Sara Shlaer — one of the best and friendliest editors I’ve had the pleasure to work with. Also, thanks to friends, family, and work colleagues for understanding why I haven’t had time for much socializing lately, and to donna, as always, for all her support and for putting up with all the late nights.

—KARLI WATSON

INTRODUCTION

 

 

IF WE WERE TO DESCRIBE THE C# LANGUAGE AND ITS ASSOCIATED ENVIRONMENT, the .NET Framework, as the most significant technology for developers around right now, we would not be exaggerating. .NET is designed to provide an environment within which you can develop almost any application to run on Windows, while C# is a programming language that has been designed specifically to work with the .NET Framework. By using C#, you can, for example, write a dynamic web page, a Windows Presentation Foundation application, 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 4. If you are coding using any of the prior versions, there may be sections of the book that will not work for you. We try to notify you of items that are new and specific to the .NET Framework 4.

Don’t be fooled by the .NET label in the Framework’s name and think that this is a purely Internet-focused framework. 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. It is also important to understand that 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 need to write for the Windows platform. Between them, C# and .NET have revolutionized the way that developers write their programs and have made programming on Windows much easier than it has ever been before.

So what’s the big deal about .NET and C#?

THE SIGNIFICANCE OF .NET AND C#

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 18 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 7 and Windows Server 2008 R2 have the same familiar Windows API at their core. As we have 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 have used to develop software for Windows. For example, COM (Component Object Model) originated as OLE (Object Linking and Embedding). Originally, it was largely a means by which different types of Office documents could be linked, so that you could place a small Excel spreadsheet in your Word document, for example. 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 would not 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.

It was clear that something had to change. Microsoft could not go on forever extending the same development tools and languages, always making them more and more complex in order to satisfy the conflicting demands of keeping up with the newest hardware and maintaining backward compatibility with what was around when Windows first became popular in the early 1990s. There comes a point where you have to start with a clean slate if you want a simple yet sophisticated set of languages, environments, and developer tools, which makes it easy for developers to write state-of-the-art software.

This fresh start is what C# and .NET were all about in the first incarnation. Roughly speaking, .NET is a framework — an API — for programming on the Windows platform. Along with the .NET Framework, C# is a language that has been designed from scratch to work with .NET, as well as to take advantage of all the progress in developer environments and in our understanding of object-oriented programming principles that have taken place over the past 25 years.

Before we continue, we should make it clear that backward compatibility has not been lost in the process. Existing programs will continue to work, and .NET was designed with the capability to work with existing software. Presently, communication between software components on Windows takes place almost entirely using COM. Taking this into account, the .NET Framework does have the capability to provide wrappers around existing COM components so that .NET components can talk to them.

It is true that you don’t need to learn C# in order to write code for .NET. Microsoft has extended C++, and made substantial changes to Visual Basic to turn it into a more powerful language, in order to allow code written in either of these languages to target the .NET environment. These other languages, however, are hampered by the legacy of having evolved over the years rather than having been written from the start with today’s technology in mind.

This book will equip you to program in C#, while at the same time provide the necessary background in how the .NET architecture works. We not only cover the fundamentals of the C# language but also go on to give examples of applications that use a variety of related technologies, including database access, dynamic web pages, advanced graphics, and directory access.

ADVANTAGES OF .NET

So far, we’ve talked in general terms about how great .NET is, but we haven’t said much about how it helps to make your life as a developer easier. This section briefly identifies some of the improved features of .NET.

We look more closely at the benefits of the .NET architecture in Chapter 1, “.NET Architecture.”

WHAT’S NEW IN THE .NET FRAMEWORK 4

The first version of the .NET Framework (1.0) was released in 2002 to much enthusiasm. The.NET Framework 2.0 was introduced in 2005 and was considered a major release of the Framework. The .NET Framework 4 is another major release of the product with many outstanding new features.

With each release of the Framework, Microsoft has always tried to ensure that there were minimal breaking changes to code developed. Thus far, Microsoft has been very successful at this goal.

The following section details some of the changes that are new to C# 2010 and the .NET Framework 4.

Dynamic Typing

The world of programming has seen tremendous growth in dynamic languages such as JavaScript, Python, and Ruby. Because of the growing popularity of this type of programming, Microsoft has released a new dynamic typing capability in C#. It is not always possible to know statically what objects might end up being. Instead of using the object keyword and making everything of this type, we can now let the Dynamic Language Runtime (DLR) figure this out at runtime.

Using the new dynamic capabilities of C#, you now have a better interoperability story. You are able to interop with various dynamic languages and work with the DOM more easily. It’s even simple to work with the Microsoft Office COM APIs now.

In this release of the .NET Framework 4, Microsoft has included the Dynamic Language Runtime. The DLR has been built upon the Common Language Runtime (CLR) to provide the ability to tie together all the dynamic language interactions.

C# provides access to the new DLR through the use of the new dynamic keyword. This is a flag to the compiler; whenever this keyword is encountered, the compiler will realize that it is a dynamic invocation and not the typical static invocation.

Optional and Named Parameters

Optional parameters and named parameters have been in Visual Basic for some time but have not been available to C# until the .NET 4 release. Optional parameters allow you to provide default values for some of the parameters of your methods and allow for a type of overloading by the consumer, even if there is only a single method in place to deal with all the variants. Here’s an example:

public void CreateUser(string firstname, string lastname,
 bool isAdmin, bool isTrialUser)
{

}

If you wanted to overload this and have default values for the two bool objects, then you could easily have a few more methods that populate these values for the consumer and then make a call to the master method to actually create the user. Now with optional parameters, you are able to do something like this:

public void CreateUser(string firstname, string lastname,
 bool isAdmin = false, bool isTrialUser = true)
{

}

Looking over this bit of code, the parameters firstname and lastname do not have a default value set, while isAdmin and isTrailUser do have default values set. As a consumer of something like this, you are now able to do some of the following:

myClass.CreateUser("Bill", "Evjen");
myClass.CreateUser("Bill", "Evjen", true);
myClass.CreateUser("Bill", "Evjen", true, false);
myClass.CreateUser("Bill", "Evjen", isTrailUser: false);

The last example makes use of named parameters, which are also a new feature for C# in this release of the .NET Framework. Named parameters will potentially change the way you write your code. This new feature will allow you to make your code easier to read and understand. As an example of this in action, take a look at the File.Copy() method of the System.IO namespace. Typically, it would be constructed similarly to this:

File.Copy(@"C:\myTestFile.txt", @"C:\myOtherFile.txt", true);

In this case, this simple method is working with three parameters, but what are the actual items being passed into the Copy() method? Unless you know this method backward and forward, it is hard to tell what is going on by just glancing at this method. Using named parameters, you are able to use the parameter name in the code prior to the value being provided, as in the following example:

File.Copy(sourceFileName: @"C:\myTestFile.txt",
   destFileName: @"C:\myOtherFile.txt", overwrite: true);

Now with the named parameters in place, you can more easily read and understand what is going on with this line of code. Using named parameters makes no difference to the resulting compilation; they are only used in the coding of the application.

Covariance and Contravariance

Covariance and contravariance were included in prior versions of the .NET Framework, but they have been extended in .NET 4 to perform even better when working with generics, delegates, and more. In the prior versions of .NET, you were able to use contravariance with objects and arrays, but, for instance, you were unable to use contravariance with generic interfaces. In .NET 4, you are able to do this.

ASP.NET MVC

ASP.NET MVC is the latest major addition to ASP.NET and has generated a lot of excitement in the development community. ASP.NET MVC supplies you with the means to create ASP.NET using the model-view-controller model that many developers expect. ASP.NET MVC provides developers with testability, flexibility, and maintainability in the applications they build. It is important to remember that ASP.NET MVC is not meant to be a replacement for the ASP.NET everyone knows and loves, but is simply a different way to construct your applications.

This release of ASP.NET allows you to build using this new model. You will find that it is completely built in to the Framework and Visual Studio.

WHERE C# FITS IN

In one sense, C# can be seen as being the same thing to programming languages that .NET is to the Windows environment. Just as Microsoft has been adding more and more features to Windows and the Windows API over the past decade and a half, Visual Basic 2010 and C++ have undergone expansion. Although Visual Basic and C++ have ended up as hugely powerful languages as a result of this, both languages also suffer from problems because of the legacies left over from the way they evolved.

In the case of Visual Basic 6 and earlier versions, the main strength of the language was the fact that it was simple to understand and made many programming tasks easy, largely hiding the details of the Windows API and the COM component infrastructure from the developer. The downside to this was that Visual Basic was never truly object oriented, so that large applications quickly became disorganized and hard to maintain. As well, because Visual Basic’s syntax was inherited from early versions of BASIC (which, in turn, was designed to be intuitively simple for beginning programmers to understand, rather than to write large commercial applications), it didn’t really lend itself to well-structured or object-oriented programs.

C++, on the other hand, has its roots in the ANSI C++ language definition. It is not completely ANSI-compliant for the simple reason that Microsoft first wrote its C++ compiler before the ANSI definition had become official, but it comes close. Unfortunately, this has led to two problems. First, ANSI C++ has its roots in a decade-old state of technology, and this shows up in a lack of support for modern concepts (such as Unicode strings and generating XML documentation) and for some archaic syntax structures designed for the compilers of yesteryear (such as the separation of declaration from definition of member functions). Second, Microsoft has been simultaneously trying to evolve C++ into a language that is designed for high-performance tasks on Windows, and in order to achieve that, it has been forced to add a huge number of Microsoft-specific keywords as well as various libraries to the language. The result is that on Windows, the language has become a complete mess. Just ask C++ developers how many definitions for a string they can think of: char*, LPTSTR, string, CString (MFC version), CString (WTL version), wchar_t*, OLECHAR*, and so on.

Now enter .NET — a completely revolutionary environment that has brought forth new extensions to both languages. Microsoft has gotten around this by adding yet more Microsoft-specific keywords to C++, and by completely revamping Visual Basic to the current Visual Basic 2010, a language that retains some of the basic VB syntax, but that is so different in design from the original VB that it can be considered, for all practical purposes, a new language.

It is in this context that Microsoft has provided developers an alternative — a language designed specifically for .NET, and designed with a clean slate. C# is the result. Officially, Microsoft describes C# as a “simple, modern, object-oriented, and type-safe programming language derived from C and C++.” Most independent observers would probably change that to “derived from C, C++, and Java.” Such descriptions are technically accurate but do little to convey the beauty or elegance of the language. Syntactically, C# is very similar to both C++ and Java, to such an extent that many keywords are the same, and C# also shares the same block structure with braces ({}) to mark blocks of code and semicolons to separate statements. The first impression of a piece of C# code is that it looks quite like C++ or Java code. Beyond that initial similarity, however, C# is a lot easier to learn than C++, and of comparable difficulty to Java. Its design is more in tune with modern developer tools than both of those other languages, and it has been designed to provide, simultaneously, the ease of use of Visual Basic and the high-performance, low-level memory access of C++, if required. Some of the features of C# are:

Most of these statements, it should be pointed out, do also apply to Visual Basic 2010 and Managed C++. The fact that C# is designed from the start to work with .NET, however, means that its support for the features of .NET is both more complete and offered within the context of a more suitable syntax than those of other languages. Although the C# language itself is very similar to Java, there are some improvements; in particular, Java is not designed to work with the .NET environment.

Before leaving the subject, it is important to point out a couple of limitations of C#. The one area the language is not designed for is time-critical or extremely high-performance code — the kind where you really are worried about whether a loop takes 1,000 or 1,050 machine cycles to run through, and you need to clean up your resources the millisecond they are no longer needed. C++ is likely to continue to reign supreme among low-level languages in this area. C# lacks certain key facilities needed for extremely high-performance apps, including the ability to specify inline functions and destructors that are guaranteed to run at particular points in the code. However, the proportions of applications that fall into this category are very low.

WHAT YOU NEED TO WRITE AND RUN C# CODE

The .NET Framework 4 will run on Windows XP, 2003, 7, and the latest Windows Server 2008 R2. In order to write code using .NET, you will need to install the .NET 4 SDK.

In addition, unless you are intending to write your C# code using a text editor or some other third-party developer environment, you will almost certainly also want Visual Studio 2010. The full SDK is not needed to run managed code, but the .NET runtime is needed. You may find you need to distribute the .NET runtime with your code for the benefit of those clients who do not have it already installed.

WHAT THIS BOOK COVERS

This book starts by reviewing the overall architecture of .NET in Chapter 1 in order to give you the background you need to be able to write managed code. After that, the book is divided into a number of sections that cover both the C# language and its application in a variety of areas.

Part I: The C# Language

This section gives a good grounding in the C# language itself. This section doesn’t presume knowledge of any particular language, although it does assume you are an experienced programmer. You start by looking at C#’s basic syntax and data types, and then explore the object-oriented features of C# before moving on to look at more advanced C# programming topics.

Part II: Visual Studio

This section looks at the main IDE utilized by C# developers worldwide: Visual Studio 2010. The two chapters in this section look at the best way to use the tool to build applications based on the .NET Framework 4. In addition, this section also focuses on the deployment of your projects.

Part III: Foundation

In this section, you look at the principles of programming in the .NET environment. In particular, you look at security, threading, localization, transactions, how to build Windows services, and how to generate your own libraries as assemblies, among other topics.

Part IV: Data

Here, you look at accessing databases with ADO.NET and LINQ, and at interacting with directories and files. This part also extensively covers support in .NET for XML and on the Windows operating system side, and the .NET features of SQL Server 2008.

Part V: Presentation

This section starts with coverage on building classic Windows applications, which are called Windows Forms in .NET. Windows Forms are the thick-client version of applications, and using .NET to build these types of applications is a quick and easy way of accomplishing this task. This section also shows how to build applications based upon the Windows Presentation Foundation and Silverlight, and covers writing components that will run on web sites, serving up web pages. Finally, it includes coverage of the tremendous number of features that ASP.NET and ASP.NET MVC provide.

Part VI: Communication

This section is all about communication. It covers services for platform-independent communication using the Windows Communication Foundation (WCF). With Message Queuing, asynchronous disconnected communication is shown. This section looks at utilizing the Windows Workflow Foundation (WF), as well as peer-to-peer networking, and creating syndication feeds.

Appendix

The book closes with an appendix covering Windows 7 and Windows Server 2008 R2 development.

Online Chapters

Even with such a large book, we can’t fit in everything we’d like to tell you about C# and using this language with other .NET technologies, so we’ve made ten additional chapters available online at www.wrox.com. These chapters include information on a variety of topics: GDI+, which is a technology that is used for building applications that include advanced graphics; .NET Remoting for communication between .NET clients and servers; Enterprise Services for the services in the background; and the Managed Add-In Framework (MAF). Some other big topics found online include VSTO development and working with LINQ to SQL.

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.

Image

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

Image

The pencil icon indicates notes, tips, hints, tricks, or asides to the current discussion.

As for styles in the text:

We use a monofont type with no highlighting for most code examples.
We use bold to emphasize code that's particularly important in the present context or to show changes from a previous code snippet.

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 http://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.

Image

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

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 http://www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.

ERRATA

We make every effort 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, like a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata you may save another reader hours of frustration and at the same time you will be helping us provide even higher quality information.

To find the errata page for this book, go to http://www.wrox.comwww.wrox.com/misc-pages/booklist.shtml