CC is a modern, object-oriented language, designed by Microsoft to be the language of choice for programming the .NET Framework..NET provides a new environment for developing almost any Windows-based or web-based application.
By taking the 'Fast Track' to C#, you have a compact guide to this new world. Spanning an extensive range of topics, this book presents a tutorial to the C# language itself, before taking you deeper into programming the .NET Framework with C#.
Fast Track C# delivers the information you need to exploit this exciting new environment, and to start building real-world applications as quickly as possible.
This book is the ideal .NET jump-start for experienced Java or C++ programmers with some familiarity with Windows development, who are looking to orientate themselves quickly in the new environment of .NET.
What you will learn from this book
Understanding what C# is, and how it fits into the .NET Framework
A concise introduction to all the main features of the C# language, with Java and C++ comparisons noted
Using threads, reflection and .NET attributes from C#
Using the .NET base classes
Writing and deploying Windows applications with C# and Visual Studio .NET
Creating and configuring .NET assemblies
Accessing databases with ADO.NET, and using XML in C#
Integrating your existing COM components with the .NET Framework
COM+ Services in the .NET Framework
Building web applications with ASP. NET
Creating web services with C#
Introduction
Who Is This Book For?
What You Need to Use This Book
What Does This Book Cover?
Conventions
Technical Support
Source Code
Errata
p2p.wrox.com
Chapter 1: Overview of .NET and the CLR
What is .NET?
Compiling and Executing a C# Application
Compilation
Execution
Microsoft Intermediate Language
MSIL Programming Methodology
MSIL Data Handling
Common Type System (CTS)
System.Object
Common Language Specification (CLS)
Language Interoperability
The .NET Base Class Library (BCL)
Assemblies
Application Domains
JIT Compilation
The Garbage Collector
Summary
Chapter 2: Introduction to C#
Why Do We Need C#?
Problems with Existing Languages
C and C++
Visual Basic
Java
Enter C#!
Strengths of C#
Simplicity
Variables and Type Safety
Flow Control Statements
Mature Object-Oriented Functionality
Unsafe Code
XML Documentation
Common Language Runtime
C# Compared to Other .NET Languages
Managed C++
Visual Basic .NET
J#
JScript. NET
C# Applications
ASP.NET
Web Forms
Mobile ASP.NET
Web Controls
Web Services
Windows Applications
Windows Controls
Windows Services
Class Libraries
Console Applications
The C# Compiler
Using the Compiler
Summary
Chapter 3: C# Basics
Starting Out
Executables in C#
Using Visual Studio .NET
Program Structure
Basic Syntax
Comments
Types
Value and Reference Types
Boxing
C#'s Built-in Types
Constants
Operators
Creating and Initializing Variables
Variable Comparisons
String Construction
Arrays
Statements
The goto Statement
The if Statement
The for Statement
The break and continue Keywords
The do and while Statements
The foreach Statement
The switch Statement
Defining and Calling Methods
Method Overloading
Error Handling
Exception Classes
Console I/O
Console Input
Console Output
Summary
Chapter 4: Object-Oriented Features of C#
Enumerations
Structs
Defining Methods for Structs
Struct Constructors
Order of Declaration
Classes
Constructors and Destructors
Destructors
Constant and Read-Only Members
The this Reference
Properties
Static Members
Inheritance
Using Base Class References
Protected Access
Calling Base Class Constructors
Virtual Methods
Hieing Base Class Methods
Accessing Base Class Members
Abstract Classes and Methods
Preventing Derivation
Casting
The Object Class
Operator Overloading
Interfaces
Interfaces and inheritance
Indexers
Summary
Chapter 5: Advanced C#
More about Classes
Variable Parameter Lists
User-Defined Conversions
The Preprocessor
#define, #undef and #if
#warning and #error
#line
#region and #endregion
Delegates
Events
Unsafe Code
A Brief introduction to Pointers
The fixed Keyword
stackalloc Keyword
XML Documentation
Producing Documentation
An XML Documentation Example
Summary
Chapter 6: .NET Programming with C#
Namespaces and the Using Keyword
Namespaces
Using Namespaces in Programs
Reflection and the Type Class
The Type Class
Attributes
Using Attributes
Writing Custom Attributes
Using Attributes
Collections and Arrays
Arrays
Collections
Threading
Application Domains
The System.Threading Namespace
Summary
Chapter 7: Working with the .NET Base Class Library
.NET Class Library Namespaces
String Handling in C#
The System.String Class
Manipulating Strings
The StringBuilder Class: Mutable Strings
The File System with C#
Files and Folders
Copying, Deleting, and Moving Files and Folders
Reading, Writing, and Streams
Binary Files
Text Files
Using XML in C#
Writing to an XML File
Reading an XML File
XML Serialization
An HTML Content Describer
Summary
Chapter 8: Building Windows Applications
Windows Forms
Windows Controls
Event Handling
Custom Drawing onto your Form
Simple Calculator Application
Menus
Deploying Applications
Setup and Deployment Projects
Summary
Chapter 9: Assemblies and ILDASM
What is an Assembly?
Benefits of Assemblies: The End of "DLL Hell"
Benefits of Assemblies: Side-by-Side Execution
What is in an Assembly?
.NET System Assemblies and References
Namespaces and Assemblies are Different
Culture
Private and Shared Assemblies
Global Assembly Cache (GAC)
Strong Names
Version Numbers
Shared Assembly Version Checking
Structure of Assemblies
Example Assembly: Shapes Class Library
Assembly Attributes
Informational Assembly Attributes
Culture Attribute
Version Attribute
Strong Name Attributes
Viewing the Contents of an Assembly: ILDASM
Viewing Contents of the Manifest
Viewing Contents of a Method
Outputting the Contents of an Assembly as IL
Private Assemblies
Simple .Client Program
Private Assembly Binding and Searching
Application Configuration Files
Shared Assemblies
Building a Shared Assembly
Installing a Shared Assembly Into the Global Assembly Cache
Side-by-Side Installation of Different Versions in the GAC
Shared Assembly Searching
Shared Assembly Configuration Files
Digital Signatures and SignCode
Code Access Security
Evidence and Security Policy
Code Permissions
Advanced Assembly Topics
Reflection and the Assembly Class
Explicit and Implicit Loading
Dynamic Assemblies
Cross-Language Support
COM Interop Assemblies
Summary
Chapter 10: Data Access with ADO.NET
ADO.NET
.NET Data Providers
ADO.NET Class Structure
Data Consumer Classes
.NET Provider Classes
Other .NET Framework Classes
Using ADO.NET
Example Database: MSDE and Northwind
Microsoft Access Northwind Sample for OLE DB
.NET Data Provider Examples
Data Reader for SQL Server
Data Reader with OLE DB .NET Data Provider
Data Reader with ODBC .NET Data Provider
Stored Procedures
SQL Execute Methods in .NET Data Providers
Transactions
DataSet Examples
Data Adapter Class
DataSet Structure for Tables, Rows, and Columns
Navigating Relationships and Tables using a DataSet
Updating Data
Finding and Adding Rows
Deleting Data using a DataSet with SQL Server
Displaying Data with a DataGrid
Strongly Typed DataSets
Using XML in ADO.NET
ReadXml0 and WriteXml0
XmIDataDocument
Summary
Chapter 11: COM and COM+ Interoperability
COM Interop
Generating Metadata
Creating and Invoking
Using Reflection
Interop with ActiveX Controls
Interop with COM Clients
Private Deployment
Shared Deployment
Taking Advantage of COM+ Services
Building a Serviced Component
Configuring Transaction Support
Configuring Queuing
Platform Invocation Services
Identifying DLL Functions
Using the DIIImportAttribute
PInvoke Marshalling
Summary
Chapter 12: ASP,NET
ASP.NET - Why is it Here?
Creating a Web Forms Project
Adding Controls
Code-Behind Files
Validation Controls
User Controls
Adding a User Control to a Web Form
Accessing a User Control from the Code-Behind
Additional Server Controls
Data Binding with Web Controls
The DataGrid
The Repeater
ASP.NET Configuration
Using web.cenfig
Authentication
Authorization
Application Configuration
Diagnostics in ASP.NET - Tracing
Page-Level Tracing
Application-Level Tracing
Summary
Chapter 13: Web Services
Web Service Problem Domains
Platform Interoperability
Distributed Computing
Writing a Web Service
WebService and WebMethod Attributes
Testing and Debugging a Web Service
Using HTTP POST
Using SOAP
Web Services Description Language
Creating a Web Service Client
Adding a Web Reference Using Visual Studio .NET
XML Serialization
Customizing XML Serialization
XML Schemas
A Windows Form Client
Asynchronous Web Service Calls
Using Callback Delegates
WebMethod Properties in Detail
Web Service Transactions
Web Service Caching
State Management
State Management Drawbacks
SOAP Headers
Using SOAP Headers from the Client
Summary
Index
C# is Microsoft's new language, designed specifically for its new platform, the .NET Framework.
The basic premise of .NET is quite simple: all .NET programs are compiled to an intermediate language (IL, or MSIL) rather than to native code that can be understood by the computer's processor. This IL code is then compiled to native code either when the application is installed, or when the application is run. Code run on the .NET Framework is managed by a run-time environment called the Common Language Runtime (CLR). This runtime provides memory-management features such as automatic garbage collection and type-safety checking, and is similar in some ways to Java's Virtual Machine.
The .NET Framework also provides a large number of base classes, whose functionality is available to all languages that use the CLR, and which allow the developer to achieve many common programming tasks. In the long term (if the .NET Framework is migrated to non-Windows platforms), these classes may provide a degree of platform-independence by avoiding the necessity of calling OS-specific APIs.
For the last few years, developers working chiefly on Microsoft platforms have had two principal languages to work with: they could choose the power of Visual C++, or the ease of use of Visual Basic. Although Visual Basic did allow a lot of power to those who were prepared to stretch it to its limits, and Visual C++ had a host of AppWizards designed to simplify life for the C++ developer, as a general rule applications built in Visual C++ took longer to develop, but had much better performance than those developed in Visual Basic.
The release of the .NET Framework changes all that in two ways. Firstly, Visual Basic .NET is much more powerful than its predecessor. All .NET languages compile to Intermediate Language, and can take advantage of the features supplied by the Common Language Runtime. Added to this are a number of more powerful features in Visual Basic. NET, such as true object-oriented features and exception handling with Try... Catch. However, probably the more important development is the creation of an entirely new language - C#, the subject of this book.
C# is a new language derived from C++, but designed to support Rapid Application Development in a similar way to Visual Basic. Cf allows us to design both Windows and web applications quickly and easily using form designers; Visual Studio .NET takes care of much of the code, such as instantiating the controls and writing the definitions for event handlers. This of course comes on top of the features provided by the Common Language Runtime, such as automatic garbage collection. However, C~ also gives us most of the power of C++, even allowing the use of direct access to memory addresses through pointers in blocks of "unsafe" code (code that bypasses C4f's type safety features). Add to this the fact that C# is the only language designed from the ground up for the .NET Framework, and it's clear why C# looks set to become the language of choice for .NET programming.
Who Is This Book For?
This book is for anybody who wants to learn about C~ and the .NET platform. This book is not a beginner's book - we've assumed that you've got some programming experience, perhaps in Windows programming with Visual C++. Alternatively, you may be coming from a Java background and want to see what all the fuss is about. Some of the later chapters assume some basic knowledge of Microsoft technologies such as ADO, and COM.
What You Need to Use This Book
This book and the code it contains have been checked against the release version of Microsoft Visual Studio .NET. Its minimum requirements are therefore the same as those for that product: a PII-450 CPU, Microsoft Windows 2000 Professional or higher, at least 128 MB of RAM, and around 3GB of free space on your hard drive.
What Does This Book Cover?
This book is designed to provide an introduction to programming in C# on the .NET platform. As we have already implied, these two topics are closely connected. Because all code written for the .NET Framework will make extensive use of the .NET base classes, for example for input/output, data manipulation, and file handling, we cover these extensively, as well as the syntax of the Cg language itself.
We start off by taking quick overviews of the .NET Framework, and C#, before moving on to look at the C# language in detail. Next we cover the basics of .NET programming - tile .NET class libraries, building Windows applications, data access with ADO.NET, and the unit of .NET deployment – the assembly. Finally, we look at a few more advanced topics: integrating C# programs with COM and with Component Services, building ASP.NET web applications, and Web Services in C#.
Let's take a brief look at what we cover in each of the individual chapters of this book:
Chapter 1: Overview of .NET and the CLR
In this chapter we look at the .NET Framework, we look at some of the problems that the .NET Framework addresses, and we see how it does this. The Common Language Runtime (CLR) is discussed, along with Intermediate Language (IL) and the Common Type System (CTS).
Chapter 2- Introduction to C#
This chapter looks at the Cg language - it starts with a discussion of why we need another programming language. C# is also compared to other programming languages currently in use. The chapter then looks at the types of application that can be built using C# in the .NET environment. Finally, we look at the CS compiler.
Chapter 3: C# Basics
This chapter is the start of the detailed look at CS. Throughout the chapter, any similarities and differences between CS and C++ and Java are noted. We look at the features of a CS program, including the data types, operators, and statements used in the language. Program control and loops are examined, and also the calling of methods and method overloading. Errors and how to handle them are also discussed.
Chapter 4: Object-Oriented Features of C#
This chapter looks at the functionality built into C# for working with objects. We begin with a discussion of enumerations, before going on to look at structs and classes. The members of classes - fields, properties, methods, and events - are all discussed. We also look at Od concepts such as inheritance, and see how they are implemented in CS. Other topics covered include interfaces and abstract classes, operator overloading, and indexers.
Chapter 5: Advanced C#
Now we go on to look at some of the more advanced features of CS. We start by looking at some advanced techniques involved with working with classes, such as variable argument lists. Next we look at C#'s preprocessor directives, which we can use to modify how our code is compiled, using pointers and unsafe code in C#, delegates, and events, before finally looking at XML documentation.
Chapter 6: .NET Programming with C#
Having finished our look at the CS language itself, this chapter starts dealing with how the language is used in the .NET environment. We look at reflection, which allows us to inspect types and objects at run time and find out what they are and what they can do. Then we look at .NET attributes, markers that we can apply to our code to provide additional run time information. Next, we look at collections and arrays, and finish off the chapter with a look at how .NET supports writing multithreaded applications in CS.
Chapter 7: Working with the .NET Base Class Library
This chapter takes us on a tour of some of the most commonly used base classes. We write example programs that show the base classes in action, and demonstrate how to perform common programming tasks in C# such as string manipulation, file handling, reading and writing to files, reading and writing XML, and XML serialization.
Chapter 8: Building Windows Applications
This chapter uses Windows forms to aid Rapid Application Development (RAD). After a quick look at creating applications without Visual Studio, the Visual Studio .NET IDE is used to add controls onto Windows forms. A sample Windows application is used to demonstrate creating menus, handling events, and other aspects of building Windows applications such as the standard dialogs. We then look at how to deploy applications from within Visual Studio .NET.
Chapter 9: Assemblies and ILDASM
In this chapter, we look at the concepts of assemblies and manifests. Assemblies are .NET components that include both the code itself and all the metadata needed to describe the component - its manifest. We explore the ILDASM tool which, allows us to view the contents of an assembly. The .NET Framework uses shared names to locate assemblies regardless of their physical location in the file system, so we see how we can create shared names for our assemblies. This allows assemblies to be shared by multiple applications. We also take a look at code access security.
Chapter 10: Data Access with ADO.NET
In this chapter, we look at data access on the .NET platform using ADO.NET, the latest of Microsoft's data access technologies. After a quick look at the data consumer, and provider classes, we look at the forward-only, read-only data reader, and using stored procedures and transactions in ADO.NET. Next, we see how to use the DataSet to access and update a database, and how to bind a Da DataGrid, and introduce some of Visual Studio .NET's built-in features for data access. Finally, we examine some of ADO.NET's functionality for working with XML.
Chapter 11: COM and COM+ Interoperability
Next, we look at integrating C# applications and components with existing code. First, we see how to call existing COM components from C# applications, using both early and late binding. Next, we discuss calling C#' components as if they were COM components, by creating a wrapper COM object and exporting a type library. After an overview of Component Services, we see how to use these features with .NET components. We look at creating transactional components under .NET and registering them with COM+ Services, and we see how to take advantage of some of the other main features of COM+ from our C~ component, such as message queuing. Finally, we look at calling unmanaged functions using Plnvoke (Platform Invocation Services).
Chapter 12: ASP.NET
In our penultimate chapter, we see how to create web applications using ASP.NET, the latest incarnation of ASP. After an overview of the new features on offer, we show an example of creating a simple ASP.NET web application. We demonstrate the use of server-side controls in maintaining state and in validating user input. Finally, we look at configuring web applications, and some of the monitoring tools offered by ASP. NET.
Chapter 13: Web Services
Finally, we look at another, new kind of web application - the web service. Web services are a way of exposing the application logic on a server over the Internet. This allows the client to use the data on the server, without being tied to particular pre-constructed static or dynamic web pages. After a look at what web services are, and the protocols they use, we demonstrate how to build a Web service, and a client that will consume this service, and how to use asynchronous methods to handle possible interruptions to our service caused by network turmoil.
Conventions
We have used a number of different styles of text and layout in the book to help differentiate between the different kinds of information. Here are examples of the styles we use and an explanation of what they mean:
Bullets appear indented, with each new bullet marked as follows:
Important Words are in a bold type font
Words that appear on the screen in menus like the File or Window are in a similar font to the one that you see on screen
Keys that you press on the keyboard, like Ctrl and Enter, are in italics
Code has several styles. If it's a word that we're talking about in the text, for example, when discussing the if... else loop, it's in this font. If it's a block of code that you can type in as a program and run, then it's also in a gray box:
public static void Main ( )
{
AFunc (i, 2, "abc" );
Sometimes you'll see code in a mixture of styles, like this:
// If we haven't reached the end, return true, otherwise
// set the position to invalid, and return false.
pos++;
if (pos < 4
return true;
else {
pos = -1;
return false;
)
The code with a white background is code we've already looked at and that we don't wish to examine further.
Advice, hints, and background information come in an italicized, indented ~bnt like this.Important pieces of information Come in boxes like thiS2
We demonstrate the syntactical usage of methods, properties (and so on) using the following format:
Regsvcs BookDistributor.dll [COM+AppName] [TypeLibrary. tbl]
Here, italicized parts indicate object references, variables, or parameter values to be inserted; the square braces indicate optional parameters.Technical Support
If you wish to directly query a problem in the book with an expert who knows it in detail then e-mail support @wrox.com with the title of the book and the last four numbers of the ISBN in the subject field. A typical e-mail should include the following things:
The name, last four digits of the ISBN, and page number of the problem in the Subject field.
Your name, contact information, and the problem in the body of the message.
We won't send you junk mail. We need the details to save your time and ours. When you send an e-mail message, it will go through the following chain of support:
Customer Support - Your message is delivered to one of our customer support staff, who are the first people to read it. They have files on most frequently asked questions and will answer anything general about the book or the web site immediately.
Editorial - Deeper queries are forwarded to the technical editor responsible for that book. They have experience with the programming language or particular product, and are able to answer detailed technical questions on the subject. Once an issue has been resolved, the editor can post the errata to the web site.
The Authors - Finally, in the unlikely event that the editor cannot answer your problem, they will forward the request to the author. We do try to protect the author from any distractions to their writing, however, we are quite happy to forward specific requests to them. All Wrox authors help with the support on their books. They will mail the customer and the editor with their response, and again all readers should benefit.
The Wrox support process can only offer support to issues that are directly pertinent to the content of our published title. Support for questions that fall outside the scope of normal book support is provided via the community lists of our http://p2p.wrox.com/forum.
Source Code
All of the source code for this book is available at the wrox.com web site. When you arrive at http://www.wrox.com/, locate the title through our search facility or by using one of the title lists. Then, click on the Download Code link on the book's detail page, and you can obtain the code.
The files that are available for download from our site have been archived using WinZip. When you've saved them to your hard drive, you'll need to extract the files they contain using a decompression program such as WinZip or PKUnzip. When you extract the files, ensure that your software has the Use folder names (or some equivalent) option switched on.
Errata
We have made every effort to ensure that there are no errors in the text or the code. However, no one is perfect and mistakes do occur. If you find an error in this book, we'd be very grateful if you'd tell us about it. By sending in errata, you may save another reader hours of frustration, and you'll be help!ng us to provide information of even higher quality. Simply e-mail your discovery to 8upport@wrox.com; your information will be checked and, if found correct, posted to the errata page or used in subsequent editions of the book. To find errata on the web site, log on to http://www.wrox.com, and locate the title through the search facility. Then, on the book's detail page, click on the Book Errata link. On this page you'll be able to view any errata that have been already submitted and verified. You can also click the Submit Errata link to notify us of any errata that you may have found.
p2p.wrox.com
For author and peer discussion, join the P2P mailing lists. Our unique system provides programmer to programmerTM contact on mailing lists, forums, and newsgroups, all in addition to our one-to-one e-mail support system. Be confident that your query is being examined by the many Wrox authors, and other industry experts, who are present on our mailing lists. At p2p.wrox.com you will find a number of different lists that will help you, not only while you read this book, but also as you develop your own applications.
To subscribe to a mailing list just follow these steps:
1. Go to http://p2p.wrox.com/.
2. Choose the appropriate category from the left menu bar.
3. Click on the mailing list you wish to join.
4. Follow the instructions to subscribe and fill in your e-mail address and password.
5. Reply to the confirmation e-mail you receive.
6. Use the subscription manager to join more lists and set your mail preferences.