1. Trang chủ
  2. » Khoa Học Tự Nhiên

2003 sybex c sharp network programming

1K 101 0

Đ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

Định dạng
Số trang 1.014
Dung lượng 4,86 MB

Nội dung

The C# language has solved many of my network programming problems by allowing me to quickly prototype and deploy network applications using C# classes.. Before learning the basics of ne

Trang 3

On its own, C# simplifies network programming.

Combine it with the precise instruction found in C# Network Programming, and you’ll find that building

network applications is easier and quicker than ever.

This book helps newcomers get started with a look at the basics of network programming as they relate to C#, including the language’s network classes, the

Winsock interface, and DNS resolution Spend as much time here as you need, then dig into the core topics of the network layer You’ll learn to make sockets

connections via TCP, and “connectionless” connections via UDP You’ll also discover just how much help C# gives you with some of your toughest chores, such as asynchronous socket programming, multithreading, and multicasting.

Network-layer techniques are just a means to an end,

of course, and so this book keeps going, providing a series of detailed application-layer programming

examples that show you how to work with real

protocols and real network environments to build and implement a variety of applications Use SNMP to

manage network devices, SMTP to communicate with remote mail servers, and HTTP to Web-enable your applications And use classes native to C# to query and modify Active Directory entries.

Rounding it all out is plenty of advanced coverage to push your C# network programming skills to the limit For example, you’ll learn two ways to share application

Trang 4

methods across the network: using Web services and remoting You’ll also master the security features

intrinsic to C# and NET—features that stand to benefit all of your programming projects.

About the Author

Richard Blum has spent 14 years as a network and

system administrator for the US Department of

Defense, supporting a large network of workstations and servers He holds a BS in Electrical Engineering and an MS in Management Information Systems, both from Purdue University.

Trang 5

Internet screen shot(s) using Microsoft Internet Explorer Version 6reprinted by permission from Microsoft Corporation

Trang 6

distinguish proprietary trademarks from descriptive terms by following thecapitalization style used by the manufacturer

The author and publisher have made their best efforts to prepare thisbook, and the content is based upon final release software wheneverpossible Portions of the manuscript may be based upon pre-releaseversions supplied by software manufacturer(s) The author and the

publisher make no representation or warranties of any kind with regard tothe completeness or accuracy of the contents herein and accept no

liability of any kind including but not limited to performance,

merchantability, fitness for any particular purpose, or any losses or

damages of any kind caused or alleged to be caused directly or indirectlyfrom this book

Manufactured in the United States of America

10 9 8 7 6 5 4 3 2 1

Software License Agreement: Terms and Conditions

The media and/or any online materials accompanying this book that areavailable now or in the future contain programs and/or text files (the

“Software”) to be used in connection with the book SYBEX hereby grants

to you a license to use the Software, subject to the terms that follow Yourpurchase, acceptance, or use of the Software will constitute your

acceptance of such terms

The Software compilation is the property of SYBEX unless otherwiseindicated and is protected by copyright to SYBEX or other copyright

owner(s) as indicated in the media files (the “Owner(s)”) You are herebygranted a single-user license to use the Software for your personal,

noncommercial use only You may not reproduce, sell, distribute, publish,circulate, or commercially exploit the Software, or any portion thereof,without the written consent of SYBEX and the specific copyright owner(s)

of any component software included on this media

In the event that the Software or components include specific licenserequirements or end-user agreements, statements of condition,

Trang 7

disclaimers, limitations or warranties (“End-User License”), those End-particular Software component Your purchase, acceptance, or use of theSoftware will constitute your acceptance of such End-User Licenses

By purchase, use or acceptance of the Software you further agree tocomply with all export laws and regulations of the United States as suchlaws and regulations may exist from time to time

Reusable Code in This Book

The author(s) created reusable code in this publication expressly for

reuse by readers Sybex grants readers limited permission to reuse thecode found in this publication, and available for download from our

provided in the appropriate read.me files or listed elsewhere on the

media

Should the manufacturer(s) or other Owner(s) cease to offer support ordecline to honor any offer, SYBEX bears no responsibility This noticeconcerning support for the Software is provided for your information only.SYBEX is not the agent or principal of the Owner(s), and SYBEX is in noway responsible for providing any support for the Software, nor is it liable

or responsible for any support provided, or not provided, by the Owner(s)

Disclaimer

SYBEX makes no warranty or representation, either expressed or

implied, with respect to the Software or its contents, quality, performance,

Trang 8

SYBEX, its distributors, or dealers be liable to you or any other party fordirect, indirect, special, incidental, consequential, or other damages

arising out of the use of or inability to use the Software or its contentseven if advised of the possibility of such damage In the event that theSoftware includes an online update feature, SYBEX further disclaims anyobligation to provide this feature for any specific duration other than theinitial posting

The exclusion of implied warranties is not permitted by some states.Therefore, the above exclusion may not apply to you This warranty

provides you with specific legal rights; there may be other rights that youmay have that vary from state to state The pricing of the book with theSoftware by SYBEX reflects the allocation of risk and limitations on

register it Individual programs differ on details of trial periods,

registration, and payment Please observe the requirements stated inappropriate files

Copy Protection

The Software in whole or in part may or may not be copy-protected orencrypted However, in all cases, reselling or redistributing these fileswithout authorization is expressly forbidden except as specifically

provided for by the Owner(s) therein

This book is dedicated to Sister Marie Imelda, C.S.C, who in the late 1970s fought and struggled to teach a bunch of goofy high school kids how to program Thanks, Sister “Trust in the Lord with all your heart and lean not on your own understanding; in all your ways acknowledge him, and he will make your paths straight.” Prov 3:5-6 (NIV)

Trang 9

First, all honor, glory, and praise goes to God, who through His Son, allthings are possible, and who gives us the gift of eternal life

I would like to thank all the great people at Sybex for their help, guidance,and professionalism Thanks to Denise Santoro Lincoln, the AcquisitionsEditor, for offering me the opportunity to write this book Also, thanks toCarol Henry, the Developmental Editor, for all her work guiding this bookalong and helping make my paragraphs make sense

Many thanks to Sally Engelfried, the Copy Editor, for turning my poorgrammar into perfect sentences, and to Dan Frumin, the Technical Editor,for going above and beyond the call of duty fixing my programs and

pointing out my technical blunders Also, thanks to Carole McClendon atWaterside Productions for her help in arranging this book for me

Finally, I would like to thank my parents, Mike and Joyce Blum, for theirdedication and support, and my wife Barbara and daughters Katie Janeand Jessica for their faith, love, and understanding, especially while I waswriting this book

The quotation on the bottom of the front cover is taken from the sixty-third chapter of Lao Tzu’s Tao Te Ching, the classic work of Taoist philosophy This particular verse is from the translation by D C Lau (copyright 1963) and communicates the idea that one should confront the difficult while it

is still easy and accomplish a great task by a series of small acts.

It is traditionally held that Lao Tzu lived in the fifth century B.C in China, during the Chou dynasty, but it is unclear whether he was actually a

historical figure It is said that he was a teacher of Confucius The

concepts embodied in the Tao Te Ching influenced religious thinking in the Far East, including Zen Buddhism in Japan Many in the West,

however, have wrongly understood the Tao Te Ching to be primarily a mystical work; in fact, much of the advice in the book is grounded in a practical moral philosophy governing personal conduct.

Trang 10

Networks (and network programming) have come a long way over thepast 20 years In the early days of network computing (the ’80s), networkprogramming was left to the advanced programmer, who typically builtapplications using the C programming language in (mostly) Unix

environments Now, networks are everywhere, from large corporations tosmall home users With so many computers connected together via

networks, network-aware applications are an accepted necessity

Existing applications must incorporate network features to stay

competitive in the marketplace, and adding network communication toapplications is essential Network programs are used for everything fromchildren’s games to advanced corporate database systems

Network programming has always been a key feature of the MicrosoftWindows operating system Unfortunately, you’ve had to know advanced

C or C++ programming concepts to utilize the network programming

features in Windows programs Now, though, the NET Framework

languages simplify the task of adding network features to your

applications The NET libraries provide many network classes that canintegrate network programming

As a network administrator, I’ve written many network programs using the

C and Java languages for both Windows and Unix platforms Today’snetwork management and security requirements make it essential tocommunicate with network devices and track workstations on the

network Trying to quickly write clean network code can be difficult whenyou are working within the structure of the C socket APIs (especially inWinSock), and running Java applications is often a painful experiencedue to slow processing speeds and poor Windows support

The C# language has solved many of my network programming problems

by allowing me to quickly prototype and deploy network applications

using C# classes Combining the C# Forms library to write the graphicalcode with the C# Socket library to write the networking code makes

creating professional network applications simple With C# network

classes, what used to take a day to write often only takes an hour or less

Trang 11

Obviously, if you are a C# programmer who is interested in creating

network programs, this book is specifically intended to help you out I’vedescribed each network C# class in detail, and you’ll find lots of

examples to help you implement the classes in your own work If youhave never before written a network program, I’ve included useful

explanations of the concepts and ideas behind network programming ingeneral, including common techniques for passing data between networkdevices

You may already be familiar with writing network programs using otherlanguages, such as C, C++, or Java In that case, you’ll be interested inseeing how easy it is to do this with the C# language

If you are new to the C# language, the first chapter describes the basics

of creating and compiling C# programs You may want to skip other

chapters in the first part of the book, which discuss network programmingbasics, and dive right into the C#-specific network programming classes

Trang 12

This book is organized into four separate sections that cover a particularaspect of network programming

Part I: Network Programming Basics

The first four chapters are intended for programmers just starting out innetwork programming and looking for some background information

about how network programming works and the pieces that are requiredfor network programming

Chapter 1, “The C# Language,” provides some basic information for thereader new to C#, such as which C# package to use for developmentwork and how to compile C# programs

Chapter 2, “IP Programming Basics,” demonstrates how network

programming has evolved from the Unix world to the world of Windows,via the WinSock interface, and how NET uses the WinSock interface toaccess network resources

Chapter 3, “C# Network Programming Classes,” offers a quick

introduction to the entire C# network libraries and shows the basic

formats of the classes

Chapter 4, “DNS and C#,” rounds out the introductory section by showingnetwork novices how DNS can resolve host addresses and how to usethe C# DNS classes

Part II: Network Layer Programming

The next group of chapters presents the core of network programmingtopics in the book Each of these chapters discusses a major topic using

in creating C# network programs

Chapter 5, “Connection-Oriented Sockets,” starts the discussion of

network programming by introducing stream programming using TCP Inaddition to the standard C# Socket class used for stream programming,common pitfalls are discussed to help you create stream programs that

Trang 13

Chapter 6, “Connectionless Sockets,” discusses how to use the Socketclass to create UDP applications In addition to showing you how to

create UDP applications, this chapter also discusses pitfalls related toUDP programming and shows examples of creating applications that willwithstand the problems inherent in real networks

Chapter 7, “Using the C# Socket Helper Classes,” discusses the C#

TcpClient, TcpListener, and UdpClient classes These are

special classes in NET to help programmers create network programswith minimal effort This chapter also discusses the basics of sendingdifferent data types across the network

Chapter 8, “Asynchronous Socket Programming,” discusses the

technique of using asynchronous programming (prevalent in Windowsprograms) within the network programming world

Chapter 9, “Using Threads,” presents information for using multi-threadedapplication techniques in network programs This technology is oftenused in server applications that must service multiple clients at the sametime

Chapter 10, “IP Multicasting,” describes how to use broadcasting andmulticasting to send packets to multiple clients, cutting down on networkbandwidth

Trang 14

applications using C# SNMP allows you to communicate with many

devices on the network to retrieve network statistics This chapter showsspecific examples of reading a vendor MIB sheet and creating a C#

application to extract the MIB data from the network device

Chapter 13, “SMTP,” describes the C# e-mail classes and shows

examples of using them to send mail using SMTP to remote mail servers.Also, an example of using other mail protocols (such as POP3) is shown

Chapter 14, “HTTP,” presents the C# web classes and how you can usethem to create web-enabled C# applications Also, NET web services ,and how you can use them to host your application methods on an IISserver, are discussed

Chapter 15, “Active Directory,” shows the C# classes for contacting

Microsoft Active Directory servers Examples are presented that showhow to query, change, add, and delete entries in the Active Directory

Chapter 16, “Remoting,” discusses the NET concept of remoting,

allowing an application to share methods with clients across the network.Examples are shown that demonstrate how to create both a remotingserver and client

Chapter 17, “Security,” closes out the book by describing how the NETFramework handles program security, and how you can implement

security in your network applications using encryption techniques

Trang 15

The next group of chapters presents the core of network programmingtopics in the book Each of these chapters discusses a major topic using

in creating C# network programs

Chapter 5, “Connection-Oriented Sockets,” starts the discussion of

network programming by introducing stream programming using TCP Inaddition to the standard C# Socket class used for stream programming,common pitfalls are discussed to help you create stream programs thatwill work on real networks

Chapter 6, “Connectionless Sockets,” discusses how to use the Socketclass to create UDP applications In addition to showing you how to

create UDP applications, this chapter also discusses pitfalls related toUDP programming and shows examples of creating applications that willwithstand the problems inherent in real networks

Chapter 7, “Using the C# Socket Helper Classes,” discusses the C#

TcpClient, TcpListener, and UdpClient classes These are special classes

in NET to help programmers create network programs with minimal

effort This chapter also discusses the basics of sending different datatypes across the network

Chapter 8, “Asynchronous Socket Programming,” discusses the

technique of using asynchronous programming (prevalent in Windowsprograms) within the network programming world

Chapter 9, “Using Threads,” presents information for using multi-threadedapplication techniques in network programs This technology is oftenused in server applications that must service multiple clients at the sametime

Chapter 10, “IP Multicasting,” describes how to use broadcasting andmulticasting to send packets to multiple clients, cutting down on networkbandwidth

Trang 16

All of the examples in this book have been created and compiled usingthe NET Framework 1.0 package Each of the examples willeasily

compile using any of the Microsoft Visual Studio packages (includingVisual C#)

At the time of this writing (2002) the current version of the NET

Framework was version 1.0, with Service Pack 1 Microsoft maintains the.NET Framework website at

http://www.microsoft.com/netframework, where all NET

announcements are posted

Trang 17

Part I: Network Programming Basics

Trang 19

Chapter 1: The C# Language

Trang 20

In its short history, the Microsoft NET technology has quickly become apopular programming platform for developing applications for MicrosoftWindows workstations and servers Although most of the media attentionhas focused around the web application capabilities of NET, there aremany other features that are useful to Windows programmers

One of those features is the new C# programming language, developedspecifically for NET C# is becoming a widely used programming

platform for programmers wanting to create both network-aware andstand-alone applications for Windows systems The language providesmany resources to help create robust Windows-based applications Manyprogrammers are migrating to the C# language to take advantage ofthese resources

Before learning the basics of network programming in C#, it is importantthat you understand the C# programming environment, the fundamentals

of NET, and how to create and distribute C# applications This chaptershows how to create a C# development environment on your system andhow to ensure that C# applications you create will run on other Windowsworkstations and servers Finally, I’ll present a brief introduction to the C#language, along with some C# programming topics relevant to networkprogramming All together, the concepts presented in this chapter willhelp you get ready for C# network programming

Trang 21

The NET group of programming languages differs from previous

versions of Windows programming languages in the way programs arecreated and run on the Windows systems If you are not familiar with howC# programs operate, this section briefly describes the basics you shouldknow to be able to deploy applications based on the NET technologies

Common Language Runtime (CLR)

The core of the Microsoft NET technology is the Common Language Runtime (CLR) environment This environment enables programmers to

create programs using a multitude of programming languages and runthem on any platform that supports the CLR The idea of the CLR is toprovide a middle layer of Application Program Interfaces (APIs) that

operate between the low-level Windows Win32 API functions and theapplication program code By providing a common middle layer, Microsofthas given a larger number of application languages access to core

Windows technologies (such as network support)

The layout of how application programs run in the CLR environment isshown in Figure 1.1 High-level applications written in various NET

languages, such as Visual Basic NET, Visual C++ NET, Visual J# NET,and of course Visual C# NET, are compiled into a special intermediate

language called Microsoft Intermediate Language (MSIL) The MSIL code

is interpreted by the CLR as the program runs; MSIL runs on the hostoperating system as a normal executable program Of course, legacyprograms that do not use the CLR can still directly access the low-levelWindows Win32 APIs as before

Trang 23

on the system Unlike native Windows applications, which interact directlywith the low-level Win32 API system, NET applications rely on the NETFramework CLR to run Running a NET application on a system thatdoes not have the NET Framework installed will produce an error

message like the one in Figure 1.2 The NET Framework is crucial toany NET application, whether it is running on a Windows workstation orserver Without it the MSIL code cannot run Any Windows workstation orserver expected to run NET programs must have the NET Frameworkinstalled

following section includes instructions for installing the NET Frameworkfor a developer environment to allow you to create, compile, and run

.NET applications

Trang 24

Windows XP Home Edition or Professional

Programmers without access to any of these systems will not be able todevelop C# programs—but there is a solution to this, as will be explainedlater in the C# Runtime Environment section

C# Development Options

Microsoft offers three development environments for C# developers.Each environment has its own set of pros and cons This section

examples, no matter which development environmentyou are using

Trang 25

The Visual Studio NET package is the flagship development product forMicrosoft NET This Integrated Development Environment (IDE) offersmany features to assist your Windows application programming tasks.Microsoft describes the Visual Studio package as “a rapid applicationdevelopment (RAD) tool, enabling programmers to quickly code anddebug NET applications.” It includes a complete graphical environmentfor creating Windows forms, typing code, and debugging programs Inaddition to containing a fancy development environment, Visual Studioalso supports all the NET programming languages—Visual Basic NET,Visual C++ NET, Visual J# NET, and Visual C# NET If you are looking

at developing with all of the NET languages, the Visual Studio package

is well worth the extra expense

In Visual Studio NET, applications can be created in a graphical

environment using any of the four programming languages The IDEprovides separate windows for developing code and for visually layingout Window controls for the application, including text boxes, list boxes,buttons, and scrollbars Visual Studio NET offers an easy way to create,test, and debug NET applications, whether they are stand-alone

Windows applications or ASP.NET web pages

There are several package levels for Visual Studio NET, depending onyour development requirements (and budget) Each package level

includes progressively more development functionality, and also comeswith a progressively higher price tag

Visual C# NET

If you are interested only in programming using the C# language, you donot have to buy the full Visual Studio NET package Instead, Microsoftoffers the Visual C# NET package, which has the same functionality ofVisual Studio NET but supports only the C# language This is a muchless expensive method of development for C# programmers Similar toVisual Studio, the Visual C# package also comes in various packagelevels, from a bare-bones student version to a full-featured professionaldeveloper version Before you choose this version, however, be aware

Trang 26

automatic database support, that are in Visual Studio NET

Both the Visual Studio and C# development options require that youpurchase a commercial software development package from Microsoft.Both are excellent software development packages that can save youhours of time in creating Windows and debugging applications However,many first-time and hobbyist programmers might find the cost of theseIDE packages too great

.NET Framework SDK

If you are looking for an inexpensive way to get started with C#

programming, the NET Framework SDK is the way to go The SDK isavailable free from Microsoft and contains command-line tools for

compiling and debugging NET programs, including C# This packageallows you to get the feel for developing C# applications without investing

in an expensive IDE development environment You can obtain the NETFramework SDK package by downloading the complete package viaMicrosoft’s NET Framework website, or by ordering a minimal-cost CDdirectly from Microsoft (See the upcoming section for website

information.)

If you are completely new to C#, you may want to start by downloadingthe NET Framework SDK and giving it a try It is often said that the bestway to learn a programming language is to hand-code all your programsand suffer the consequences—I think this is especially true of networkprogramming As you progress in your C# programming skills, you canmigrate to the Visual C# NET package for creating Windows forms anddebugging complex applications To get you started, the following sectiondescribes how to download and install the NET Framework SDK

Downloading the NET Framework SDK

At the time of this writing, the current version of the NET FrameworkSDK is release 1 As mentioned, it can be downloaded free or you canpurchase a CD from Microsoft If you choose to download the packagefrom Microsoft, there are two methods that can be used Because the

Trang 27

The NET Framework site contains lots of information about the SDK,including a link to the separate software download page The downloadpage shows the various options for downloading the software The

single-file download is a file named setup.exe, which can be

downloaded to your workstation or server for installation If you select themultipart download option, you must download all of the split SDK files,along with the separate setup.bat file, to a temporary directory Afterall of the files are downloaded, you must run the setup.bat file This filecreates the master setup.exe file from all of the SDK split files

In either download scenario, the resulting file will be a setup.exe file.You must run this file to install the NET Framework SDK package Thefollowing section describes this process

Installing the NET Framework SDK

Once the setup.exe file is obtained, either by single download,

multipart download, or CD, you can install the NET Framework SDK Youstart the installation by running the setup.exe file from a DOS

command prompt, or by double-clicking it in Windows Explorer

When the installation starts, a dialog box asks if you want to install the.NET Framework SDK Click the Yes button to start the installation

The NET installation process first extracts the working installation filesinto a temporary directory, pointed to by the TEMP environment variable

Trang 28

After the opening screen and a license agreement screen, you are askedwhich components of the SDK package you want installed This is shown

in Figure 1.3

Figure 1.3: NET Framework

Install Options screen

If you are tight on disk space, you can prevent the SDK samples frombeing loaded on the workstation by deselecting the SDK Samples

checkbox After the Install Options screen, the program asks where toinstall the SDK components This only applies to some of the

components, as the DLLs and executable files used by the NET

Framework must be installed on the system drive (usually C:\) After youselect the installation destination, the installation begins When it’s

completed, you should be ready to compile and run C# programs

Tip It’’s a good idea to check out the Microsoft NET Framework

home page occasionally to see if new service packs are

released, and then to install them as directed

Trang 29

The NET Framework provides not only a development environment, butalso a CLR environment for Windows workstations and servers that onlyrun NET programs The NET Framework contains lots of DLL files used

to supply libraries to support NET application programs These librariesmust be loaded on any workstation or server you want your NET

program to run on However, you do not need to load the NET

Framework SDK on every machine that runs your program As alluded topreviously, Microsoft has a solution to this aggravation

Microsoft has indicated that all future Windows operating systems willinclude the NET Framework runtime (CLR) environment, starting withthe Windows NET Server release This will ensure that NET applicationswill run on the new OSes without your having to manually install any

.NET Framework libraries Unfortunately, this is not the case with olderversions of Windows (98, Me, NT, 2000, and XP) The solution for thesesystems is manually installing a runtime version of the NET Frameworklibraries

The NET Framework runtime version is a much smaller distribution thanthe SDK package It includes only the files necessary to run NET

applications on the Windows workstation or server The following sectiondescribes how to download and install the NET Framework runtime files

on older Windows platforms

Downloading and Installing the C# Runtime Package

The C# runtime package is part of the NET Framework Redistributablepackage The Redistributable package contains runtime environments forall NET languages Similar to the SDK package, the Redistributable

package can be obtained from the NET Framework home page at

www.microsoft.com/netframework/ Because this is a much

smaller distribution, there is no multipart download option The entirepackage must be downloaded as a single piece (about 20MB)

The download file, dotnetredist.exe, is actually a compressed file

Trang 30

named dotetfx.exe

There is not much to installing the NET Framework Redistributable

package After starting the dotnetfx.exe file, you’re asked to confirmthe installation, and then the files are installed You don’t have any choice

as to locations for the Redistributable package files; they all go into

default locations on the system drive

Developing with the C# Runtime

Currently, the NET Framework Redistributable package includes the C#compiler program, csc.exe This allows developers who do not haveworkstations or servers running Windows NT 4, 2000, or XP to compileC# programs without installing the NET Framework SDK Any machinethat supports the NET Framework runtime can be used to compile C#applications using the csc.exe program This includes Windows 98 and

Me workstations Though the compiler is included, none of the

bones development environment

documentation or debugging programs are, so this is pretty much a bare-If you want to compile C# programs from the Redistributable package,you must add the location of the csc.exe program to the PATH

environment variable of your system This differs depending on the

system you are using

For Windows 98 and Me systems, you can add the PATH

statement in the autoexec.bat file located in the C:\ directory.There may already be an autoexec.bat file present, and it mayalready have a PATH statement in it If so, you can append thecsc.exe path to the existing PATH statement

For release 1 of the NET Framework Redistributable package,csc.exe is located in the

C:\Windows\Microsoft.Net\Framework\v1.0.3705

Trang 31

You are now ready to start programming using the C# language

Trang 32

Though it’s considered a bare-bones development environment, the NETFramework SDK contains quite a few tools that allow you to create,

compile, and debug C# programs This section describes some of thetools that are at your disposal

Creating C# Programs

If you are using one of the Microsoft Visual products to develop your

programs (Visual Studio NET or Visual C# NET), you have a completeprogram editing environment, including help files, graphical wizards, andcommand completion wizards If you are using the NET Framework SDKpackage, you are on your own for producing and compiling your C# code.Although this SDK’s features pale in comparison to the fancy Visual

packages, it is nonetheless just as valid a way to produce C#

applications

The first step to working with C# programs in the NET Framework

development environment is to associate the C# source code filenameextension with a text editor This will make editing programs much easier;you can just double-click a program from within the Windows Explorerprogram to begin editing The type of editor you select is important

Choose one that allows you to save your source code files in text moderather than a Microsoft Word doc file or other word processing

document, because the C# compiler must be able to interpret each line ofcode If you do select a word processing package to edit your C#

programs, make sure that you save all of the files in text format

After you select an editor, associate the CS file type to the editor

application within the Windows Explorer: right-click a C# program, selectthe Open With option, and select the appropriate application from the list

If you are new to C#, you may want to practice compiling and debuggingC# programs To do that, you must first have a sample program to workwith Listing 1.1 shows a simple program that demonstrates some basicC# programming principles

Trang 34

SampleClass code could just as easily have been definedfirst, before the DataClass definition The C# compiler willrealize that the required class is located later in the program.You can even declare classes in separate files, as long as youinclude them on the command line when compiling The

compiler will only complain if declared classes are never found

in any of the program files listed on the command line

SampleClass contains two static integer variables, a constructor, and aMain() method, which instructs the C# compiler where to start execution

of the program The Main() method first checks to ensure that two

Trang 36

/debug:type

Creates debugging information for

the executable file The type can

be full (the default), whichenables attaching the debugger to

a running process, or it can bepdbonly, which only creates a.pdb database file for debuggingwithin a debugging tool

The compile was successful if the command prompt returns with no text

messages If any errors or warnings are indicated by the C# compiler,

you must edit the source code file to correct them Each error or warning

produced by the compiler indicates the line where the error occurred

Trang 40

3 Click File ‚ Open ‚ File Select the SampleClass.cs sourcecode file for the application, and click Open

Figure 1.4: Using dbgclr to

single-step through an application

When the debugging process starts, a new window appears showing

Ngày đăng: 25/03/2019, 17:09

TỪ KHÓA LIÊN QUAN

w