Introduction

Many moons ago (circa 2001), I was given the opportunity to write a book on a forthcoming Microsoft technology that was, at the time, dubbed NGWS (Next Generation Windows Software). As I began to examine the source code provided by Microsoft, I noticed numerous code comments referring to the “COOL” (Common Object Oriented Language) programming language.

While I worked on my first initial manuscript of C# and the .NET Platform using a pre-alpha build (and no documentation to speak of), NGWS was eventually rebranded as the Microsoft .NET platform. COOL, as you might guess, is what we now know today as C#.

The first edition of this book was released in step with .NET 1.0, beta 2. Since then, I have updated the text to account for the numerous updates to the C# programming language, as well as the explosion of new APIs introduced with each new release of the .NET platform.

Over the years, this book has (thankfully and gratefully) been very well received, by the press (a JOLT award finalist and ReferenceWare programming book of the year), readers, and various university programs in computer science and software engineering.

It has been just wonderful to communicate with readers and educators around the globe. Thank you for all of your suggestions, comments, and (yes) criticism. I might not be able to respond to every e-mail, but everything is taken under consideration, to be sure.

We’re a Team, You and I

Technology authors write for a demanding group of people (I should know—I’m one of them). You know that building software solutions using any platform or language is extremely complicated and is very specific to your department, company, client base, and subject matter. Perhaps you work in the electronic publishing industry, develop systems for the state or local government, or work at NASA or a branch of the military. Speaking for myself, I have developed children’s educational software (Oregon Trail/Amazon Trail), various n-tier systems, and projects within the medical and financial industries. The chances are almost 100 percent that the code you write at your place of employment has little to do with the code I write at mine (unless we happened to work together previously!).

Therefore, in this book, I have deliberately chosen to avoid creating demonstrations that tie the example code to a specific industry or vein of programming. Given this, I explain C#, OOP, the CLR, and the .NET base class libraries using industry-agnostic examples. Rather than having every blessed example fill a grid with data, calculate payroll, or whatnot, I’ll stick to subject matter we can all relate to: automobiles (with some geometric structures and employee payroll systems thrown in for good measure). And that’s where you come in.

My job is to explain the C# programming language and the core aspects of the .NET platform the best I possibly can. As well, I will do everything I can to equip you with the tools and strategies you need to continue your studies at this book’s conclusion.

Your job is to take this information and apply it to your specific programming assignments. I obviously understand that your projects most likely don’t revolve around automobiles with friendly pet names (Zippy the BMW, or a Yugo named Clunker, among others), but that’s what applied knowledge is all about!

Rest assured, once you understand the topics and 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# 5.0 and the .NET 4.5 Framework, Sixth Edition, is logically divided into eight distinct parts, each of which contains a number of related chapters. Here is a part-by-part and chapter-by-chapter breakdown of the text.

Part I: 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.

Chapter 1: The Philosophy of .NET

This first chapter functions as the backbone for the remainder of the text. The primary goal of this chapter is to acquaint you with a number of .NET-centric 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. As well, you will learn the role of the .NET platform within the Windows 8 operating system, and understand the distinction between a Windows 8 app and a .NET application.

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. You will begin by learning how to use 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 Notepad++, SharpDevelop, Visual C# Express, and Visual Studio. You will also learn how to configure your development machine with a local installation of the all-important .NET Framework 4.5 SDK documentation.

Part II: Core C# Programming

The topics presented in this part of the book are quite important because you will use them regardless of which type of .NET software you intend to develop (e.g., web applications, desktop GUI applications, code libraries, or Windows services). Here, you will learn about the fundamental data types of .NET, work with text manipulation, and learn the role of various C# parameter modifiers (including optional and named arguments).

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 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 using the out, ref, and params keywords. This chapter will examine two C# features called arguments and optional parameters. 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.

Part III: Object-Oriented Programming with C#

In this section you will come to understand the core constructs of the C# language, including the details of object-oriented programming (OOP). This part will also examine how to process runtime exceptions, and dive into the details of working with strongly typed interfaces.

Chapter 5: Understanding Encapsulation

This chapter begins your examination of object-oriented programming (OOP) using the C# programming language. After you are introduced to the pillars of OOP (encapsulation, inheritance, and polymorphism), the remainder of this chapter will show you how to build robust class types using constructors, properties, static members, constants, and read-only fields. You will wrap up with an examination of partial type definitions, object initialization syntax, and automatic properties.

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. As you do this, 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 will examine various tools within Visual Studio that allow you to debug the exceptions that escape your notice.

Chapter 8: 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 classes and structures 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 creating a number of custom interfaces, you will also learn how to implement standard interfaces found within the .NET platform. You will use these to build objects that can be sorted, copied, enumerated, and compared.

Part IV: Advanced C# Programming

This section of the book will deepen your understanding of the C# language by walking you through 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. You will also learn about the role of generics, take a first look at Language Integrated Query (LINQ), and examine a number of more advanced features of C# (e.g., extension methods, partial methods, and pointer manipulation).

Chapter 9: Collections and Generics

This chapter explores the topic of generics. As you will see, generic programming gives you a way to create types and type members, which contain various placeholders that can be specified by the caller. In a nutshell, generics greatly enhance 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 10: Delegates, Events, and Lambda Expressions

The purpose of Chapter 10 is to demystify the delegate type. Simply put, a .NET delegate is an object that points to other methods in your application. Using this type, you can 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 you can use to simplify the manipulation of raw delegate programming. You will wrap up this chapter by investigating the role of the C# lambda operator (=>) and exploring the connection between delegates, anonymous methods, and lambda expressions.

Chapter 11: Advanced C# Language Features

This chapter deepens your understanding of the C# programming language by introducing you to 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. You will also learn how to build and interact with type indexers, as well as work with extension methods, anonymous types, partial methods, and C# pointers using an unsafe code context.

Chapter 12: LINQ to Objects

This chapter will begin your examination of Language Integrated Query (LINQ). LINQ allows you to build strongly typed query expressions that 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 (e.g., arrays, collections, and custom types). This information will serve you well as you encounter a number of additional LINQ APIs throughout the remainder of this book (e.g., LINQ to XML, LINQ to DataSet, PLINQ, and LINQ to Entities).

Chapter 13: Understanding Object Lifetime

The final chapter of this section 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, you will examine the topics of disposable objects (using the IDisposable interface) and the finalization process (using the System.Object.Finalize() method). This chapter will also investigate the Lazy<T> class, which allows you to define data that will not be allocated until requested by a caller. As you will see, this feature can be very helpful when you want to ensure you do not clutter the heap with objects that are not actually required by your programs.

Part V: Programming with .NET Assemblies

Part 5 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 role of resolving type information at runtime. This section will also explain the role of the Dynamic Language Runtime (DLR) and the C# dynamic keyword. Later chapters will examine some fairly advanced topics regarding assemblies, such as application domains, the syntax of CIL, and the construction of in-memory assemblies.

Chapter 14: Building and Configuring Class Libraries

At a very high level, assembly is the term used to describe a *.dll or *.exe binary file created with a .NET compiler. However, the true story of .NET assemblies is far richer than that. Here, you will learn the distinction between single-file and multifile assemblies, as well as how to build and deploy each entity. You’ll also examine how you can configure private and shared assemblies using XML-based *.config files and publisher policy assemblies. Along the way, you will investigate the internal structure of the global assembly cache (GAC).

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

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

Chapter 16: Dynamic Types and the Dynamic Language Runtime

.NET 4.0 introduces a new aspect of the .NET runtime environment called the dynamic language runtime. Using the DLR and the C# 2010 dynamic keyword, you can define data that is not truly resolved until runtime. Using these features simplifies some very complex .NET programming tasks dramatically. In this chapter, you will learn some practical uses of dynamic data, including how to leverage the .NET reflection APIs in a streamlined manner, as well as how to communicate with legacy COM libraries with a minimum of fuss and bother.

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 Chapter 19, where you will examine the construction of multithreaded applications.

Chapter 18: Understanding CIL and the Role of Dynamic Assemblies

The goal of the final chapter in this section 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 will cover the role of the System.Reflection.Emit namespace. You can use these types to build software that can generate .NET assemblies in memory at runtime. Formally speaking, assemblies defined and executed in memory are termed dynamic assemblies.

Part VI: 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 6 leverages your newfound knowledge by exploring a number of commonly used services found within the base class libraries, including the creation of multithreaded applications, file I/O, and database access using ADO.NET. This part also covers the construction of distributed applications using Windows Communication Foundation (WCF), workflow-enabled applications that use the Windows Workflow Foundation (WF) API, and the LINQ to XML API.

Chapter 19: Multithreaded, Parallel, and Async Programming

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 to ensure, explaining a delegate’s intrinsic support for asynchronous method invocations. Next, you will investigate the types within the System.Threading namespace. The remainder of this chapter covers the Task Parallel Library (TPL). Using the TPL, .NET developers can build applications that distribute their workload across all available CPUs in a wickedly simple manner. At this point, you will also learn about the role of Parallel LINQ (PINQ), which provides a way to create LINQ queries that scale across multiple machine cores. We wrap up by examining some new C# keywords introduced in .NET 4.5, which integrate asynchronous method calls directly into the language.

Chapter 20: File I/O and Object Serialization

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 create (and destroy) a directory system programmatically. You will also learn how to move data into and out of various streams (e.g., file based, string based, and memory based). The latter part of this chapter will examine 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. After you understand the basics, you will learn how to customize the serialization process using the ISerializable interface and a set of .NET attributes.

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

In this first of three database-centric chapters, you will take your first look at the database access API of the .NET platform, ADO.NET. Specifically, this chapter will introduce you to the role of .NET data providers and how to communicate with a relational database using the connected layer of ADO.NET, which is 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 the first iteration of a custom data access library (AutoLotDAL.dll); you will use this library throughout the remainder of this book.

Chapter 22: 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 and data adapter objects. You will also learn about the many tools of Visual Studio 2010 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, as well as how to apply LINQ queries to in-memory DataSet objects using LINQ to DataSet.

Chapter 23: ADO.NET Part III: The Entity Framework

This chapter wraps up your investigation of ADO.NET by examining the role of the Entity Framework (EF). Essentially, EF is a way for you to author data-access code using strongly typed classes that directly map to your business model. Here, you will come to understand the role of EF Object Services, the Entity Client and Object Context, and the composition of an *.edmx file. While doing so, you will learn to interact with relational databases using LINQ to Entities. You will also build the final version of your custom data-access library (AutoLotDAL.dll), which you will use in several of the remaining chapters of the book.

Chapter 24: Introducing LINQ to XML

Chapter 14 introduced you to the core 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 XML documents. You will begin by learning about the “warts” that were present in .NET’s initial foray into XML manipulation as you use the types of the System.Xml.dll assembly. With this brief history lesson behind you, you will explore how to create XML documents in memory, how to persist them to the hard drive, and how to navigate their contents using the LINQ programming model (LINQ to XML).

Chapter 25: Introducing Windows Communication Foundation

Until this point in the book, all of the sample applications have executed on a single computer. In this chapter, you will learn about the Windows Communication Foundation (WCF) API that allows you to build distributed applications in a symmetrical manner, regardless of their underlying plumbing. This chapter will expose you to the construction of WCF services, hosts, and clients. As you will see, WCF services are extremely flexible because they allow clients and hosts to leverage XML-based configuration files to specify addresses, bindings, and contracts declaratively.

Chapter 26: Introducing Windows Workflow Foundation

In this chapter, you will begin by learning about the role of a workflow-enabled application, and you will come to understand the various ways to model business processes using the .NET 4.0 WF API. Next, you will examine the scope of the WF activity library, as well as learn how to build custom activities that will use the custom database access library you created earlier in the book.

Part VII: Windows Presentation Foundation

.NET 3.0 introduced programmers to an amazing API called Windows Presentation Foundation (WFP). This API has quickly become the heir apparent to the Windows Forms desktop programming model. In essence, WPF allows you to build desktop applications that incorporate vector graphics, interactive animations, and data-binding operations using a declarative markup grammar called XAML. Furthermore, the WPF control architecture provides a trivial way to restyle the look-and-feel of a typical control radically using little more than some well-formed XAML.

Chapter 27: Introducing Windows Presentation Foundation and XAML

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 (e.g., 2D and 3D graphics, animations, and rich documents) 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 without XAML, as well as using nothing but XAML, and by using a combination of both approaches. You will wrap up the chapter by building a custom XAML editor that you will use for the remainder of the WPF-centric chapters.

Chapter 28: Programming with WPF Controls

This chapter will expose you to the process of using intrinsic WPF controls and layout managers. For example, you will learn to build menu systems, splitter windows, toolbars, and status bars. This chapter will also introduce you to a number of WPF APIs (and their related controls), including the WPF Documents API, the WPF Ink API, and the data-binding model. Just as importantly, this chapter will begin your investigation of Expression Blend IDE, which simplifies the task of creating rich UIs for a WPF application.

Chapter 29: WPF Graphics Rendering Services

WPF is a graphically intensive API; given this fact, WPF provides three ways to render graphics: shapes, drawings and geometrics, and visuals. In this chapter, you will evaluate each option and learn about a number of important graphics primitives (e.g., brushes, pens, and transformations) along the way. This chapter will also examine a number of ways in which Expression Blend can help you simplify the process of creating WPF graphics, as well as how to perform hit-testing operations against graphical data.

Chapter 30: WPF Resources, Animations, and Styles

This chapter will introduce you to three important (and interrelated) topics that will deepen your understanding of the Windows Presentation Foundation API. The first order of business is to learn the role of logical resources. As you will see, the logical resource (also termed an object resource) system provides a way for you to name and refer to commonly used objects within a WPF application. Next, you will learn how to define, execute, and control an animation sequence. Despite what you might be thinking, however, WPF animations are not limited to the confines of video game or multimedia applications. You will wrap up the chapter by learning about the role of WPF styles. Similar to a web page that uses CSS or the ASP.NET theme engine, a WPF application can define a common look-and-feel for a set of controls.

Chapter 31: Dependency Properties, Routed Events, and Templates

This chapter begins by examining two topics that are important when creating a custom control: dependency properties and routed events. After you understand these topics, you will learn about the role of a default template, as well as how to view them programmatically at runtime. After this foundation has been laid, the remainder of this chapter will examine how to build custom templates.

Part VIII: ASP.NET Web Forms

Part 8 is devoted to an examination of constructing web applications using the ASP.NET programming API. Microsoft designed ASP.NET to model the creation of desktop user interfaces by layering an event-driven, object-oriented framework on top of a standard HTTP request/response.

Chapter 32: Introducing ASP.NET Web Forms

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 (e.g., C# and VB .NET). 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 33: ASP.NET Web Controls, Master Pages, and Themes

Whereas the previous chapter showed you how to construct ASP.NET Page objects, this chapter will examine 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. This chapter will also illustrate the role of master pages and the ASP.NET theme engine, which is a server-side alternative to traditional style sheets.

Chapter 34: ASP.NET State Management Techniques

This chapter extends your understanding of ASP.NET by examining various ways to handle state management under .NET. Like classic ASP, ASP.NET allows you to create cookies and application-level and session-level variables quite easily. However, ASP.NET also introduces a new state management technique: the application cache. After you look at the numerous ways to handle state with ASP.NET, you will examine the role of the HttpApplication base class and learn how to alter the runtime behavior of your web application dynamically using the web.config file.

Downloadable Appendixes

As if 34 chapters were not enough, I have made two additional chapters available for download from the home page of this book at the Apress web site (www.apress.com). The first appendix covers the basics of the Windows Forms API, which is used for a few of the UI examples in this text. The second appendix examines the platform-independent nature of .NET via the Mono platform.

Downloadable Appendix A: Programming with Windows Forms

The original desktop GUI toolkit that shipped with the .NET platform is called Windows Forms. This appendix will walk you through the role of this UI framework and illustrate how to build main windows, dialog boxes, and menu systems. You will also learn about the role of form inheritance and see how to render 2D graphical data using the System.Drawing namespace. You will wrap things up by building a (semicapable) painting application that illustrates the various topics discussed throughout this appendix.

Downloadable Appendix B: Platform-Independent .NET Development with Mono

Last but not least, Appendix B covers how to use an open source implementation of the .NET platform named Mono. You can use Mono to build feature-rich .NET applications that can be created, deployed, and executed upon a variety of operating systems, including Mac OS X, Solaris, 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.

Obtaining This Book’s Source Code

You can find all of the code examples contained in this book available as a free download from the Source Code/Download area of the Apress website. Simply navigate to 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# 5

With this book, you can download a self-extracting *.zip file. After you unzip the contents, you will find that the code has been partitioned on a chapter-by-chapter basis.

On a related note, be aware that you will find “Source Code” notes, such as the following, in many of the book’s chapters. These notes serve as your visual cue that you can load the example under discussion into Visual Studio for further examination and modification.

images Source Code This is a source code note that refers you to a specific directory in the ZIP archive.

To open a solution into Visual Studio, use the File images Open images Project/Solution menu option, and then navigate to the correct *.sln file within the correct subdirectory of the unzipped archive.

Obtaining Updates for This Book

As you read through this text, you might find an occasional grammatical or code error (although I sure hope not). If this is the case, please accept my apologies. Being human, I am sure that a glitch or two might be present, despite my best efforts. If this is the case, you can obtain the current errata list from the Apress web site at www.apress.com (again, this is located 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 would like 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# SixthEd” in the Subject line somewhere):

[email protected]

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, please be aware that I am not trying to be a jerk, nor am I trying to avoid talking 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 whether you will buy it). I hope you enjoy reading this book and putting your newfound knowledge to good use.

— Andrew Troelsen

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.156.202