The aim of this book is to teach you the fundamentals of programming withC# by using Visual Studio 2005 and the .NET Framework.. Install the practice files as described in the nextsectio
Trang 2www.microsoft.com/learning/ Send comments to mspinput@microsoft.com
Microsoft, ActiveX, Excel, IntelliSense, JScript, Microsoft Press, MSDN,Visual Basic, Visual C#, Visual J#, Visual Studio, Windows, and WindowsServer are either registered trademarks or trademarks of Microsoft
Corporation in the United States and/or other countries Other product andcompany names mentioned herein may be the trademarks of their respectiveowners
The example companies, organizations, products, domain names, e-mailaddresses, logos, people, places, and events depicted herein are fictitious Noassociation with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred
Trang 3contained in this book is provided without any express, statutory, or impliedwarranties Neither the authors, Microsoft Corporation, nor its resellers, ordistributors will be held liable for any damages caused or alleged to becaused either directly or indirectly by this book
Trang 4This title includes references to electronic content, such as sample files,sample code, beta software, tools, and other content This content is
provided as an additional learning tool to accompany the text Although thereferences to this content might mention a CD or CD-ROM where these filesare available, you can access selected portions of this content online bygoing to http://www.microsoft.com/mspress/products/mell
To view the companion content for a title at this Web site, type in the
product ISBN (International Standard Book Number) of the title in the text
box and click Go.
The ISBN for this title is listed below and can also be found on the LOC(Library of Congress) page listed in the Table of Contents
ISBN: 0-7356-2129-2
Trang 5Microsoft Visual C# is a powerful but simple language aimed primarily atdevelopers creating applications by using the Microsoft NET Framework Itinherits many of the best features of C++ and Microsoft Visual Basic, but few
of the inconsistencies and anachronisms, resulting in a cleaner and morelogical language The advent of C# 2.0 has seen several important new
features added to the language, including Generics, Iterators, and anonymousmethods The development environment provided by Microsoft Visual Studio
2005 makes these powerful features easy to use, and the many new wizardsand enhancements included in Visual Studio 2005 can greatly improve yourproductivity as a developer
The aim of this book is to teach you the fundamentals of programming withC# by using Visual Studio 2005 and the NET Framework You will learn thefeatures of the C# language, and then use them to build applications running
on the Microsoft Windows operating system By the time you complete thisbook, you will have a thorough understanding of C# and will have used it tobuild Windows Forms applications, access Microsoft SQL Server databases,develop ASP.NET Web applications, and build and consume a Web service
Trang 6This book is designed to help you build skills in a number of essential areas.You can use this book if you are new to programming or if you are switchingfrom another programming language such as C, C++, Sun MicrosystemsJava, or Visual Basic Use the following table to find your best starting point
2 Work through the chapters in Parts I, II, and IIIsequentially
3 Complete Parts IV, V, and VI as your level ofexperience and interest dictates
New to C#
1 Install the practice files as described in the nextsection, “Installing and Using the Practice Files.”
Skim the first five chapters to get an overview of C#and Visual Studio 2005, and then concentrate onChapters 6 through 19
2 Complete Parts IV, V, and VI as your level ofexperience and interest dictates
Migrating
from C, C++,
or Java
1 Install the practice files as described in the nextsection, “Installing and Using the Practice Files.”
2 Skim the first seven chapters to get an overview of C#and Visual Studio 2005, and then concentrate onChapters 8 through 19
3 For information about building Windows applicationsand using a database, read Parts IV and V
4 For information about building Web applications and
Trang 72 Work through the chapters in Parts I, II, and IIIsequentially.
3 For information about building Windows applications,read Part IV
4 For information about accessing a database, read PartV
5 For information about creating Web applications andWeb services, read Part VI
6 Read the Quick Reference sections at the end of thechapters for information about specific C# and VisualStudio 2005 constructs
2 Read the Quick Reference sections at the end of eachchapter to find a brief review of the syntax and
techniques presented in the chapter
Trang 8This book presents information by using conventions designed to make theinformation readable and easy to follow Before you start the book, read thefollowing list, which explains conventions you'll see throughout the bookand points out helpful features in the book that you might want to use
Conventions
Each exercise is a series of tasks Each task is presented as a series ofnumbered steps (1, 2, and so on) A round bullet (•) indicates an
exercise that has only one step
Notes labeled “tip” provide additional information or alternative
methods for completing a step successfully
Notes labeled “important” alert you to information you need to checkbefore continuing
A plus sign (+) between two key names means that you must pressthose keys at the same time For example, “Press Alt+Tab” means thatyou hold down the Alt key while you press the Tab key
Other Features
Sidebars throughout the book provide more in-depth information aboutthe exercise The sidebars might contain background information,
design tips, or features related to the information being discussed
Each chapter ends with a Quick Reference section The Quick
Reference section contains quick reminders of how to perform the tasksyou learned in the chapter
Trang 9The online companion content page has content and links related to thisbook
http://www.microsoft.com/mspress/companion/0-7356-2129-2/
Technology Updates
As technologies related to this book are updated, links to additional
information will be added to the Microsoft Press Technology Updates Webpage Visit this page periodically for updates on Visual Studio 2005 andother technologies
http://www.microsoft.com/mspress/updates/
NOTE
Practice files for this book are on the companion CD
Trang 10You'll need the following hardware and software to complete the exercises inthis book:
CD-ROM or DVD-ROM drive
Microsoft Mouse or compatible pointing device
You will also need to have Administrator access to your computer to
configure SQL Server 2005 Express Edition and to modify the WindowsRegistry in Chapter 28, “Creating and Using a Web Service.”
Prerelease Software
This book was reviewed and tested against the August 2005 CommunityTechnical Preview (CTP) of Visual Studio 2005 The August CTP was thelast preview before the final release of Visual Studio 2005 This book isexpected to be fully compatible with the final release of Visual Studio 2005
If there are any changes or corrections for this book, they will be collectedand added to a Microsoft Knowledge Base article See the “Support for thisBook” section in this Introduction for more information
Trang 11The companion CD inside this book contains the practice files that you'll use
as you perform the exercises in the book By using the practice files, youwon't waste time creating files that aren't relevant to the exercise The filesand the step-by-step instructions in the lessons also let you learn by doing,which is an easy and effective way to acquire and remember new skills.Installing the Practice Files
Follow these steps to install the practice files on your computer's hard disk
so that you can use them with the exercises in this book
1 Remove the CD from the package inside this book, and insert it intoyour CD-ROM drive
NOTE
An end user license agreement should open automatically If this
agreement does not appear, open My Computer on the desktop or Startmenu, double-click the icon for your CD-ROM drive, and then double-click StartCD.exe
2 Review the end user license agreement If you accept the terms, selectthe accept option and then click Next
Trang 121 On the Windows Start menu, click All Programs, click Accessories, andthen click Command Prompt to open a command prompt window
Replace YourServer with the name of your computer, and replace
UserName with the name of the user account you will be using.
4 At the 2> prompt, type the following command and then press Enter:sqlcmd –S YourServer\SQLExpress –E
sp_grantlogin [YourServer\UserName]
Trang 148 Close the command prompt window.
Using the Practice Files
Each chapter in this book explains when and how to use any practice filesfor that chapter When it's time to use a practice file, the book will list theinstructions for how to open the file The chapters are built around scenariosthat simulate real programming projects, so you can easily apply the skillsyou learn to your own work
For those of you who like to know all the details, here's a list of the VisualC# projects on the practice disk
Project Description
Chapter 1
TextHello This project gets you started It steps through the
based greeting
Trang 15DailyRate This project walks you through writing your own
methods (both manually and by using a wizard),running the methods, and stepping through themethod calls by using the Visual Studio debugger.Chapter 4
Selection This project shows how a cascading if statement is
used to compare two dates
switchStatement This simple program uses a switch statement to
convert characters into their XML representations.Chapter 5
Iteration This project displays code fragments for each of the
different iteration statements and the output thateach generates
whileStatement This project uses a while statement to read the
contents of a source file one line at a time anddisplay each line in a Windows text box
The try and catch keywords then make the
application more robust so that it no longer fails.Chapter 7
Classes This project covers the basics of defining your own
classes, complete with public constructors,methods, and private fields It also covers creating
class instances by using the new keyword and by
using static methods and fields
Chapter 8
Trang 16Chapter 13
UsingStatement This project revisits a small piece of code from the
previous chapter and reveals that it is notexception-safe It shows you how to make the code
exception-safe with a using statement.
Chapter 14
Properties This project presents a simple Windows application
that uses several properties to continually display
Trang 17Chapter 15
Indexers This project uses two indexers: one to look up a
person's phone number when given a name, and theother to look up a person's name when given aphone number
Chapter 16
Delegates This project displays the time in digital format by
using delegate callbacks The code is thensimplified by using events
Chapter 20
BellRingers This project is a Windows Forms application
demonstrating basic Windows Forms controls
Trang 18BellRingers This project is an extension of the application
created in Chapter 20, “Introducing WindowsForms,” but with drop-down and pop-up menusadded to the user interface
Chapter 22
CustomerDetails This project demonstrates how to validate user
input, using customer information as an example.Chapter 23
DisplayProducts This project shows you how to use Microsoft
ADO.NET to connect to the Northwind Tradersdatabase, and retrieve information from theProducts table The project uses the Data SourceConfiguration Wizard to generate a data source to
connect to the database, and DataSet, DataTable, and TableAdapter objects to bind the data source to
a DataGridView control The DataGridView control
displays the data in a Windows Form
ReportOrders This project shows how to access a database by
using ADO.NET code rather than by using thecomponents generated by the Data SourceConfiguration Wizard The application retrievesinformation from the Orders table in the NorthwindTraders database
HonestJohn This project creates a simple Microsoft ASP.NET
Trang 19Chapter 26
HonestJohn This project is an extended version of the
HonestJohn project from the previous chapter andshows how to validate user input in an ASP.NETWeb application
Chapter 27
Northwind This project shows how to use Forms-based
security for authenticating the user The applicationalso demonstrates how to use ADO.NET from anASP.NET Web form, showing how to query andupdate a database in a scalable manner
Chapter 28
NorthwindServices This project implements a Web service, providing
remote access across the Internet to data in theProducts table in the Northwind Traders database.ProductInfo This project shows how to create a Windows
application that consumes a Web service It showshow to invoke the Web methods in the
NorthwindServices Web service
In addition to these projects, several projects have solutions available for thepractice exercises The solutions for each project are included on the CD inthe folder for each chapter and are labeled Complete
Uninstalling the Practice Files
Follow these steps to remove the practice files from your computer
1 In Control Panel, open Add Or Remove Programs
2 From the Currently Installed Programs list, select Microsoft Visual C#
Trang 203 Click Remove
4 Follow the onscreen instructions to remove the practice files
Trang 21Every effort has been made to ensure the accuracy of this book and thecontents of the companion CD As corrections or changes are collected, theywill be added to a Microsoft Knowledge Base article To view the list ofknown corrections for this book, visit the following article:
Trang 22Introducing Microsoft Visual C# and Microsoft Visual Studio 2005
Trang 23played in the development of UNIX If you already know a language such as
C, C++, or Java, you'll find the syntax of C# reassuringly familiar because ituses the same curly brackets to delimit blocks of code However, if you areused to programming in other languages, you should soon be able to pick upthe syntax and feel of C#; you just need to learn to put the curly brackets andsemi-colons in the right place Hopefully this is just the book to help you!
In Part I, you'll learn the fundamentals of C# You'll discover how to declarevariables and how to use operators such as plus (+) and minus (-) to createvalues You'll see how to write methods and pass arguments to methods You'll
also learn how to use selection statements such as if and iteration statements such as while Finally, you'll understand how C# uses exceptions to handle
errors in a graceful, easy-to-use manner These topics form the core of C#, andfrom this solid foundation, you'll progress to more advanced features in Part IIthrough Part VI
Trang 24Beginning Programming with the Visual Studio 2005 Environment
Visual Studio 2005 is a tool-rich programming environment containing allthe functionality you'll need to create large or small C# projects You caneven create projects that seamlessly combine modules from different
languages In the first exercise, you'll start the Visual Studio 2005
programming environment and learn how to create a console application.Create a console application in Visual Studio 2005
1 In Microsoft Windows, click the Start button, point to All Programs,and then point to Microsoft Visual Studio 2005
2 Click the Microsoft Visual Studio 2005 icon Visual Studio 2005 starts
NOTE
If this is the first time that you have run Visual Studio 2005, you mightsee a dialog box prompting you to choose your default developmentenvironment settings Visual Studio 2005 can tailor itself accordingyour preferred development language The various dialog boxes andtools in the integrated development environment (IDE) will have theirdefault selections set for the language you choose Select Visual C#Development Settings from the list, and then click the Start VisualStudio button After a short delay, the Visual Studio 2005 IDE appears
Trang 253 On the File menu, point to New, and then click Project The NewProject dialog box opens This dialog box allows you to create a newproject using various templates, such as Windows Application, ClassLibrary, and Console Application, that specify the type of applicationyou want to create.
NOTE
The actual templates available depend on the version of Visual Studio
2005 you are using It is also possible to define new project templates,but that is beyond the scope of this book
Trang 26NOTE
If the folder you specify does not exist, Visual Studio 2005 creates it foryou
6 In the Name field, type TextHello
7 Ensure that the Create Directory for Solution check box is checked andthen click OK The new project opens
The menu bar at the top of the screen provides access to the features you'll
use in the programming environment You can use the keyboard or the
Trang 27Solution 'TextHello'
Trang 28If you use Windows Explorer to look at your \My Documents\VisualCSharp Step by Step\Chapter 1\TextHello folder, you'll see that theactual name of this file is TextHello.sln Each solution file containsreferences to one or more project files
TextHello
This is the C# project file Each project file references one or morefiles containing the source code and other items for the project All thesource code in a single project must be written in the same
programming language In Windows Explorer, this file is actuallycalled TextHello.csproj, and it is stored in your \My Documents\VisualCSharp Step by Step\Chapter 1\TextHello\TextHello folder
Properties
This is a folder in the TextHello project If you expand it, you will seethat it contains a file called AssemblyInfo.cs AssemblyInfo.cs is a
special file that you can use to add attributes to a program, such as the
name of the author, the date the program was written, and so on Thereare additional attributes that you can use to modify the way in whichthe program will run These attributes are outside the scope of thisbook
References
This is a folder that contains references to compiled code that yourapplication can use When code is compiled, it is converted into an
assembly and given a unique name Developers use assemblies to
package up useful bits of code that they have written for distribution toother developers that might want to use them in their applications.Many of the features that you will be using when writing applicationsusing this book will make use of assemblies provided by Microsoftwith Visual Studio 2005
Program.cs
This is a C# source file, and is the one displayed in the Code and Text
Trang 29Editor window when the project is first created You will write yourcode in this file It contains some code that Visual Studio 2005provides automatically, which you will examine shortly.
Trang 301 In the Code and Text Editor window displaying the Program.cs file,
place the cursor in the Main method after the opening brace, and type Console As you type the letter C at the start of the word Console an
IntelliSense list appears This list contains all of the valid C# keywordsand data types that are valid in this context You can either continuetyping, or scroll through the list and double-click the Console item with
the mouse Alternatively, after you have typed Con, the Intellisense list will automatically home in on the Console item and you can press the
Trang 31The IntelliSense list closes, and the WriteLine method is added to the source file Main should now look like this:
4 Type an open parenthesis Another IntelliSense tip appears
This tip displays the parameters of the WriteLine method In fact,
WriteLine is an overloaded method, meaning that Console contains more than one method named Write Line Each version of the WriteLine
Trang 33Console.WriteLine("Hello World");
}
Trang 36If you run the program using Start Debugging on the Debug menu, theapplication runs but the Command window closes immediately withoutwaiting for you to press a key
4 In the Solution Explorer, click the TextHello project (not the solution),
and then click Show All Files button Entries named bin and obj appear
above the C# source filenames These entries correspond directly tofolders named bin and obj in the project folder (\My Documents\VisualCSharp Step by Step\Chapter 1\TextHello\TextHello) These folders arecreated when you build your application, and they contain the
executable version of the program and some other files
5 In the Solution Explorer, click the + to the left of the bin entry Anotherfolder named Debug appears
6 In the Solution Explorer, click the + to the left of the Debug entry.Three entries named TextHello.exe, TextHello.pdb, and
TextHello.vshost.exe appear The file TextHello.exe is the compiledprogram, and it is this file that runs when you click Start Without
Debugging in the Debug menu The other two files contain informationthat is used by Visual Studio 2005 if you run your program in Debugmode (when you click Start Debugging in the Debug menu)
Command Line Compilation
Trang 384 Run the program by typing the following command:
The program should run exactly as before, except that you will notsee the "Press any key to continue" prompt
TextHello
Trang 39The example you have seen so far is a very small program However, smallprograms can soon grow into bigger programs As a program grows, it
creates two problems First, more code is harder to understand and maintainthan less code Second, more code usually means more names; more nameddata, more named methods, and more named classes As the number ofnames increases so does the likelihood of the project build failing becausetwo or more names clash (especially when the program uses third-partylibraries)
In the past, programmers tried to solve the name-clashing problem by
prefixing names with some sort of qualifier (or set of qualifiers) This
solution is not a good one because it's not scalable; names become longerand you spend less time writing software and more time typing (there is adifference) and reading and re-reading incomprehensibly long names
Namespaces help solve this problem by creating a named container for otheridentifiers, such as classes Two classes with the same name will not beconfused with each other if they live in different namespaces You can create
Trang 40You can then refer to the Greeting class as TextHello.Greeting in your own programs If someone else also creates a Greeting class in a different
namespace and installs it on your computer, your programs will still work as
expected because they are using the TextHello.Greeting class If you want to refer the new Greeting class, you must specify that you want the class from
the new namespace
It is good practice to define all your classes in namespaces, and the VisualStudio 2005 environment follows this recommendation by using the name ofyour project as the top-level namespace The NET Framework SoftwareDeveloper Kit (SDK) also adheres to this recommendation; every class in
the NET Framework lives inside a namespace For example, the Console class lives inside the System namespace This means that its fully qualified name is actually System.Console.
Of course, if you had to write the fully qualified name of a class every time,
it would be no better that just naming the class SystemConsole Fortunately, you can solve this problem with a using directive If you return to the
TextHello program in Visual Studio 2005 and look at the file Program.cs inthe Code and Text Editor window, you will notice the following statements:
The using statement brings a namespace into scope, and you no longer have
to explictly qualify objects with the namespace they belong to in the codethat follows The three namespaces shown contain classes that are used so
often that Visual Studio 2005 automatically adds these using statements every time you create a new project You can add further using directives to
using System;
using System.Collections.Generic;
using System.Text;