1. Trang chủ
  2. » Giáo án - Bài giảng

Giáo án - Bài giảng: beginning c# 2008

511 295 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Beginning C# 2008: From Novice to Professional
Tác giả Christian Gross
Trường học Springer-Verlag New York
Chuyên ngành Computer Science
Thể loại sách hướng dẫn
Năm xuất bản 2007
Thành phố New York
Định dạng
Số trang 511
Dung lượng 11,47 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

295 CH APTER 12 Learning About Application Configuration and Dynamic Loading...329 CH A PTER 13 Learning About M ultithreading...359 CH APTER 14 Learning About Relational Database Data..

Trang 1

THE EXPERT’S VOICE® IN NET N

Trang 3

Beginning C# 2008 From Novice to Professional

Christian Gross

Trang 4

All rights reserved No p art of this work m ay be reproduced or tran sm itted in any form or by any m eans, electronic or m echanical, including photocopying, recording, or by any inform adon storage or retrieval system, w ithout the prior w ritten perm ission of the copyright ow ner and the publisher.

ISBN-13 (pbk): 978-1-59059-869-6

ISBN-10 (pbk): 1-59059-869-5

Printed an d b o u n d in the U nited States of America 9 8 7 6 5 4 3 2 1

Tradem arked nam es m ay ap p ear in this book Rather th a n use a tradem ark sym bol with every occurrence

of a tradem arked nam e, we use the nam es only in an editorial fashion and to the benefit of the tradem ark owner, w ith no in ten tio n of infringem ent of the tradem ark.

Lead Editor: Ewan Buckingham

Technical Reviewer: C hristian Kenyeres

Editorial Board: Steve Anglin, Ewan B uckingham , Tony C am pbell, Gary C ornell, lo n a th a n Gennick, laso n G ilm ore, Kevin Goff, Jo n a th a n Hassell, M atthew M oodie, Joseph Ottinger, Jeffrey Pepper, Ben Renow-Clarke, D om inic Shakeshaft, M att Wade, Tom Welsh

Project M anager: Sofia M archant

Copy Editor: M arilyn Smith

Associate P roduction Director: Kari Brooks-Copony

Production Editor: Kelly W inquist

Compositor: Kinetic Publishing Services

Proofreader: Nancy Riddiough

Indexer: Broccoli Inform ation M anagem ent

Artist: Kinetic Publishing Services

Cover Designer: Kurt Krames

M anufacturing Director: Tom Debolski

D istributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY 10013 Phone 1-800-SPRINGER, fax 201-348-4505, e-m ail orders-ny(5>springer-sbm.com, or visit http://w w w springeronline.com

For inform ation on translations, please contact Apress directly at 2855 Telegraph Avenue, Suite 600, Berkeley, CA94705 Phone 510-549-5930, fa x 510-549-5939, e-m ail info@apress.com, or visit http://w w w apress.com The inform ation in this book is distributed on an “as is” basis, w ithout warranty Although every precaution has been taken in the p rep aratio n of this work, n eith er the author(s) n o r Apress shall have any liability to any person or entity w ith respect to any loss or dam age caused or alleged to be caused direcdy or indirectiy

by the inform ation contained in this work.

The source code for this book is available to readers at h t t p : //www a p re s s com.

Trang 5

“A com m on mistake that people make when trying to design something completely fo o lp ro o f is to underestimate the ingenuity o f complete fools.”

“The m ajor difference between a thing that m ight go wrong and a thing that cannot possibly go wrong is that when a thing that cannot possibly go wrong goes

wrong it usually turns out to be impossible to get at or repair.”

— Douglas Adams, M ostly H a rm le ss

Trang 7

Contents at a Glance

About the Author xvii

About the Technical Reviewer XIX Introduction XXI CH APTER 1 Ready, steady, G o! T CHAPTER 2 Learning About NET Number and Value Types 27

CH APTER 3 Learning About String Manipulations 53

CHAPTER 4 Learning About Data Structures, Decisions, and Loops 77

CH APTER 5 Learning About c# Exception H an dling ÏÏ5 CH APTER 6 Learning the Basics of Object-Oriented Programming 137

CH APTER 7 Learning About Components and Object H ierarchies 165

CH APTER 8 Learning About Component-Oriented A rch itectu re 199

CH APTER 9 Learning About Lists, Delegates, and Lambda Expressions 23?

C H A PTER 10 Learning About Persistence 257

CH APTER 11 Learning About NET Generics 295

CH APTER 12 Learning About Application Configuration and Dynamic Loading 329

CH A PTER 13 Learning About M ultithreading 359

CH APTER 14 Learning About Relational Database Data 389

C H A PTER 15 Learning About LINQ 415

CH APTER 16 Writing Functional Code in c # 439

CHAPTER 17 Learning About other c# Techniques 455

I N D E X 47?

Trang 9

About the Author xvii

About the Technical Reviewer xix

Introduction xxi

CH A PTER 1 R ead y, S te a d y , G o ! T Downloading and Installing the Tools T Downloading Visual C# Express 2

Installing Visual C# Express 3

Choosing the Application T yp e 4

Creating Projects and Solutions 4

Creating the Windows Application 5

Viewing the Source Code 6

Renaming the Solution 6

Saving the Solution 7

Running the Windows Application 7

Making the Windows Application Say Hello 9

Adding Comments to the Application 12

Navigating the User Controls of the Solution 13

Creating the Console Application 16

Adding a Console Application Project to the Solution 16

Making the Console Application Say H ello 16

Setting the Startup Project 17

Running the Console Project 17

Creating the Class Library 17

Adding a Class Library Project to the Solution 17

Moving Functionality 18

Defining References 19

Calling Class Library Functionality 19

Using Variables and Constants 2T Understanding How the NET Framework Works 23

The Important Stuff to Remember 25

Some Things for You to Do 26

Trang 10

CH APTER 2 L e a rn in g A b o u t N ET N u m ber an d V a lu e T y p e s 27

Focusing and Organizing Your Development 27

Organizing the Calculator 28

Focusing the Calculator 30

Implementing the Class Library 32

Writing the AddO Method 34

Writing Code to Test the AddO Method 37

Understanding Problems with Numeric Numbers 42

Understanding Numeric and Value Data Types 44

Understanding Value and Reference Types 44

Understanding the CLR Numeric Types 45

Finishing the Calculator 49

The Important Stuff to Remember 50

Some Things for You to Do 50

CH A PTER 3 L e a rn in g A b o u t S trin g M a n ip u la tio n s 53

Organizing the Translation Application 53

Building the Translator Application 54

Creating the Translator Class 55

Translating H ello 55

Creating the Test Application 56

Answering the Question of Responsibility 57

Investigating the String Type 57

Solving the Extra Whitespace Problem 63

Quoting Strings 67

Character Mapping 67

Dealing with Languages and Cultures 69

Setting Culture and Language in Windows 69

Parsing and Processing Numbers 70

Working with Cultures 72

The Important Stuff to Remember 74

Some Things for You to Do 75

CHAPTER 4 Le a rn in g A b o u t D ata S tru c tu re s , D ecisio n s, and L o o p s 77

Understanding the Depth-First Search Algorithm 77 Implementing User-Defined Types sT Declaring Structs and Classes sT Value Type Constraints sT

Trang 11

Organizing the Search Algorithm 87

Writing the Depth-First Search Code 89

Defining and Implementing the Data Structure 89

Defining the Algorithm T est 99

Implementing the Depth-First Search Algorithm ÏÔ3 Running the Depth-First Search Algorithm TTT The Important Stuff to Remember 112

Some Things for You to Do 113

CHAPTER 5 Lea rn in g A b o u t C# Ex ce p tio n H a n d lin g 115

Understanding Errors, Exceptions, and Exception Handling TTs Running the Debugger rfis Handling Exceptions 117

Catching Exceptions TTs Implementing Exception Handlers 120

Safeguarding Against Stack Unwinding 124

Filtering Exceptions 128

Writing Exception-Safe Code 130

Writing Defensive Code Ï3Ô Using Default State 133

Processing Errors That Are Warnings 134

The Important Stuff to Remember 135

Some Things for You to Do 136

CHAPTER 6 L e a rn in g th e B a s ic s o f O bject-O riented P ro g ra m m in g 137

Understanding Currency Spreads 138

Organizing the Currency Exchange Application Ï39 Writing Tests for the Currency Exchange Application 139

Getting Started with Structural Code 140

Understanding Base Classes 140

Understanding Inheritance Ï4 Ï Using C# Properties 143

Understanding Inheritance and Scope Modifiers Ï47 Handling Verification Ï5Ô Finishing the Base Class 153

Writing the Active Trader and Hotel Trader Currency Converters 154

Implementing ActiveCurrencyTrader 154

Implementing HotelCurrencyTrader 156

Trang 12

CH APTER 7

CH APTER 8

Learning More About Preprocessor Directives, Properties, and Abstract

Methods

More Preprocessor Directive D etails

More Property Scope Details

More abstract Keyword Details

The Important Stuff to Remember

Some Things for You to Do

Learning About Components and Object Hierarchies .

Understanding Some Basic Tax Concepts

Organizing the Tax Application

Programming Using Ideas

Representing Ideas Using C# Interfaces

Understanding How Inheritance and Components Work

Implementing a Tax Engine

Defining the Interfaces

Implementing a Base Class Tax Engine

Using Default Implementations

Implementing a Base Tax Account

Using the Base Functionality of the Tax Engine to Calculate Taxes

Implementing a Tax Engine and Tax Account

Using the Tax Engine

Learning More About Inheritance and Type Casting

More Inheritance Details

More Type-Casting Details

The Important Stuff to Remember

Some Things for You to Do

Learning About Component-Oriented Architecture

Understanding Kernels

Organizing the Lighting Application

Building the Kernel

Defining the Interfaces

Implementing the Kernel

Defining the Kernel As an Interface Instead of a Class

Building a Complete Application

Defining Some Rooms

Instantiating PublicRoom and PrivateRoom

Trang 13

Learning More About Private Classes and Object Initialization 227

Private Classes 227

Object Initialization with Nested Data Types 227

The Important Stuff to Remember 229

Some Things for You to Do 229

CHAPTER 9 Le a rn in g A b o u t L is ts , D e leg a te s, and Lam b d a E x p r e s s io n s 23?

Managing Collections 23T Managing a Collection Before C# 2.0 232

Managing a Collection After C# 2 0 236

The Case of the Code That Feels Wrong 237

Using Delegates 240

Using Anonymous Delegates 245

Multicasting with Delegates 246

Using Lambda Expressions 247

Understanding Lambda Expressions 249

Creating the Algorithm 250

Implementing the Algorithm Using Lambda Expressions 250

Learning More About Collection Types 252

Using a Plain-Vanilla L is t 252

Using a KeyAtelue Pair List 253

Using a Stack .254

Using a Queue 254

The Important Stuff to Remember 255

Some Things for You to Do 255

CHAPTER 10 L e a rn in g A b o u t P e r s is te n c e 257

Organizing the Lottery-Prediction System 257

Piping Data Using a Console 258

Reading Data from the Console 258

Building a S h e ll 260

Implementing the TextProcessor Application 270

Piping Binary Data 278

Defining the Interfaces and Implementing the Shell 280

Defining the Type 283

Converting a Text Stream into a Binary Stream 284

Converting a Binary Stream into a Text Stream 285

Trang 14

Tweaking Serialization 287

Performing Custom Serialization 287

Declaring a Data Member as Nonserializable 288

Separating Data Objects from Action Objects 288

Completing Custom Types 289

Implementing GetHashCodeO 289

Implementing EqualsO 292

The Important Stuff to Remember 294

Some Things for You to Do 294

CH APTER 11 Le a rn in g A b o u t N ET G e n e r ic s 295

Why Use NET Generics? 295

The Theory of a Server-Side Spreadsheet 298

Architecting a Server-Side Spreadsheet .3ƠT Designing the Architecture 3Ợ Defining the Server Spreadsheet Interfaces 3Ơ2 Implementing the Server Spreadsheet 3ÏT Using Lambda Expressions in the Spreadsheet 316

Assigning State Without Knowing the Type 320

Overriding the ToStringO Functionality 322

Iterating Data Using Enumerators 323

Using the Spreadsheet 324

Calculating an Average 324

Understanding Why the Calculation Worked 326

The Important Stuff to Remember 327

Some Things for You to Do 328

CH APTER 12 L e a rn in g A b o u t A p p lic a tio n C o n fig u ra tio n and D yn a m ic L o a d in g 329

Convention over Configuration 329

Decoupling Using a Configuration Architecture 33Ï Decoupling Using a Convention Architecture 33Ï Setting Up the Dynamic Loading Projects 332

Signing an Assembly 334

Setting the Output Path 335

Defining and Processing a Configuration File 336

Creating an XML-Based Configuration File 336

Adding the Dynamic Loading Configuration Items 338

Reading a Configuration F ile 338

Trang 15

Dynamically Loading an Assembly 339

Dynamically Instantiating a Type 339

Enhancing the Configuration F ile 343

Loading a Strongly Named Assem bly 348

Relocating a Strongly Named Assembly to the GAC 349

Using Version Numbers 35?

Implementing a Convention-Based Architecture 354

Dynamically Loading Base Class or Interface Types 356

The Important Stuff to Remember 357

Some Things for You to Do 358

CHAPTER 13 L e a rn in g A b o u t M u ltith re a d in g 359

Understanding Multitasking 359

Preemptive Multitasking 36Ö Time Slicing 36Ö Using Threads 363

Creating a New Thread 363

Waiting for the Thread to En d 364

Creating a Thread with State 365

Synchronizing Between Threads 367

How Not to Deadlock Your Code (Mostly) 372

Implementing a Reader/Writer Threaded Architecture 376

Implementing a Producer/Consumer Architecture 38Ö Using a Hidden Producer/Consumer Implementation 38Ö Implementing a Generic Producer/Consumer Architecture 382

Using an Asynchronous Approach 384

The Important Stuff to Remember 386

Some Things for You to Do 387

CHAPTER 14 L e a rn in g A b o u t R e la tio n a l D a ta b a se D a t a 389

Understanding Relational Databases 389

Relational Database Tables 389

Database Relations 39?

Accessing Relational Databases 394

Designing a Database Using Visual C# Express 395

Configuring the Data Source 396

Adding the Tables 399

Accessing the Database Using AD0.NET 4Ö3 Connecting to a Database 403

Adding Table Data 403

Trang 16

Selecting Data from a Table 406

Deleting Data from the Database 406

Closing a Database Connection 407

Recapping AD0.NET Usage 407

Using the Dataset Designer 408

Building Relations Between Tables 408

Using the Generated Code 412

The Important Stuff to Remember 414

Some Things for You to Do 414

CHAPTER 15 L e a rn in g A b o u t L IN Q 415

Finding the Frequency of Winning Numbers 415

Extending the Lottery-Prediction System 416

Implementing a Frequency Solution 419

Learning More LINQ Tricks 425

Selecting and Altering D ata 428

Selecting with Anonymous Types 430

Processing Multiple Streams 43?

Sorting the Results 431

Splitting Results into Groups 433

Performing Set Operations 434

Using LINQ in Other Contexts 436

The Important Stuff to Remember 438

Some Things for You to Do 438

CHAPTER 16 W ritin g F u n ctio n a l Code in C # 439

Why Functional Programming? 439

The Essence of Functional Programming 44?

Higher-Order Functions 442

Pure Functions 445

Function Evaluation 450

Recursion 452

The Important Stuff to Remember 453

Some Things for You to Do 453

Trang 17

CHAPTER 17 Learning About Other C# Techniques 455

Operators 455

Using Arithmetic Operators 455

Overloading the Operators 460

The goto Statement 462

.NET Generics Constraints 463

Using the type Constraint 463

Using the new Constraint 465

Using the class Constraint 465

Nullable Types 466

Partial Classes and Methods 468

The Important Stuff to Remember 470

Some Things for You to Do 470

INDEX 47T

Trang 19

About the Author

M any p e o p le say th a t by looking at a p e rs o n ’s dog, you can tell w h a t th e perso n is like Well, the picture is of m y dog Louys, an English bulldog And yes, m y English bulldog an d I have m an y co m m o n characteristics

But w hat ab o u t the biography of the author, CHRISTIAN GROSS? It’s

pretty sim ple: I’m a guy w ho h as sp e n t oodles of tim e strap p ed to a chair debugging a n d taking ap a rt code In fact, I really enjoy this business we call softw are developm ent I have loved it ever since I learned how to peek

an d poke m y first bytes I have w ritte n various books, in clu d in g Ajax and REST Recipes:

A Problem-Solution Approach, Foundations o f Object-Oriented Programming Using NET

2.0 Patterns, a n d A Programmer's Introduction to Windows DNA, all available from Apress

These days, I enjoy coding an d experim enting w ith NET, as it is a fascinating environm ent

.NET m akes m e feel like a kid o p en in g a p resen t on C hristm as m orning You h a d an id ea w hat

th e gift was, b u t you w ere n o t com pletely sure A nd w ith NET, th e re is no relative giving you

socks or a sweater It’s excitem ent all the way!

xvii

Trang 21

About the Technical Reviewer

CHRISTIAN KENYERES, principal architect for Collaborative Consulting, is

a visionary technology professional w ith m ore th a n 15 years of extensive inform ation technology experience He h as served nu m erous high-profile clien ts as a n e n te rp rise a rc h ite c t a n d b o asts a b ro ad range of tec h n ica l

a n d business knowledge

Prior to join in g Collaborative, C hristian p erfo rm ed co n su ltin g for various co m p an ies such as C om paq, EMC, Fidelity Investm ents, Liberty

M utual Insurance, and lo h n H ancock He h olds B.S a n d M.S degrees in C o m p uter Science

from th e U niversity of M assachusetts and B oston University, respectively

xix

Trang 23

T i e first c o m p u te r p ro g ra m m in g book I re a d was e n title d Programming Windows 3.0 by

Charles Petzold This was a ro u n d th e tim e w h en M icrosoft W indows 3.0 (circa 1992) once an d

for all showed the industry that Microsoft was a com pany with a future Writing code for Wmdows

back th e n was c o m p licated by m an y things: lack of d o c u m e n tatio n , 16-bit arch itecture, a n d

the necessity of buying a com piler separate from the software developm ent kit (SDK) Charles’s

book tied everything together an d solved the problem of how to write a program for W indows

Now th e p ro b le m s are q u ite th e opp osite: we have to o m u c h d o c u m e n ta tio n , we have

64-bit architectures, a n d everything including th e kitchen sink is throw n into a developm ent

environm ent Now we n eed to figure out w hat we actually need We have too m any op tion s—

too m any ways to solve the sam e problem W hat I am trying to do w ith this book is the sam e

thing th a t Charles did for m e w h en I first sta rte d out, a n d th a t was to help m e figure o ut w hat

I need ed to w rite code

This book is a b o u t ex p lainin g th e C# p ro g ra m m in g lan g uage in th e con tex t of solving

pro blem s C# h as b eco m e a so p h istic a te d p ro g ra m m in g lan gu age th a t can achieve m an y

goals, b u t you are left w o n d e rin g w h at te c h n iq u e s to use w hen This bo ok is h e re to answ er

your questions

This book is n o t a reference to all of th e features of the C# program m ing language I d o n ’t

explain th e esoteric C# features I stick to the C# program m ing features th at you will use day in

and day out T hat does n o t m ea n th a t you will be m issing c e rtain Cif program m ing language

constructs, becau se I have covered all of the m ajor features

To get th e full b en efit of this book, I suggest th a t you do th e exercises at th e e n d o f th e

chapters The answ ers are available o n the Apress web site ( h ttp : //www a p re s s com), a n d you

can ch eat a n d n o t do th e exercises, b u t I advise against that

If you are a beginning p rog ram m er w ho has no clue ab o u t C#, a n d you read this book an d

do th e exercises, I am alm ost entirely sure th a t you will be a solid a n d know ledgeable C# p ro ­

g ram m er by th e en d of th e book If th a t so u n d s like a big prom ise, well, yes it is The c h a p te r

text is in te n d e d to get you acq u ain ted with th e C# program m ing language and how to apply its

features The exercises are in tend ed to m ake sure you actually u n d erstan d the C# program m ing

language a n d its features

The chapter exercises are challenging They can n o t be solved w ithin a few m inutes In fact,

w hen I did all of th e exercises, it took m e five w orking-hour days to do all of them!

If you have any questions, su ch as, “So w hat was he trying to get at w ith th a t exercise?”

I am available o n Skype w ith th e u ser ID christianh gross Please d o n ’t ju st ring m e First ch at

using text, a n d if necessary, we can have a voice conversation Also, you can sen d e-m ail to m e

atchristianhgross@ gm ail.com

Thanks an d good luck

xxi

Trang 25

Ready, Steady, Go!

THiis book is a b o u t the C# program m ing language first a n d forem ost It is abo u t becom ing

a proficient C# program m er Reading this book from cover to cover will n o t m ake you a super-

star, b u t it will m ake you a p ro g ram m er w ho u n d e rsta n d s w hat need s to be done w hen writing

robust, stable, a n d m ain tain ab le C# applications

In this chapter, you’ll get started by acquiring the tools you n eed to develop C# applications

and taking those tools for a test spin Along th e way, y o u’ll create a couple C# applications

Downloading and Installing the Tools

G etting sta rte d w ith C# 3.0, you’re probably really excited ab o u t writing som e code th a t does

som ething It’s like getting your driver’s license a n d w anting to drive a car w ithout even th in k ­

ing ab o u t w here you w an t to drive You just w an t to drive The great p a rt of NET is th a t you

can start w riting som e code after you have installed either th e NET software develo pm en t kit

(.NET SDK) or a Visual Studio integrated developm ent en v iro n m en t (IDE) D ow nloading an d

installing th e right en v iro n m en t is critical to taking your first step tow ard an enjoyable coding

experience

Note Software version numbers, product descriptions, and technologies can be confusing Having used

Microsoft technologies for over a decade, I can say that naming a technology or product has never been

Microsoft’s strong point The technologies have (for the most part) been great, but product classification and

identification have not been so great Thus, this book covers the C# 3.0 programming language that is used

to v/rite applications for the NET Framework With C# 3.0, the NET 3.0 and 3.5 Frameworks are used .NET

3.0 gives you all of the essentials, and NET 3.5 gives you the extras.

1

Trang 26

For the exam ples in this book, you’ll be using Visual C# 2008 Express Edition, because it’s freely available an d h as everything you need to get started w ith C# 3.0 The other Express Edi­tion IDEs available from M icrosoft are tailored to different languages (Visual Basic an d C++)

or, in th e case of Visual Web D eveloper Express, specific functionality th a t is too restrictive for our purposes

M icrosoft also offers full versions of th e Visual Studio IDE, such as the Standard, Profes­sional, an d Team editions Each of these editions has different features an d different price tags See th e M icrosoft Visual Studio web site (h ttp ://m sd n 2 in ic ro so ft.c o m /en -u s/v stu d io /

d e f a u lt aspx) for m ore inform ation If you already have Visual Studio 2008 Professional, you can use th at for the examples in this book That edition can do everything that Visual C# Express can do, an d in fact, has m any m ore options

Note I personally use Visual Studio Standard or Professional in combination with other tools such as

t e s td r iv e n n e t/) , and NUnit (h ttp ://w w w n u n it.o rg ) The Visual Studio products are very good, but others are available Being a good developer means knowing which tools work best for you.

In stalling a n d d ow n lo ad in g Visual C# Express from th e M icrosoft web site involves the transfer of large files If you do n o t have a b ro ad b a n d connection, I suggest that you install the IDE from a CD instead

Downloading Visual C# Express

The following is th e proced ure for dow nloading Visual C# Express from th e M icrosoft web site

By the tim e you are reading this book, the pro ced u re m ay be a bit different, but it will be sim i­lar en ough th a t you’ll be able to find and dow nload th e IDE package

1 Go to h ttp ://m s d n m ic ro s o ft.c o m /v stu d io /e x p re s s /

2 Select th e Visual Studio 2008 Express Editions link

3 Select W indow s D evelopm ent (because for th e scope of this book, th at is w hat you’ll be doing)

4 Click th e Visual Studio Express D ow nload link

5 You’ll see a list ofVisual Studio Express editions, as show n in Figure 1-1 Click Visual C#

2008 Express Edition

Trang 27

W <St 9 Vv»*> too* tifmi | Q • m •j To* • "

Figure 1 -1 Selecting Visual C# 2008 Express Edition

6 A dialog box appears, asking w here you w ant to store the dow nloaded file The file that you are d o w n lo a d in g is a sm all b o o tstra p file, w h ich y o u ’ll u se to begin th e a ctu al installation of th e Visual C# Express IDE Choose to save the file on the desktop

These steps can be carried o u t very quickly, probably w ithin a few m inutes Do n o t m istake this procedure for dow nloading the com plete Visual C# Express application, because th a t’s n o t

w hat happ ened The installation procedure will dow nload th e vast m ajority of the IDE

Installing Visual C# Express

After you’ve dow nloaded th e setu p file, you can sta rt th e Visual C# Express installation D uring this process, all th e pieces of th e IDE—about 300MB—are dow nloaded a n d installed Follow these steps:

1 O n your desktop, double-click the vc ssetu p ex e file Wait while th e setup program loads all th e req u ired com ponents

2 Click Next on th e initial setup screen

Trang 28

3 A series of dialog boxes will appear Select th e defaults a n d click Next to co n tinue

th rough the setu p program In the final dialog box, click Install

4 After all the elem ents have b een dow nloaded a n d installed, you m ay n eed to restart your com puter

After Visual C# Express is installed, you c an start it by selecting it from the Start m enu

Choosing the Application Type

W ith Visual C# Express running, you’re ready to w rite your first NET application However, first you n e e d to m ake a choice: w h at type of application will you write? Broadly speaking, in NET, you can develop three m ain types of program s:

• A console application is designed to ru n at th e c o m m an d line w ith no user interface

• A Windows application is designed to ru n on a u se r’s desktop an d has a user interface

• A class library holds reusable functionality th a t can be used by console a n d W indows applications It c a n n o t be ru n by itself

So th a t you know w hat each type of program is about, in this chapter, you will code all three They are all variations of th e Hello, World example, w hich displays the text “hello, w orld” on the screen Hello, World program s have been used for decades to dem onstrate what a program m ing language can do

Creating Projects and Solutions

Regardless of w hich pro g ram type you are going to code, w hen using the Visual Studio line of products, you will create projects a n d solutions:

• A project is a classification used to describe a type o f NET application

• A solution is a classification used to describe m ultiple NET applications th a t m ost likely relate to each other

Im agine building a car A project could be th e steering wheel, engine, or car body Putting all of th e car projects to g eth er creates a com plete solu tion called the car

A solution contains projects For the exam ples in this chapter, o u r solution will co ntain three projects represen tin g each of th e three different program types

W hen using Visual C# Express, creating a project implies creating a solution, because creat­ing an em pty solution w ithout a project does not m ake sense It’s like building a car with no parts

W hen I say “project” or "application” in this book, from a workspace organization perspective, it

m eans the sam e thing Solution is an explicit reference to one or m ore projects or applications Our p lan of action in term s of projects an d solutions in this ch a p te r is as follows:

• Create th e NET solution by creating th e W indows application called Examplel (creating this application also creates a solution)

• Add to the created solution a console ap plication called Example2

• Add to the created solution a class library project called Example3

Trang 29

Creating the Windows Application

We’ll dive right in a n d sta rt w ith th e W indows applicatio n W ith Visual C# Express ru n n in g , follow th ese steps to create th e W indows application:

1 Select File > New Project from the m enu

2 Select the W indows A pplication icon This represents a project style based o n a p re d e ­fined tem plate called W indows Application,

3 C hange th e default n a m e to Exarnplel

4 Click OK

These steps create a n ew project and solu tion at th e sam e time: th e Examplel solution an d Exarnplel project Visual C# Express will display a com plete project a n d solution, as show n in Figure 1-2

Trang 30

Viewing the Source Code

W hen you create a new application, Visual C# Express autom atically generates som e source code for it D ouble-click Program cs in the Solution Explorer to see th e generated code The source code show n in Figure 1-3 will a p p ear in th e area to the left of th e Solution Explorer

Note To shift between the user interface and generated code, right-click Form i.cs in the Solution Explorer A submenu appears with the options View Code (to see the code) or View Designer (to see the user interface).

References to other pieces of functionality

A way of organizing source

— | A class called Program

A method within a class called Main

A p p l i c a t i o n E n a f o l e V i s u a l S t y l e s 0 ;

A p p l i c a t i o n S e t C o r o p a t i b l e T e x t R e n d e r i n g D e f a u l t ( f a l s e ) ;

A p p lic a tio n R u n ( n e w Forrol 0 ) ; .

Code within a method used to do something

Figure 1 -3 Source code pieces in a C#file

The elem ents labeled in Figure 1-3 represent th e essence of the C# source code th a t you’ll

be writing You’ll learn ab o u t th em th rou ghout this book For now, th e m ain elem ents to n ote are as follows:

Class: An organizational unit th at groups related code together This grouping is m uch m ore specific th an a solution or a project To use th e car analogy again, if a project is a car engine,

th en a class can be the carburetor, hi other words, projects are m ade up of m ultiple classes

Method: A set of in structio n s th a t carry o ut a task A m eth o d is analogous to a function in

m any o th er languages The Main () m eth o d ru ns w hen an applicatio n starts; therefore, it contains th e code you w an t to use at the beginning of any program

Renaming the Solution

Visual C# Express n a m e d b o th th e solution a n d project Examplel autom atically, w hich isn’t ideal Fortunately, it’s easy to ren am e the solution Follow th ese steps:

Trang 31

1 Right-click th e solution n am e in th e Solution Explorer an d select Renam e from th e context m enu.

2 The solu tio n n am e will b ecom e editable C hange it to ThreeExamples

3 Press E nter to apply the change

You can use th is sam e te c h n iq u e to ren a m e p rojects or any o th e r item s show n in the Solution Explorer

Saving the Solution

After you've ren a m ed th e solution, it’s good practice to save your changes To save th e project, follow these steps:

1 1 Iig h lig h t th e s o lu tio n n a m e in th e S o lu tio n E x p lo rer.

2 Select File >- Save ThreeExam ples sin

3 Notice th a t Visual C# Express w ants to save th e solu tion using th e old Exarnplel nam e,

n o t the new solution n a m e (ThreeExamples) To save th e new solution n am e to th e h ard disk, you n eed to yet again change Exarnplel to ThreeExamples Note the p a th of w here Visual C# Express saves your projects, as you will n e e d to know it from tim e to tim e

4 Click the Save b u tton

W hen th e solution an d project are successfully saved, you’ll see th e m essage “Item(s) Saved” in th e status b ar in the lower-left co rner of th e window

In the future, w henever you w ant to save the solution and project, you can use the keyboard shortcut: Ctrl+S

Note If you have not saved your changes and choose to exit Visual C# Express, you will be asked if you want to save or discard the solution and project.

To o p e n a solution you have previously saved, you can choose File >- O pen Project at any tim e an d navigate to the solution file You can also select th e solution from the R ecent Projects window w hen you first sta rt Visual C# Express The R ecent Projects w indow is always available

on th e Start Page tab of th e m ain Visual C# Express w indow as well

Running the Windows Application

The source code gen erated by Visual C# Express is a basic applicatio n th a t contains an em pty

w indow w ith no functionality The source code gives you a startin g p o in t w here you can add

m ore source code, deb u g th e source code, an d ru n th e application

To ru n th e ap p licatio n , select D ebug >- S tart W ith o u t D ebugging Alternatively, u se th e keyboard sh o rtcu t Ctrl+F5 You’ll see a w indow representin g th e Exarnplel application You can exit th e app licatio n by clicking th e w indow ’s close b u tto n Figure 1-4 illustrates th e process

Trang 32

1 Click to open the Debug menu

fite Edt VBw Refacta Froiect eald Oetoo f Data' Tc<te Wndow CcfnmurRy Heb

s t a t i c c l a s s P r o o r a r a

■ Whdorss

► I Start 0cbu9jr>3 FS t> I S t»t VWthoUt Oehjijjnj

1 Exceptors CtaHD, E t*3 j Steplrto FU Q3l Step Over F10

Figure 1 -4 Running an application

R unning th e application enables you to see w h at it does W hen you ru n an application

th ough th e IDE, it is identical to a user clicking to start the app licatio n from the desktop In this exam ple, Examplel displays an em pty window w ith ou t any controls or functionality The source code’s functionality is to display an em pty w indow w h en started an d provide a b u tto n

to end th e application

You have n o t w ritten a single line of code, yet you have created an application an d so m e­thing actually h a p p en ed , a n d all because Visual C# generates som e boilerplate C# code th a t works straight o u t of th e box

You have created an application, seen its source code, a n d ru n it You did all of this in the context of a com fortable, do-it-all-for-you developm ent environm ent called Visual C# Express Visual C# Express is bo th a good th in g and a bad thing Visual C# Express is good because it hides th e m essy details, b u t it is b a d because th e m essy details are h id d en Im agine being

a car m echanic It is good th a t car m anufacturers p ro d u ce dashb oards th a t have little lights

th at go o n w hen so m eth in g is wrong But it w ould be bad if th e m echan ic had to rely on the little lights to fix problem s in a car

Trang 33

Making the Windows Application Say Hello

The W indows application does n o th in g o th er th a n ap p e ar w ith a blank window th a t you can close To m ake the application do som ething, you n e e d to add user interface elem en ts or ad d som e code A dding code w ith o u t adding u ser interface elem en ts will m ake the p ro gram do som ething, b u t it’s n o t as exciting So, we’ll add a b u tto n that, w h en clicked, will display “hello, world” in a text box

First, you n eed to ad d the B utton control to the form D ouble-click Forml cs in the Solu­tion Explorer to display a blank form Then click th e Toolbox tab to access the controls Click Button, a n d th e n click the form to place th e b u tto n on th e form These steps are illustrated in Figure 1-5

Next, add a TextBox control using the sam e basic procedure Finally, align th e b u tto n an d text box as show n in Figure 1-6 To m ove a control, use th e h a n d le s th a t a p p e ar w h en you highlight th e control Visual C# Express will align the edge of a control to nearby edges as you drag it, so th a t you can align controls accurately

Trang 34

- T h m l u m p l t t * * k io t o ( i Y h iw l 0 » TOO' j l i p i m Id itto n

J J • _J A J • * ' * *

s; V Jit f mjn [ ( n k l 1 )w n i| j«| O n iiH 1 Align the button

near the top of the window

2 Add and align a text

box

K&ai3A3itJa.:

Figure 1 -6 Aligned button and text box

If you now executed Examplel by pressing Ctrl+F5, you w ould see a w indow w ith a b u tto n and a text box You can click th e b u tto n a n d add or delete text from the text box But w hatever you do h as no effect, because n e ith e r control has b een associated w ith any code

To m ake th e applicatio n do som ething, you n eed to think in term s of events. For example,

if you have a garage with an autom atic door opener, you w ould expect th a t pressing th e rem ote control b u tto n w ould o p en th e garage door w hen it’s closed an d close th e door w hen it’s open The au to m atic garage do o r m an u factu rer associated the event of p u sh in g the rem ote control

b u tto n w ith th e action of eith er opening or closing th e garage door In Examplel, we’ll associ­ate th e clicking of th e b u tto n w ith th e action of show ing text in th e text box

Select th e b u tto n on th e form a n d double-click it The w ork area changes to source code, with the cursor in th e button_C lick function Add this source code to function:

T extB o xl.tex t = " h e llo , world";

Figure 1-7 illustrates th e p ro ced u re for associating an event w ith a n action

Trang 35

Figure 1 -7 Associating the button click event with the action o f adding text to the text box

Note th a t textB oxl is th e n a m e o f the text box you a d d e d to th e form This n a m e is gen er­ated by Visual C# Express, ju st as it generated a default n a m e for th e b u tto n You can change the default n am es (through each control’s Properties window), b u t we’ve left th e default for this exam ple

A dding a n ac tio n to a n event is very sim ple w h en following the in stru ctio n s show n in Figure 1-7 The sim plicity is d u e to Visual C# Express, an d n o t because th e event or actio n is sim ple Visual C# Express m akes th e a ssu m p tio n th a t w h en you double-click a control, you

w ant to m odify th e default event of th e control, an d as such, autom atically generates the code

in step 3 o f Figure 1-7 In th e case of a b utton, th e default event is th e click event; th a t is, th e event th a t co rresponds to a user clicking th e b u tto n The assu m p tio n of th e click event being the default event for a b u tto n is logical O ther controls have different default events For exam ­ple, double-clicking a TextBox control will g enerate the code for th e text-changed event

R u n th e a p p lic a tio n by p r e s s in g C trl+ F 5, a n d d i e n c lic k d ie b u tto n T h e te x t b o x fills w ith

th e te x t “h e llo , w o r ld ” C o n g r a tu la tio n s , y o u ’v e j u s t fin is h e d y o u r firs t C # a p p lic a tio n !

You have associated an event w ith an action: th e b u tto n click with th e text display Associ­ating events w ith actions is the basis of all W indows applications

Trang 36

Adding Comments to the Application

Now th a t you have a w orking program , it w ould be good to d o c u m e n t w hat it does, right there

in the source code Then if you com e back to th e application in th e future, you won’t be puzzled

by your previous work In fact, you m ay n o t even be the p e rso n w ho m aintains y our code, so leaving c o m m e n ts in th e code to help explain it is definitely good practice Even if you know you will be m ain tain in g th e code forever, treat you r future self as a stranger You m ay be s u r­prised how long it takes to decipher code you have w ritten w hen revisited m onths or years later

To add a single-line co m m en t, use the following syntax:

/ / A s in g le - lin e comment

A nything after th e / / is ignored by the com piler an d is n o t includ ed in the final ap plica­tion Let’s d o c u m e n t ou r W indows application:

// When the user clicks the button, we display text in the text box

p riv a te void b u tto n i_ C lic k (o b je c t sender, EventArgs e)

{

tex tB o x l.T ex t = " h e llo , world";

}

It’s always w orth leaving sim ple com m ents like this as you go, because it h elps greatly

w hen w orking o u t an application’s logic However, w h at if we w an t to leave longer com m ents, such as a m ore detailed co m m e n t describing a w hole class? The answ er is the m ultiline co m ­

Let’s w rite a m ultiline co m m en t for our W indows application:

namespace Examplel

{

* which displays text when the user clicks the button.

* It is a first look at event-driven programming.

Trang 37

/ / When th e u ser c lic k s th e b u tto n , we

There are o th er variations of com m ents th a t Visual C# Express can hook into to provide

m ore inform ation in its graphical u ser interface (GUI) You’ll learn ab o u t these in C hapter 10

Navigating the User Controls of the Solution

W hen you are w ritin g yo u r code, you r m o st im p o rta n t form of nav ig atio n is th e S olution Explorer The Solution Explorer is th e tree control th a t contains the references to your solu­tions an d projects C onsider th e Solution Explorer as your developer dashboard, w hich you can use to fine-tu ne how your NET application is assem bled a n d executed

I suggest th at you take a m o m en t to click around the Solution Explorer Try som e right-clicks

on various elem ents The context-sensitive click is a fast way of fine-tuning particular aspects of your solution and project However, w hen clicking, please do n o t click OK in any dialog box; for now, click Cancel so th a t any changes you m ay have m ad e are n o t saved

To th e left o f th e Solution Explorer is you r w ork area The w ork area is w here you write your code or edit your user interface The w ork area will display only a single piece of info rm a­tion, w h ich co uld be so m e code, a u ser interface, or a p roject As you saw earlier, w h en you douhle-click Program cs in th e Solution Explorer, th e w ork area displays the code related to the Program.cs file

Program, cs is a p lain -v an illa source code file from Examplel P lain-vanilla so u rce code files are source code files th a t have no special rep resen tatio n in Visual C# Express a n d sim ply contain source code Program.cs contains source code to initialize th e application a n d looks like this:

Trang 38

A pplicatio n.S etC o m p atib leT extR end erin gD efault(false);

T he S o lu tio n E xplorer also show s sp e cia liz ed g rou pin gs, w h ich are specific item s th a t Visual C# Express recognizes an d organizes A specialized g rouping contains a n u m b e r of files

th at rely on each o th er a n d im p lem en t a specific piece of functionality Forml is an exam ple of

a specialized grouping th at m anages th e layout of the user interface, elem ents of the user in ter­face, a n d your custom code The individual file pieces of Forml are illustrated in Figure 1-8

Forml Designer.cs is the Forml source code managed by the IDE

Forml resx is a source code file used to manage graphic elements of Forml

Figure 1 -8 Specialized grouping with three files

In Figure 1-8, th e Solution Explorer contains a top-level item called Forml cs, w hich is

a source code file th a t contains th e user-defined pieces of Forml Forml can be rep resen ted in one of tw o ways in th e work area: graphically a n d textually (source code) For th e m o st part, you will be ed iting Forml cs using source code a n d graphical m ean s, a n d will let Visual C# Express h an d le th e Form l.D esigner.es, an d Form l.resx files

Trang 39

The Forml specialized grouping exists to m ake the organization of the code th at represents the user interface of Forml easier to m anage for you an d th e IDE It does n o t m ean th at you can ­

n ot edit the Form l.D esigner.es an d Forml.resx files If you double-clickForm l.D esigner.cs, you will see source code, w hich you can modify However, be forew arned th a t if you m ess up the source code in th at file, Visual C# Express m ight stop functioning properly when editing Forml.Knowing th at the specialized grouping called Forml should be tak en as a whole, you m ight

w onder w here the definition of textB oxl cam e from The answ er is that textBoxl is defined and assigned in one of the IDE-generated source code files Figure 1-9 illustrates w hat the generated source code file does w ith textB oxl

■' Th ecExam plcs M icro so ft V isu al CP 2 0 0 5 Express E dition

Fite Ede View Rciactcr Prw ct c u b Dotog Oata Toils Window Cwmwnity Hob

B p H .cs

^ Fwtnl.Desisper.es Forml.resx Prcg^m.ct

Locating textBoxl on Forml— notice the use of coordinates 23,41//

irejBn fcto

Figure 1 -9 Visual C# Express-generated code

Notice th a t everything—definition, wiring of events to actions, an d p lacem en t o f th e c o n ­trols—is m an ag ed by Visual C# Express For exam ple, if you were to change the p lacem en t of textB oxl by altering the location coordinates, Visual C# Express w ould read and process th e change However, if you were to m ake larger changes th a t Visual C# Express could n o t process, you w ould c o rru p t th e u ser interface

Now th a t you have a n id ea of how the IDE works, let’s co n tin u e w ith our exam ples Next

up is th e console application

Trang 40

Creating the Console Application

A console applicatio n is a text-based application This m ean s th a t rath e r th an displaying

a GUI, it uses a co m m an d-lin e interface

The console has a very long history because th e console was the first way to in teract w ith

a com puter Consoles are n o t very user-friendly a n d becom e very tedious for any com plex operations, yet som e people claim th at a console is all you need (See h t t p : //e n w ikip ed ia org/ wiki/Com m and_line_interface for m ore inform ation ab o u t the console.)

W riting to the console works only if th e currentiy ru n n in g application has a console To

o pen th e console in W indows, select Start >■ Accessories >- C o m m an d Prom pt Alternatively, select Start >• Run an d type cmd in th e dialog box

Visual C# Express can create, build, an d m anage console applications

Adding a Console Application Project to the Solution

We will now create an application th a t ou tp u ts th e text “hello, w orld” to th e console Follow these steps to ad d th e new project to the ThreeExamples solution:

1 Right-click the solution nam e, ThreeExamples, in th e Solution Explorer

2 Select Add >- New Project

3 Select C onsole A pplication a n d change the n a m e to Example2

The Solution Explorer changes to show th e additional project, an d th e work area displays the source code in th e new Program.cs

Notice th e sim plicity o f the console application It contains a single plain-vanilla source code file, called Program, cs Console applications typically do n o t have any specialized g ro u p ­ings a n d do n o t have any events

Making the Console Application Say Hello

To m ake the console applicatio n do som ething, you n e e d to add som e source code to the Main() m ethod, as follows:

The b olded line w rites th e text “hello, w orld” to th e console

If you tried to ru n the console application by pressing Ctrl+F5, you w ould in stead cause the W indows applicatio n Examplel to run Let’s change th a t next

Ngày đăng: 16/04/2014, 18:08

TỪ KHÓA LIÊN QUAN