Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Pro CSharp 2008 And The .NET 3.5 Platform [eng]

.pdf
Скачиваний:
71
Добавлен:
16.08.2013
Размер:
22.5 Mб
Скачать

xxINTRODUCTION

names, but that’s what applied knowledge is all about! Rest assured, once you understand the concepts presented within this text, you will be in a perfect position to build .NET solutions that map to your own unique programming environment.

An Overview of This Book

Pro C# 2008 and the .NET 3.5 Platform, Fourth Edition is logically divided into eight distinct parts, each of which contains a number of related chapters. If you have read the earlier editions of this text, you will quickly notice a number of changes. For example, several topics (such as core C# constructs, object-oriented programming, and platform-independent .NET development) have been expanded into several dedicated chapters. Furthermore, this edition of the text contains numerous new chapters to account for .NET 3.0–3.5 programming features (LINQ, WCF, WPF, WF, etc.). Here is a part-by-part and chapter-by-chapter breakdown of the text.

Part 1: Introducing C# and the .NET Platform

The purpose of Part 1 is to acclimate you to the nature of the .NET platform and various development tools (many of which are open source) used during the construction of .NET applications. Along the way, you will also check out some basic details of the C# programming language and the

.NET type system.

Chapter 1: The Philosophy of .NET

This first chapter functions as the backbone for the remainder of the text. We begin by examining the world of traditional Windows development and uncover the shortcomings with the previous state of affairs. The primary goal of this chapter, however, is to acquaint you with a number of .NETcentric building blocks, such as the common language runtime (CLR), Common Type System (CTS), Common Language Specification (CLS), and base class libraries. Here, you will take an initial look at the C# programming language and the .NET assembly format, and get an overview the platformindependent nature of the .NET platform (Appendix B will examine this topic in greater detail).

Chapter 2: Building C# Applications

The goal of this chapter is to introduce you to the process of compiling C# source code files using various tools and techniques. First, you will learn how to make use of the command-line compiler (csc.exe) and C# response files. Over the remainder of the chapter, you will examine numerous code editors and integrated development environments (IDEs), including TextPad, Notepad++, SharpDevelop, Visual C# 2008 Express, and Visual Studio 2008. As well, you will be exposed to a number of additional programming tools that any .NET developer should have in their back pocket.

Part 2: Core C# Programming Constructs

The topics presented in this part of the book are quite important, as they will be used regardless of which type of .NET software you intend to develop (web applications, desktop GUI applications, code libraries, Windows services, etc.). Here, you will come to understand the core constructs of the C# language, including the details of object-oriented programming (OOP). As well, this part will examine how to process runtime exceptions and dive into the details of .NET’s garbage collection services.

INTRODUCTION xxi

Chapter 3: Core C# Programming Constructs, Part I

This chapter begins your formal investigation of the C# programming language. Here you will learn about the role of the Main() method and numerous details regarding the intrinsic data types of the

.NET platform, including the manipulation of textual data using System.String and System.Text. StringBuilder. You will also examine iteration and decision constructs, narrowing and widening operations, and use of the unchecked keyword.

Chapter 4: Core C# Programming Constructs, Part II

This chapter completes your examination of the core aspects of C#, beginning with the construction of overloaded type methods and defining parameters via the out, ref, and params keywords. You will also learn how to create and manipulate arrays of data, define nullable data types (with the ? and ?? operators), and understand the distinction between value types (including enumerations and custom structures) and reference types.

Chapter 5: Defining Encapsulated Class Types

This chapter begins your examination of object-oriented programming (OOP) using the C# programming language. Once we qualify the pillars of OOP (encapsulation, inheritance, and polymorphism), the remainder of this chapter will examine how to build robust class types using constructors, properties, static members, constants, and read-only fields. We wrap up with an examination of partial type definitions and C#’s XML code documentation syntax.

Chapter 6: Understanding Inheritance and Polymorphism

Here, you will examine the remaining pillars of OOP (inheritance and polymorphism), which allow you to build families of related class types. During this time, you will examine the role of virtual methods, abstract methods (and abstract base classes), and the nature of the polymorphic interface. Last but not least, this chapter will explain the role of the supreme base class of the .NET platform,

System.Object.

Chapter 7: Understanding Structured Exception Handling

The point of this chapter is to discuss how to handle runtime anomalies in your code base through the use of structured exception handling. Not only will you learn about the C# keywords that allow you to handle such problems (try, catch, throw, and finally), but you will also come to understand the distinction between application-level and system-level exceptions. In addition, this chapter examines various tools within Visual Studio 2008 that allow you to debug the exceptions that have escaped your view.

Chapter 8: Understanding Object Lifetime

The final chapter of this part examines how the CLR manages memory using the .NET garbage collector. Here you will come to understand the role of application roots, object generations, and the System.GC type. Once you understand the basics, the remainder of this chapter covers the topics of disposable objects (via the IDisposable interface) and the finalization process (via the System. Object.Finalize() method).

xxii INTRODUCTION

Part 3: Advanced C# Programming Constructs

This section of the book will deepen your understanding of the C# language, by examining a number of more advanced (but very important) concepts. Here, you will complete your examination of the .NET type system by examining interfaces and delegates. As well, you will learn about the role of generics and the numerous new language features of C# 2008, and take an initial look at Language Integrated Query (LINQ).

Chapter 9: Working with Interfaces

The material in this chapter builds upon your understanding of object-based development by covering the topic of interface-based programming. Here, you will learn how to define types that support multiple behaviors, how to discover these behaviors at runtime, and how to selectively hide particular behaviors using explicit interface implementation. In addition to examining a number of predefined .NET interface types, you will also learn how to make use of custom interfaces to build an ad hoc event architecture.

Chapter 10: Collections and Generics

This chapter begins by examining the collection types of the System.Collections namespace, which has been part of the .NET platform since its initial release. However, since the release of .NET 2.0, the C# programming language offers support for generics. As you will see, generic programming greatly enhances application performance and type safety. Not only will you explore various generic types within the System.Collections.Generic namespace, but you will also learn how to build your own generic methods and types (with and without constraints).

Chapter 11: Delegates, Events, and Lambdas

The purpose of Chapter 11 is to demystify the delegate type. Simply put, a .NET delegate is an object that “points” to other methods in your application. Using this pattern, you are able to build systems that allow multiple objects to engage in a two-way conversation. After you have examined the use of

.NET delegates, you will then be introduced to the C# event keyword, which is used to simplify the manipulation of raw delegate programming. You wrap up by investigating the role of the C# 2008 lambda operator (=>) and exploring the connection between delegates, anonymous methods, and lambda expressions.

Chapter 12: Indexers, Operators, and Pointers

This chapter deepens your understanding of the C# programming language by introducing a number of advanced programming techniques. Here, you will learn how to overload operators and create custom conversion routines (both implicit and explicit) for your types. As well, you will learn how to build and interact with type indexers, and manipulate C-style pointers using an “unsafe” code context.

Chapter 13: C# 2008 Language Features

With the release of .NET 3.5, the C# language has been enhanced to support a great number of new programming constructs, many of which are used to enable the LINQ API (which you will begin to examine in Chapter 14). Here, you will learn the role of implicit typing of local variables, partial methods, automatic properties, extension methods, anonymous types, and object initialization syntax.

INTRODUCTION xxiii

Chapter 14: An Introduction to LINQ

This chapter will begin your examination of Language Integrated Query (LINQ), which could easily be considered the most intriguing aspect of .NET 3.5. As you will see in this chapter, LINQ allows you to build strongly typed query expressions, which can be applied to a number of LINQ targets to manipulate “data” in the broadest sense of the word. Here, you will learn about LINQ to Objects, which allows you to apply LINQ expressions to containers of data (arrays, collections, custom types). This information will serve you well when we examine how to apply LINQ expressions to relational databases (via LINQ to ADO) and XML documents (à la LINQ to XML) later in Chapter 24.

Part 4: Programming with .NET Assemblies

Part 4 dives into the details of the .NET assembly format. Not only will you learn how to deploy and configure .NET code libraries, but you will also come to understand the internal composition of a

.NET binary image. This part also explains the role of .NET attributes and the construction of multithreaded applications. Later chapters examine some fairly advanced topics such as object context, CIL code, and dynamic assemblies.

Chapter 15: Introducing .NET Assemblies

From a very high level, assembly is the term used to describe a managed *.dll or *.exe binary file. However, the true story of .NET assemblies is far richer than that. Here you will learn the distinction between single-file and multifile assemblies, and how to build and deploy each entity. You’ll examine how private and shared assemblies may be configured using XML-based *.config files and publisher policy assemblies. Along the way, you will investigate the internal structure of the global assembly cache (GAC) and the role of the .NET Framework configuration utility.

Chapter 16: Type Reflection, Late Binding, and Attribute-Based Programming

Chapter 16 continues our examination of .NET assemblies by checking out the process of runtime type discovery via the System.Reflection namespace. Using these types, you are able to build applications that can read an assembly’s metadata on the fly. You will learn how to dynamically load and create types at runtime using late binding. The final topic of this chapter explores the role of .NET attributes (both standard and custom). To illustrate the usefulness of each of these topics, the chapter concludes with the construction of an extendable Windows Forms application.

Chapter 17: Processes, AppDomains, and Object Contexts

Now that you have a solid understanding of assemblies, this chapter dives deeper into the composition of a loaded .NET executable. The goal of this chapter is to illustrate the relationship between processes, application domains, and contextual boundaries. These topics provide the proper foundation for the topic of the following chapter, where we examine the construction of multithreaded applications.

Chapter 18: Building Multithreaded Applications

This chapter examines how to build multithreaded applications and illustrates a number of techniques you can use to author thread-safe code. The chapter opens by revisiting the .NET delegate type in order to understand a delegate’s intrinsic support for asynchronous method invocations.

Next, you will investigate the types within the System.Threading namespace. You will look at numerous types (Thread, ThreadStart, etc.) that allow you to easily create additional threads of execution. We wrap up by examining the BackgroundWorker type, which greatly simplifies the creation of threads from within a desktop user interface.

xxiv INTRODUCTION

Chapter 19: Understanding CIL and the Role of Dynamic Assemblies

The goal of the final chapter of this part is twofold. In the first half (more or less), you will examine the syntax and semantics of CIL in much greater detail than in previous chapters. The remainder of this chapter covers the role of the System.Reflection.Emit namespace. Using these types, you are able to build software that is capable of generating .NET assemblies in memory at runtime. Formally speaking, assemblies defined and executed in memory are termed dynamic assemblies.

Part 5: Introducing the .NET Base Class Libraries

By this point in the text, you have a solid handle on the C# language and the details of the .NET assembly format. Part 5 leverages your newfound knowledge by exploring a number of commonly used services found within the base class libraries, including file I/O and database access using ADO.NET. This part also covers the construction of distributed applications using Windows Communication Foundation (WCF) and workflow-enabled applications that make use of the Windows Workflow Foundation (WF) API.

Chapter 20: File I/O and Isolated Storage

The System.IO namespace allows you to interact with a machine’s file and directory structure. Over the course of this chapter, you will learn how to programmatically create (and destroy) a directory system as well as move data into and out of various streams (file based, string based, memory based, etc.). The latter part of this chapter examines the role of isolated storage, which allows you to persist per-user data into a safe sandbox, regardless of the security settings of a target machine. To understand certain aspects of the System.IO.IsolatedStorage API, you will also receive an overview of Code Access Security (CAS).

Chapter 21: Introducing Object Serialization

This chapter examines the object serialization services of the .NET platform. Simply put, serialization allows you to persist the state of an object (or a set of related objects) into a stream for later use. Deserialization (as you might expect) is the process of plucking an object from the stream into memory for consumption by your application. Once you understand the basics, you will then learn how to customize the serialization process via the ISerializable interface and a set of .NET attributes.

Chapter 22: ADO.NET Part I: The Connected Layer

In this first of two database-centric chapters, you will learn about the ADO.NET programming API. Specifically, this chapter will introduce the role of .NET data providers and how to communicate with a relational database using the connected layer of ADO.NET, represented by connection objects, command objects, transaction objects, and data reader objects. Be aware that this chapter will also walk you through the creation of a custom database and a data access library that will be used throughout the remainder of this text.

Chapter 23: ADO.NET Part II: The Disconnected Layer

This chapter continues your study of database manipulation by examining the disconnected layer of ADO.NET. Here, you will learn the role of the DataSet type, data adapter objects, and numerous tools of Visual Studio 2008 that can greatly simplify the creation of data-driven applications. Along the way, you will learn how to bind DataTable objects to user interface elements, such as the GridView type of the Windows Forms API.

INTRODUCTION xxv

Chapter 24: Programming with the LINQ APIs

Chapter 14 introduced you to the LINQ programming model, specifically LINQ to Objects. Here, you will deepen your understanding of Language Integrated Query by examining how to apply LINQ queries to relational databases, DataSet objects, and XML documents. Along the way, you will learn the role of data context objects, the sqlmetal.exe utility, and various LINQ-specific aspects of Visual Studio 2008.

Chapter 25: Introducing Windows Communication Foundation

.NET 3.0 introduced a brand-new API, WCF, that allows you to build distributed applications, regardless of their underlying plumbing, in a symmetrical manner. This chapter will expose you to the construction of WCF services, hosts, and clients. As you will see, WCF services are extremely flexible, in that clients and hosts can leverage XML-based configuration files to declaratively specify addresses, bindings, and contracts.

Chapter 26: Introducing Windows Workflow Foundation

In addition to WCF, .NET 3.0 also introduced an API, WF, that allows you to define, execute, and monitor workflows to model complex business processes. Here, you will learn the overall purpose of Windows Workflow Foundation, as well as the role of activities, workflow designers, the workflow runtime engine, and the creation of workflow-enabled code libraries.

Part 6: Desktop User Interfaces

It is a common misconception for newcomers to the .NET platform to assume this framework is only concerned with the construction of web-based user interfaces (which I suspect is due to the term “.NET,” as this tends to conjure up the notion of the “Internet” and therefore “web programs”). While it is true that .NET provides outstanding support for the construction of web applications, this part of the book focuses on traditional desktop user interfaces using two GUI frameworks, Windows Forms and Windows Presentation Foundation (WPF).

Chapter 27: Programming with Windows Forms

The original desktop GUI toolkit that shipped with the .NET platform is termed Windows Forms. This chapter will walk you through the role of this UI framework, and illustrate how to build main windows, dialog boxes, and menu systems. As well, you will understand the role of form inheritance and see how to render 2D graphical data using the System.Drawing namespace. To illustrate these topics using a cohesive example, we wrap up by building a (semicapable) painting application.

Chapter 28: Introducing Windows Presentation Foundation and XAML

.NET 3.0 introduced a brand-new GUI toolkit termed WPF. Essentially, WPF allows you to build extremely interactive and media-rich front ends for desktop applications (and indirectly, web applications). Unlike Windows Forms, this supercharged UI framework integrates a number of key services (2D and 3D graphics, animations, rich documents, etc.) into a single unified object model. In this chapter, you will begin your examination of WPF and the Extendable Application Markup Language (XAML). Here, you will learn how to build WPF programs XAML-free, using nothing but XAML, and a combination of each. We wrap up by building a custom XAML viewer, which will be used during the remainder of the WPF-centric chapters.

xxvi INTRODUCTION

Chapter 29: Programming with WPF Controls

In this chapter, you will learn how to work with the WPF control content model as well as a number of related control-centric topics such as dependency properties and routed events. As you would hope, this chapter provides coverage of working with a number of WPF controls; however, more interestingly, this chapter will explain the use of layout managers, control commands, and the WPF data-binding model.

Chapter 30: WPF 2D Graphical Rendering, Resources, and Themes

The final chapter of this part will wrap up your examination of WPF by examining three seemingly independent topics. However, as you will see, WPF’s graphical rendering services typically require you to define custom resources. Using these resources, you are able to generate custom WPF animations, and using graphics, resources, and animations, you are able to build custom themes for a WPF application. To pull all of these topics together, this chapter wraps up by illustrating how to apply custom graphical themes at runtime.

Part 7: Building Web Applications with ASP.NET

Part 7 is devoted to the examination of constructing web applications using the ASP.NET programming API. As you will see, ASP.NET was intentionally designed to model the creation of desktop user interfaces by layering on top of standard HTTP request/response an event-driven, object-oriented framework.

Chapter 31: Building ASP.NET Web Pages

This chapter begins your study of web application development using ASP.NET. As you will see, server-side scripting code has now been replaced with real object-oriented languages (such as C#, VB .NET, and the like). This chapter will examine the construction of an ASP.NET web page, the underlying programming model, and other key aspects of ASP.NET, such as your choice of web server and the use of Web.config files.

Chapter 32: ASP.NET Web Controls, Themes, and Master Pages

Whereas the previous chapter examined the construction of ASP.NET Page objects, this chapter is concerned with the controls that populate the internal control tree. Here, you will examine the core ASP.NET web controls, including validation controls, the intrinsic site navigation controls, and various data-binding operations. As well, this chapter will illustrate the role of master pages and the ASP.NET theme engine, which is a server-side alternative to traditional style sheets.

Chapter 33: ASP.NET State Management Techniques

This chapter extends your current understanding of ASP.NET by examining various ways to handle state management under .NET. Like classic ASP, ASP.NET allows you to easily create cookies, as well as application-level and session-level variables. However, ASP.NET also introduces a new state management technique: the application cache. Once you have looked at the numerous ways to handle state with ASP.NET, you will then come to learn the role of the System.HttpApplication base class (lurking within the Global.asax file) and how to dynamically alter the runtime behavior of your web application using the Web.config file.

INTRODUCTION xxvii

Part 8: Appendixes

This final part of this book examines two important topics, which quite frankly did not seem to fit naturally within the bulk of the text, and have therefore been “appendix-ized.” Here you will complete your examination of C# and the .NET platform by learning how to integrate legacy code into your .NET applications as well as how to take .NET development beyond the Windows family of operating systems.

Appendix A: COM and .NET Interoperability

If you have programmed the Windows operating system prior to using .NET, you are most likely aware of the Component Object Model (COM). While COM and .NET have nothing to do with each other (beyond the fact that they each originated from Microsoft), the .NET platform has an entire namespace (System.Runtime.InteropServices) that makes it possible for .NET software to make use of legacy COM components and vice versa. This appendix will examine the interoperability layer in quite a bit of detail, as this topic is quite important when looking for ways to leverage your existing code base as you build new .NET applications.

Appendix B: Platform-Independent .NET Development with Mono

Last but not least, Appendix B covers the use of an open source implementation of the .NET platform named Mono. Using Mono, it is possible to build feature-rich .NET applications that can be created, deployed, and executed upon a variety of operating systems, including Mac OS X, Solaris, AIX, and numerous Linux distributions. Given that Mono is largely comparable with Microsoft’s

.NET platform, you already know most of what Mono has to offer. Therefore, this appendix will focus on the Mono installation process, Mono development tools, and Mono runtime engine.

Diving Even Deeper with Five Free Chapters

As if a grand total of thirty-three chapters and two appendixes were not enough, those of you who purchase this book are eligible to download an additional five chapters for free. As you may be aware, previous editions of this text included three chapters devoted to Windows Forms development (including an examination of custom controls), another chapter that addressed the .NET remoting layer (System.Runtime.Remoting and friends), and a final chapter covering the construction of traditional XML web services using the ASP.NET Web Service project template.

This edition of the text does not provide printed versions of these five chapters. The major reason for doing so is due to the fact that the .NET 3.0 WCF and WPF APIs are poised to become the heirs apparent to .NET remoting/XML web services and Windows Forms APIs, respectively. If you wish to dig deeper into Windows Forms (beyond what is provided in Chapter 27) or to see how to make use of the (legacy?) .NET remoting and XML web service APIs, simply look up this book from the Apress website:

http://apress.com/book/view/1590598849

There you will find a link to download this book’s supplemental chapters in a digital format, once you answer randomly generated questions regarding the text within this book.

xxviii INTRODUCTION

Obtaining This Book’s Source Code

All of the code examples contained within this book (including the five additional chapters that may be downloaded for free, as mentioned in the previous section) are available for free and immediate download from the Source Code/Download area of the Apress website. Simply navigate to http://www.apress.com, select the Source Code/Download link, and look up this title by name. Once you are on the home page for Pro C# 2008 and the .NET 3.5 Platform, Fourth Edition, you may download a self-extracting *.zip file. After you unzip the contents, you will find that the code has been logically divided by chapter.

Do be aware that Source Code notes like the following in the chapters are your cue that the example under discussion may be loaded into Visual Studio 2008 for further examination and modification:

Source Code This is a source code note referring you to a specific directory!

To do so, simply open the *.sln file found in the correct subdirectory. If you are not making use of Visual Studio 2008 (see Chapter 2 for additional IDEs), you can manually load the provided source code files into your development tool of choice.

Obtaining Updates for This Book

As you read through this text, you may find an occasional grammatical or code error (although I sure hope not). If this is the case, my apologies. Being human, I am sure that a glitch or two may be present, despite my best efforts. If this is the case, you can obtain the current errata list from the Apress website (located once again on the home page for this book) as well as information on how to notify me of any errors you might find.

Contacting Me

If you have any questions regarding this book’s source code, are in need of clarification for a given example, or simply wish to offer your thoughts regarding the .NET platform, feel free to drop me a line at the following e-mail address (to ensure your messages don’t end up in my junk mail folder, please include “C# FE” in the Subject line somewhere): atroelsen@Intertech.com.

Please understand that I will do my best to get back to you in a timely fashion; however, like yourself, I get busy from time to time. If I don’t respond within a week or two, do know I am not trying to be a jerk or don’t care to talk to you. I’m just busy (or, if I’m lucky, on vacation somewhere).

So, then! Thanks for buying this text (or at least looking at it in the bookstore while you try to decide if you will buy it). I hope you enjoy reading this book and putting your newfound knowledge to good use.

Take care,

Andrew Troelsen

P A R T 1

Introducing C# and the

.NET Platform