Get hundreds of recipes covering every application type—from Microsoft Windows to Web pages, Web services, Windows Forms, and Windows services.. Mastering the development of Microsoft .N
Trang 3No half-baked solutions Get expert code from expert developers.
Get hundreds of recipes covering every
application type—from Microsoft Windows to Web pages, Web services, Windows Forms, and
Windows services.
Discover expert ways to solve common Web
application and network programming challenges.
Manage files, directories, and streams with the NET I/O classes.
Access databases using Microsoft ADO.NET.
Tackle advanced techniques for multithreading, manipulating XML data, NET Remoting, and
reusing common patterns.
Develop rich multimedia applications using the
Trang 4Help protect your applications with code access security, role-based security, and cryptography.
based solutions.
Interoperate with legacy Win32 API and COM-About the Author
Allen Jones is coauthor of the popular C# for Java
Developers, Microsoft NET XML Web Services Step by Step, and Programming NET Security A 13-year
technology veteran, he is known for the depth of his C# and NET expertise He specializes in developing and implementing enterprise solutions, including e- commerce and security systems.
Trang 6The example companies, organizations, products, domain names, e-mailaddresses, logos, people, places, and events depicted herein are
fictitious No association with any real company, organization, product,domain name, e-mail address, logo, person, place, or event is intended
Trang 7Introduction
Trang 8Mastering the development of Microsoft NET Framework applications inC# is less about knowing the C# language and more about knowing how
to use the functionality of the NET Framework class library most
effectively The C# Programmer's Cookbook explores the breadth of the.NET Framework class library and provides specific solutions to commonand interesting programming problems Each solution (or recipe) is
presented in a succinct problem/solution format and is accompanied byworking code samples
The C# Programmer's Cookbook is not intended to teach you how toprogram, nor to teach you C# However, if you have even the most
rudimentary experience programming applications built on the NET
Framework using C#, you will find this book to be an invaluable resource
Ideally, when you are facing a problem, this book will contain a recipethat provides the solution—or at least it will point you in the right
direction Even if you are simply looking to broaden your knowledge ofthe NET Framework class library, the C# Programmer's Cookbook is theperfect resource to assist you You cannot become proficient with C# andthe classes in the NET Framework class library merely by reading aboutthem; you must use them and experiment with them by writing programs,programs, and more programs The structure and content of this bookand the real-world applicability of the solutions it provides offer the
perfect starting point from which to kick-start your own experimentation
Note The code in this book has been written for and tested on
version 1.1 of the NET Framework In many cases, you willfind that the sample code will run on version 1.0 of the NETFramework, but this has not been tested and no guaranteesare made
Trang 9The code for all recipes in the C# Programmer's Cookbook is availableonline at http://microsoft.com/mspress/books/6456.asp To download the
sample files, click the Companion Content link in the More Informationmenu on the right side of the page This action loads the CompanionContent page, which includes a link for downloading the sample files Toinstall the sample files, click the Download The Book's Sample Files linkand follow the instructions in the setup program A link to the samplecode will be added to your Start menu
The code is provided as a set of Visual Studio NET 2003 solutions andprojects organized by chapter and recipe number Each chapter is a
separate solution, and each recipe is a separate project within the
chapter's solution Some recipes in Chapter 11 and Chapter 12 that
demonstrate network programming include separate projects that containthe client and server elements of the recipe's solution
Although all samples are provided as Visual Studio NET projects, mostconsist of a single source file that you can compile and run independent
of Visual Studio NET If you are not using Visual Studio NET 2003 youcan locate the code for a particular recipe by navigating through the
directory structure of the sample code For example, to find the code forrecipe 4.3, you would look up the code in the directory
"Chapter04\Recipe04-03" If you use the command-line compiler, ensurethat you include references to all required NET class library assemblies
Some of the sample applications require command-line arguments
Where required, the recipe's text will describe the arguments If you areusing Visual Studio NET, you can enter these arguments in the projectproperties (under the Debugging node of the Configuration Propertiesitem) Keep in mind that if you need to enter directory or file names thatincorporate spaces, you will need to place the full name in quotationmarks
Some additional steps are required to install the two virtual directoriesused for the examples that accompany Chapter 7, "ASP.NET and WebForms," and Chapter 12, "XML Web Services and Remoting." These
Trang 10steps are described in a readme.txt file provided with the downloadedcode and on the code download page.
Trang 11Microsoft Internet Information Services (IIS) for some recipes in
Chapter 7 and Chapter 12
The minimum hardware specification for development is a 450-MHz
Pentium II-class processor, with a minimum of 128 MB of RAM if you'rerunning Microsoft Windows 2000 and 256 MB of RAM if you're runningWindows XP, Windows 2000 Server, or Windows Server 2003 You'llneed about 5 GB of free hard-disk space to install Visual Studio NET
2003 These values are minimums, and your development life will bemuch easier on a system with ample RAM and free disk space
Note Although Microsoft's implementation of the NET Framework for
Windows is the focus of the C# Programmer's Cookbook, animportant goal was to provide a useful resource to all C#
programmers regardless of the platform on which they are
developing or the tools to which they have access Apart fromspecific topics that are not supported on all NET platforms(such as Windows Forms, ADO.NET, and ASP.NET) many ofthe samples in this book are valid across all NET
implementations
Trang 12If you have no programming experience, this book will not teach you how
to program Similarly, if you are a programmer but have little or no C#experience, this book does not provide the structure required to teachyou how to program effectively in C# Depending on your programmingbackground and current level of C# knowledge, the following books canteach you enough about C# and the NET Framework to enable you toget the most from the solutions provided in this book:
Trang 13Advanced NET Remoting (Apress, 2002) Ingo Rammer.
Trang 14Every effort has been made to ensure the accuracy of the book and itscompanion content Microsoft also provides corrections for books throughthe World Wide Web at the following address:
http://www.microsoft.com/mspress/support/
If you have comments, questions, or ideas regarding the presentation oruse of this book or the companion content, you can send them to
2003, go to http://msdn.microsoft.com/vstudio/ You can also call
Standard Support at (425) 635-7011 weekdays between 6 A.M and 6P.M Pacific time, or you can search Microsoft Product Support
Services at http://support.microsoft.com/support
Trang 15Chapter 1: Application Development
Trang 16This chapter covers some of the fundamental activities you will need toperform during the development of your C# solutions The recipes in thischapter describe how to
Build Console and Windows Forms applications (recipes 1.1 and
1.2)
Create and use code modules and libraries (recipes 1.3 and 1.4)
Access command-line arguments from within your applications(recipe 1.5)
Use compiler directives and attributes to selectively include code
at build time (recipe 1.6)
Access program elements built in other languages whose namesconflict with C# keywords (recipe 1.7)
Give assemblies strong names and verify strong-named
assemblies (recipes 1.8, 1.9, 1.10, and 1.11)
Sign an assembly with a Microsoft Authenticode digital signature(recipes 1.12 and 1.13)
Trang 17automatically adds this directory to your environmentpath
The tools provided with the SDK are in the Bin
subdirectory of the directory in which you install the
SDK This directory is not added to your path
automatically, so you must manually edit your path inorder to have easy access to these tools
Most of the tools support short and long forms of thecommand- line switches that control their functionality.This chapter always shows the long form, which ismore informative but requires additional typing For theshortened form of each switch, see the tool's
documentation in the NET Framework SDK
Trang 18Console.Write(msg);
Trang 20}
}
To build a Console application consisting of more than one source codefile, you must specify all the source files as arguments to the compiler.For example, the following command builds an application named
MyFirstApp.exe from the HelloWorld.cs and ConsoleUtils.cs source files.csc /target:exe /main:HelloWorld
Trang 21Problem
You need to build an application that provides a Windows Forms–basedGUI
Solution
Ensure you implement a static method named Main in at least one of your source code files In the Main method, create an instance of a class that extends the System.Windows.Forms.Form class (This is your
application's main form.) Pass your main form object to the static method Run of the System.Windows.Forms.Application class Use the
/target:winexe switch on the C# compiler (csc.exe) when you compile
your assembly
Discussion
Building an application that provides a simple Windows GUI is a worldaway from the development of a full-fledged Windows-based application.However, there are things you must do regardless of whether you arewriting the Windows equivalent of Hello World or the next version of
Microsoft Word, including the following:
For each form you need in your application, create a class that
extends the System.Windows.Forms.Form class.
In each of your form classes, declare members that represent thecontrols that will be on that form, for example buttons, labels,
lists, and text boxes These members should be declared private
or at least protected so that other program elements can't access
them directly If you need to expose the methods or properties ofthese controls, implement the necessary members in your formclass, providing indirect and controlled access to the containedcontrols
Trang 22private Button button1;
Trang 23// Constructor used to create an instance of the form and configure // the form's controls.
Trang 24this.Name = "form1";
this.Text = "C# Programmer's Cookbook";
// Resume the layout logic of the form now that all controls are // configured
this.ResumeLayout(false);
}
// Application entry point, creates an instance of the form, and begins // running a standard message loop on the current thread The message // loop feeds the application with input from the user as events
Trang 25Write and WriteLine methods of the System.Console class.
Figure 1.1 shows the WelcomeForm.exe application in operation greeting
a user named Rupert This version of the application is built using the
/target:exe compiler switch, resulting in the visible Console window in which you can see the output from the Console.WriteLine statement in the button1_Click event handler.
Trang 26applications written in other NET languages
Use types developed in another language from within your C#application
Metadata describing the types contained in the module
Resources, such as icons and string tables, used by the types inthe module
Assemblies consist of one or more modules and an assembly manifest.When there is a single module, the module and assembly manifest areusually built into a single file for convenience When there is more than
Trang 27By building an assembly from multiple modules, you complicate the
management and deployment of the assembly, but under some
circumstances, modules offer significant benefits, including:
The runtime will load a module only when the types defined in themodule are required Therefore, where you have a set of typesthat your application uses rarely, you can partition them into aseparate module that the runtime will load only if necessary Thisoffers the following benefits:
Improved performance, especially if your application isloaded across a network
Minimizing the use of memory
The ability to use many different languages to write applicationsthat run on the common language runtime (CLR) is a great
strength of the NET Framework However, the C# compiler can'tcompile your Microsoft Visual Basic NET or COBOL NET codefor inclusion in your assembly You must first use a language-specific compiler to turn your source into MSIL in a structure thatthe C# compiler can incorporate—a module Likewise, if you want
to allow programmers of other languages to use the types youdevelop in C#, you must build them into a module
To compile a source file named ConsoleUtils.cs into a module use the
command csc /target:module ConsoleUtils.cs The result is the
creation of a file named ConsoleUtils.netmodule The netmodule
extension is the default extension for modules, and the file name is thesame as the name of the C# source file
You can also build modules from multiple source files, which results in asingle file (module) containing the MSIL and metadata for all types
contained in all the source files The command csc /target:module
Trang 28ConsoleUtils.netmodule and WindowsUtils.netmodule, which arenow integral components of the multi-file assembly but are
unchanged by this compilation process (If you attempt to runMyFirstApp.exe without the netmodules present, a
System.IO.FileNotFoundException is thrown.)
Trang 29/target:library ConsoleUtils.cs WindowsUtils.cs.
Before distributing your library, you might consider strong naming it so
Trang 30original Strong naming your library also allows people to install it into theglobal assembly cache, which makes reuse much easier (Recipe 1.9
describes how to strong name your assembly and recipe 1.14 describeshow to install a strong-named assembly into the global assembly cache.)You might also consider signing your library with an Authenticode
signature, which allows users to confirm that you are the publisher of theassembly—see recipe 1.12 for details on signing assemblies with
Authenticode
To compile an assembly that relies on types declared within externallibraries, you must tell the compiler which libraries are referenced using
Trang 31Problem
You need to access the arguments that were specified on the commandline when your application was executed
Solution
Use a signature for your Main method that exposes the command-line arguments as a string array Alternatively, access the command-line
arguments from anywhere in your code using the static members of the System.Environment class.
Trang 33Problem
You need to selectively include and exclude sections of source code fromyour compiled assembly
operation However, such an approach can bloat your code and affectperformance, especially if there are many variations to support or manylocations where evaluations need to be made An alternative approach is
to build multiple versions of your application to support the different targetplatforms and environments Although this approach overcomes the
problems of code bloat and performance degradation, it would be anuntenable solution if you had to maintain different source code for eachversion, so C# provides features that allow you to build customized
versions of your application from a single code base
The #if, #elif, #else, and #endif preprocessor directives allow you to
identify blocks of code that the compiler should include in your assemblyonly if specified symbols are defined at compile time Symbols function
as on/off switches; they don't have values—either the symbol is defined,
or it is not To define a symbol you can use either the #define directive in your code or use the /define compiler switch Symbols defined using
Trang 34In this example, the code assigns a different value to the local variable
platformName based on whether the winXP, win2000, winNT, or Win98 symbols are defined The head of the code defines the symbols win2000 and release (not used in this example) and undefines the win98 symbol
#if winXP // Compiling for Windows XP
platformName = "Microsoft Windows XP";
#elif win2000 // Compiling for Windows 2000 platformName = "Microsoft Windows 2000";
Trang 36symbols winXP OR win2000 are defined AND the symbol release is defined.
Warning You must be careful not to overuse conditional compilation
directives and not to make your conditional expressions toocomplex; otherwise, your code can quickly become
confusing and unmanageable—especially as your projectsbecome larger
A less flexible but more elegant alternative to the #if preprocessor
directive is the attribute System.Diagnostics.ConditionalAttribute If you apply ConditionalAttribute to a method, the compiler will ignore any calls
to the method if the symbol specified by ConditionalAttribute is not
defined at the calling point In the following code, ConditionalAttribute specifies that calls to the DumpState method should be included in a compiled assembly only if the symbol DEBUG is defined during
Trang 37definition of the symbol DEBUG, and the methods of the Trace class are conditional on the definition of the symbol TRACE.
Trang 38Same Name as a Keyword
Problem
You need to access a member of a type, but the type or member name isthe same as a C# keyword
Solution
Prefix all instances of the identifier name in your code with the at sign(@)
Discussion
The Net Framework allows you to use software components developed
in other NET languages from within your C# applications Each languagehas its own set of keywords (or reserved words) and imposes differentrestrictions on the names that programmers can assign to program
elements such as types, members, and variables Therefore, it's possiblethat a programmer developing a component in another language willinadvertently use a C# keyword as the name of a program element Thesymbol @ enables you to use a C# keyword as an identifier and
overcome these possible naming conflicts This code fragment
instantiates an object of type operator (perhaps a telephone operator) and sets its volatile property to true—both operator and volatile are C#
Trang 39ad179f15f7dccca6c6b72a
Trang 40The public key token shown at the end of the listing is the last 8 bytes of
a cryptographic hash code computed from the public key Because thepublic key is so long, NET uses the public key token for display purposesand as a compact mechanism for other assemblies to reference yourpublic key (Chapter 14 includes a general discussion of cryptographichash codes.)
As the name suggests, you don't need to keep the public key (or publickey token) secret When you strong name your assembly (discussed inrecipe 1.9), the compiler uses your private key to generate a digital
signature (an encrypted hash code) of the assembly's manifest The
compiler embeds the digital signature and your public key in the
assembly so that any consumer of the assembly can verify the digitalsignature
Keeping your private key secret is imperative People with access to yourprivate key can alter your assembly and create a new strong name—leaving your customers unaware that they are using modified code
There's no mechanism to repudiate compromised strong name keys Ifyour private key is compromised, you must generate new keys and
distribute new versions of your assemblies that are strong named usingthe new keys You must also notify your customers about the
compromised keys and explain to them which versions of your public key
to trust—in all, a very costly exercise in terms of both money and
credibility There are many ways to protect your private key; the approachyou use will depend on factors such as