Chapter 4, "Creating and Using .NET Collections," covers the fundamentalcollection types in the .NET Framework, including searching andsorting those collections, as well as recipes that
Trang 2description of the topic at hand and then gives you the goods - recipes that explain a brief description of the task, the technique and comments about the technique chosen
by C# experts, Mark Schmidt and Simon Robinson.
Trang 16Copyright © 2004 by Sams Publishing
All rights reserved No part of this book shall be reproduced,stored in a retrieval system, or transmitted by any means,
electronic, mechanical, photocopying, recording, or otherwise,without written permission from the publisher No patent
liability is assumed with respect to the use of the informationcontained herein Although every precaution has been taken inthe preparation of this book, the publisher and author assume
no responsibility for errors or omissions Nor is any liabilityassumed for damages resulting from the use of the informationcontained herein
regarded as affecting the validity of any trademark or servicemark
Warning and Disclaimer
Trang 17as accurate as possible, but no warranty or fitness is implied.The information provided is on an "as is" basis The authors andthe publisher shall have neither liability nor responsibility to anyperson or entity with respect to any loss or damages arisingfrom the information contained in this book
Bulk Sales
Sams Publishing offers excellent discounts on this book whenordered in quantity for bulk purchases or special sales For
Trang 19Mark Schmidt
Trang 20Mark Schmidt is a software engineer at Hewlett-Packard His
current research is in the area of advanced custom user
interfaces Part of this work was the topic of a talk he gave atthe 2001 VSLive! Conference in San Francisco Mark has written
in straight computer programming and ended up at Lucent
Technologies doing mostly Windows COM programming, beforefinally becoming self-employed, combining writing and freelancesoftware development He has an extremely broad experience
of programming on Windows These days, his core specialism is.NET programming, and he is comfortable coding in C++, C#,
VB, and IL and has skills ranging from graphics and Windows
Trang 21Forms to ASP.NET, directories, data access, Windows services,and the native Windows API.
Trang 22So many people were involved or touched in one way or
another by my time spent on this book, but unfortunately, Ican't list you all
To my wife, Cher, and children, Jordan, Jake, Jonah, and
Mallorie You are my life and the reason I strive to succeed Ilove you all more than words can convey
To my Dad, who instilled in me the principle of working hard soyou can play hard later
To the many editors and people at Sams Publishing and
especially to Neil Rowe You all know how to make a hard jobfun and worthwhile, and I will always treasure the relationshipNeil and I started
Damon, Mike, and Byron, you guys put the fun in my life
Thanks for pulling me out of my hole once in a while and forbeing the close friends you guys are
Charlie, thanks for making me look good in front of my peers
To my extended family at River Rock Church, thank you forshowing so much love and support It brings me comfort andpeace to see the love of our Lord in all your faces
Finally, I'd like to especially acknowledge my two brothers,Daron and Scott, who have stuck by my side and each other'sthrough all of life's trials Brothers until the end, I love youguys
Mark Schmidt
Trang 23As the reader of this book, you are our most important critic
and commentator We value your opinion and want to know
what we're doing right, what we could do better, what areasyou'd like to see us publish in, and any other words of wisdomyou're willing to pass our way
As an associate publisher for Sams Publishing, I welcome yourcomments You can email or write me directly to let me knowwhat you did or didn't like about this bookas well as what wecan do to make our books better
Please note that I cannot help you with technical problems
related to the topic of this book We do have a User Services group, however, where I will forward specific technical
questions related to the book.
When you write, please be sure to include this book's title andauthor as well as your name, email address, and phone number
I will carefully review your comments and share them with theauthor and editors who worked on the book
Email: feedback@samspublishing.com
Mail: Michael Stephens
Associate Publisher Sams Publishing
800 East 96th Street Indianapolis, IN 46240 USA
For more information about this book or another Sams
Publishing title, visit our Web site at www.samspublishing.com.Type the ISBN (excluding hyphens) or the title of a book in theSearch field to find the page you're looking for
Trang 24When Visual C# NET first arrived on the scene, developers
everywhere were hit with a vast wave of documentation andtutorials from magazine articles, books, and Web sites The
obligatory "Hello World" programs were popping up left and
right as developers began their path to understanding this newlanguage created by Microsoft Those days of learning this
exciting new technology are now gone for some developers, andthey now need more in-depth materialmaterial that corresponds
constructed to first show you how to accomplish a task using acertain technique and then to follow with comments that
provide a closer inspection of the solution
Along with the immense array of task-specific recipes is a largecollection of source code, which is freely available on the SamsWeb site, http://www.samspublishing.com Most recipes in thisbook utilize source code contained within an application
developed for the task it is explaining Even though some of thesource code might be terse and to the point, some of the
applications would make a great stepping stone to larger, moreinvolved solutions For instance, Chapter 10, "Programming
Graphics with GDI+," uses the source code from an image-editing application with full support for image scaling, cropping,rotation, and even a print preview dialog Chapter 8, "Windows
Trang 25Studio NET 2003 Integrated Development Environment (IDE).Additionally, Chapter 13, "XML in NET," contains a full XML
impossible task Microsoft Visual C# NET 2003 Developer's
Cookbook provides the help you need when you just want to
know how to perform a single task, and it offers real-world,application-specific information The companion Web site forthis book, http://www.csharpcookbook.com, provides additionalmaterial and a way to contact the authors for more information
Trang 26Part I , The C# Language
One of the more subtle defects that occur in code is failure torecognize the various rules related to operators, expressions,and control structures Chapter 1, "Operators, Expressions, andControl Structures," details those rules and how best to utilizethem, including topics such as operator precedence and
associativity, data type conversions, and understanding logicalexpressions
C# is an object-oriented programming language and as suchplaces a strong emphasis on the use of objects within the NETFramework and the code that you write Chapter 2, "Objectsand Components," starts with basic recipes concerning objectcreation and ends with advanced topics such as polymorphism,abstract classes, and multiple interface inheritance
As you see in Chapter 3, "Strings and Regular Expressions,"strings play a major role in any programming language The.NET Framework contains a rich set of classes that aid the
developer when working with this data type Furthermore,
regular expressions allow you to take string data and performinput validation and substring replacement
Very rarely will you work with single bits of data when creating
an application More often than not, you need to utilize
collections to store several items of a similar type Chapter 4,
"Creating and Using NET Collections," covers the fundamentalcollection types in the NET Framework, including searching andsorting those collections, as well as recipes that aid in creatingyour own collection type
Delegates and events form the eventing system within the NETFramework Although a majority of event handlers respond touser-interface interaction, the model used in the NET
Framework allows any object to fire or receive events Chapter
Trang 27Application errors are an everyday occurrence Not to be
confused with regular defects, exceptions and errors are usedextensively within the NET Framework to respond appropriatelywhen something doesn't work correctly In Chapter 6,
"Exceptions in Error Handling," you'll see various techniquesoutlining the proper way to catch and throw exceptions as well
as pass exceptions on to other objects
Trang 28Part II , User Interface and Graphics
Windows Forms is the technology responsible for client-side
user interfaces Coupled with this technology is the rich designsupport built into Visual Studio NET 2003 Chapter 7, "WindowsForms," begins with several recipes aimed at creating basic
Windows Forms applications and ends with more advanced
topics, such as Multiple Document Interface (MDI) user
interfaces
Without controls, a Windows Form is just a window The NETFramework contains an extensive list of controls that you canadd to a Windows Form with a simple drag and drop from thedesigner Several recipes in Chapter 8, "Windows Forms
Controls," demonstrate various ways to control certain commoncontrols, whereas others show methods to harness the WindowsForms designer to create compelling user interfaces
Although the NET Framework contains an exhaustive list of
controls, there will always be room for more Chapter 9, "UserControls," shows different techniques you can utilize to createour own NET Windows Form control and how to plug the
Localizing an application is a task that should be solidified
during an application's design Without a game plan and without
a toolset to enable that plan, you might be playing catch-upduring the localization phase As shown in Chapter 11,
Trang 29localization and resource classes of the NET Framework tomake localization easier
Trang 30Part III , Data Access
For data to remain persistent, it must be written to a long-termstorage medium such as a hard disk Chapter 12, "File I/O andSerialization," looks at various techniques involved with file
input and output Furthermore, it also covers serialization, theact of saving an object's state, by looking at the various
application configuration files to method invocation on remoteobjects
Databases have transformed the Internet from static Web pages
to truly dynamic information systems You see in Chapter 14,
"Database Programming with ADO.NET," that ADO.NET is the.NET solution for interacting with different database
technologies, from Microsoft Access to more industrial-level
database systems such as SQL Server
Trang 31Part IV , Internet and Networking
Sockets form the underlying layer of network programming.Chapter 15, "Network Programming with Sockets," looks at
different ways of programming sockets as well as discusses
methods to formulate your own communication protocol Some
of the advanced techniques include accessing data through aproxy server and performing asynchronous Web transfers
The successor to Active Server Pages (ASP), ASP.NET
transforms dynamic Web pages into feature-laden Web
applications In Chapter 16, "ASP.NET," you will see techniquesdemonstrating everything from creating, manipulating, and
In the past, communication between disparate objects across anetwork was a lesson in perseverance for most developers
Remoting in the NET Framework was created not only to makethis communication much easier but also to provide great
flexibility and power for creating distributed applications
Chapter 18, "Remoting," covers various aspects of remoting,including server-activated singleton objects and custom channelsinks for logging
Trang 32Part V , Deployment and Security
The main deployment unit of a NET application is the assembly.Assemblies were created to combat the inconsistent deployment
of class libraries and version incompatibilities Chapter 19,
"Assemblies," shows that the NET Framework contains a vastarray of processes to follow when working with assemblies,
including strongly named assemblies, and techniques to followwhen creating subsequent versions of existing assemblies
Sometimes regarded as the last step in application design,
installation is also one of the most important items to plan andimplement In Chapter 20, "Installation," you'll see the
techniques needed to create a robust installation of your
application, starting with the creation of installation packagesand followed by more advanced techniques, including
installation of assemblies into the Global Assembly Cache
(GAC)
Security issues within the development community have seen afocused increase Chapter 21, "Securing Code," covers severaldifferent facets of programming, including authentication, codeexecution permissions, and licensing
Trang 33Part VI , Advanced Topics
Threading gives you the ability to run two or more simultaneousprogramming tasks However, it also opens the possibility fordata corruption if those tasks attempt to manipulate the samearea of memory You use synchronization to prevent this
possibility from happening Chapter 22, "Threading and
Synchronization," discusses several different techniques you canuse to create multithreaded applications
The ability to programmatically inspect objects at runtime is
known as reflection Reflection allows you not only to view the
contents of assemblies, modules, and data types but also todynamically create assemblies at runtime Chapter 23,
"Reflection," shows different techniques for reflection, such ascreating a plug-in architecture and performing dynamic methodinvocation
The Component Object Model (COM) is one of the oldest butmost widely used Windows technologies Because a vast array
of libraries and controls utilize COM, the NET Framework
contains the necessary toolset to use COM objects in NET
applications as well as NET objects within COM-based
applications Chapter 24, "COM Interoperability," discusses thistoolset
Trang 34SmartPhones Chapter 26, "Smart Device Extensions," explainssome of the key differences you'll encounter when creatingdevice applications, including techniques related to installation,data retrieval, and Compact NET Framework classes.
Trang 36Chapter 1 Operators, Expressions, and Control Structures
Trang 37For several generations, the most widely sold toys have beenthose that allow you to take small simple objects and combinethem to create a replica of some real-world object Initially
starting out as a large pile of plastic blocks with varying shapesand colors, they can transform into a multistage ignition rocketship or an elegant mansion without a roof
Toys aren't the only place we see this sort of design Almosteverywhere you look, this piecewise refinement is evident inmany facets of everyday life Cars aren't built using a myriad ofnon-connecting objects but rather are assembled from smallerpieces to form the engine, for instance, which is then used as acomponent in the final automobile Using another example, acompany contains employees who form a team These teamscombine to form a section or business unit, and these units
group together to form the corporation In fact, this type of
organization doesn't just make sense in the physical realm but
is prevalent in many natural things as well
Based on this concept, it comes as no surprise that software islogically divided into smaller pieces that contribute to a solutionwhen assembled At the lower levels of the programming
language construct hierarchy are the operator, the expression,and the control structure An expression is any group of
operators and operands that are combined to perform sometype of computation, such as setting a variable, calling a
function, or performing a system-related task
In this chapter, we look at all the various C# language elementsthat are available to construct an application From the basiclayout of a small console application to using overloaded
operators to change the semantic meaning of objects, this
chapter points out the various options you have at your disposal
to efficiently design your next Visual C# NET application
Trang 38Comments
For most of this chapter and in several projects throughout thisbook, you'll find yourself working with console-based
applications Their minimalist nature allows you to concentrate
on the topic being discussed without having to traverse throughextraneous, potentially distracting code
Even though it is just a simple console-based application thatcurrently provides no functionality, it does serve as a good
illustration for some of the various pieces that make a C#
application Once you create your project, the Visual Studio.NET IDE opens the application's main program file, which
should look similar to Listing 1.1
Trang 40example, the namespace could be Automobile.
On the first line, the program is letting the compiler know that itwants to use some of the objects within the System namespace.Therefore, anytime you want to use one of these objects, you
However, we recommend that you do get into the habit of using