The chapter discusses the role of the common language runtime in the .NET Framework, the difference between managed andunmanaged program execution, and the use of assemblies in applicati
Trang 1Copyright © 2003 by Microsoft Corporation
Trang 2MCAD/MCSD Self-Paced Training Kit: Developing XML Web Services andServer
QA76.3.M325565 2002
005.2'768 dc21 2002033714
Printed and bound in the United States of America
1 2 3 4 5 6 7 8 9 QWT 8 7 6 5 4 3
Trang 3A CIP catalogue record for this book is available from the British Library
Microsoft Press books are available through booksellers and distributors
worldwide For further information about international editions, contact yourlocal Microsoft Corporation office or contact Microsoft Press Internationaldirectly at fax (425) 936-7329 Visit our Web site at
www.microsoft.com/mspress Send comments to tkinput@microsoft.com
Active Directory, ActiveX, Authenticode, BackOffice, CodeView, IntelliSense,Jscript, Microsoft, Microsoft Press, MSDN, Visual Basic, Visual C++, VisualC#, Visual J++, Visual J#, Visual Studio, Win32, Windows, and Windows NTare either registered trademarks or trademarks of Microsoft Corporation in theUnited States and/or other countries Other product and company names
mentioned herein may be the trademarks of their respective owners
The example companies, organizations, products, domain names, e-mail
addresses, logos, people, places, and events depicted herein are fictitious Noassociation with any real company, organization, product, domain name, e-mailaddress, logo, person, place, or event is intended or should be inferred
Acquisitions Editor: Kathy Harding
Project Editor: Jean Trenary
Technical Editor: Bob Willer
Body Part No X08-85375
Trang 4Welcome to MCAD/MCSD Training Kit��Developing XML Web Services and Server Components with Microsoft Visual Basic NET and Microsoft Visual C# NET .NET is a new Microsoft technology that offers new application
frameworks such as Web services, ASP.NET, WinForms, and ADO.NET Thisrevolutionary component technology simplifies development and deployment ofcomponents By completing the lessons and exercises in this book, you will beable to build XML Web services and server components
This book also addresses the objectives of the Microsoft Certified ProfessionalExam 70-310 and Exam 70-320
310)
Developing XML Web Services and Server Components with Microsoft Visual C# NET and the Microsoft NET Framework (MCP Exam 70-
320)
Trang 5This course requires that students meet the prerequisites that follow
Be able to create Windows applications using Microsoft Visual Studio.NET in either the Visual Basic NET or Visual C# NET programminglanguage
Have a basic understanding of the object-oriented programming
concepts including classes, properties, methods, and events
Be familiar with Windows-based, Web-based, and console-basedapplication development and deployment
Have a basic knowledge of COM programming
Understand how Web content is stored and accessed over the Internet.This includes being able to explain the roles of Web servers, Internetprotocols, and Web clients (such as browsers)
Be familiar with XML and related technologies such as XPath andXSD
Trang 6A complete electronic version of this training kit
Completed labs
Each chapter in this book concludes with a lab containing a series ofexercises that reinforce the skills you learned Completed versions ofthese applications are included so that you can compare your results.You can also use the completed applications as a reference if you needhelp while completing an exercise
Sample exam questions
To practice taking a certification exam, you can use the sample examquestions provided on the CD-ROM The sample questions help youassess your understanding of the concepts presented in this book
About the DVD
The DVD contains a 60-day evaluation edition of Microsoft Visual Studio NETProfessional Edition
http://www.microsoft.com/mspress/support You can also e-mail
tkinput@microsoft.com or send a letter to Microsoft Press, Attn: Microsoft PressTechnical Support, One Microsoft Way, Redmond, WA 98052-6399
Features of This Book
Each chapter contains sections that are designed to help you get the most
educational value from the chapter
Trang 7The chapters are then divided into lessons Each lesson contains thereference and procedural information used for a specific skill or skills.The "Summary" section identifies the key concepts from the lesson.The "Lab" section provides hands-on exercises that reinforce the skillstaught in each of the chapter lessons The exercises offer step-by-stepprocedures that give you an opportunity to use the skills being presented
or explore the part of the application being described
Appendix A, "Questions and Answers," contains all of the questions asked ineach chapter review and the corresponding answers
Trang 8Icon Represents
Supplemental course materials You will find these materials onthe Supplemental Course Materials CD-ROM
A hands-on practice You should perform the practice to giveyourself an opportunity to use the skills being presented in thelesson
Chapter review questions These questions at the end of eachchapter allow you to test what you have learned in the lessons.You will find the answers to the review questions in Appendix
A, "Questions and Answers," at the end of the book
Chapter and Appendix Overview
This self-paced training kit combines notes, hands-on procedures, and reviewquestions to teach you how to develop XML Web services and server
components with Visual Studio NET It is designed to be worked through frombeginning to end, but you can choose a customized track and complete only thesections that interest you (See the next section, "Finding the Best Starting Pointfor You," for more information.) If you choose the customized track option, see
Trang 9The book is divided into the following sections and chapters
This "About This Book" section contains a self-paced training overviewand introduces the components of this training kit Read this sectionthoroughly to get the greatest educational value from this self-pacedtraining and to plan which lessons you will complete
Chapter 1, "Understanding the NET Framework," introduces the
fundamentals of the Microsoft NET Framework, which is the
infrastructure for developing highly distributed applications for theInternet The chapter discusses the role of the common language
runtime in the NET Framework, the difference between managed andunmanaged program execution, and the use of assemblies in applicationdeployment and configuration In addition, the chapter describes how touse the tools that the NET Framework provides for creating, deploying,and managing applications
Chapter 2, "Creating and Managing Windows Services," explains theWindows service programming model and includes sections on thecreation of Windows services in Microsoft Visual Studio NET and themechanisms used to control the behavior of Windows services Youlearn to make entries in default event logs, create custom event logs,and record information in custom event logs You also learn to
configure a service dynamically and manage a service manually andprogrammatically
Chapter 3, "Creating and Consuming Serviced Components," describesthe serviced components that enable access to COM+ services, such asautomatic transaction management, object pooling, and just-in-time(JIT) activation You learn about the basics of the COM+ programmingmodel, create and register serviced components, utilize COM+ services,and manage serviced components using the Component Services tool.Chapter 4, "Creating and Consuming NET Remoting Objects,"
demonstrates the use of the NET Framework to establish
communication between objects without having to know about the
Trang 10Chapter 5, "Database Programming Using ADO.NET," shows you how
to use ActiveX Data Objects (ADO) for the NET Framework In thischapter, you learn to use the NET data providers, and create and useADO.NET DataSets In addition, you learn to manage and control datausing Data�Reader and DataAdapter objects
Chapter 6, "Accessing and Manipulating XML Data," explains the
importance of XML as the core to data exchange between applications
in the NET Framework This chapter discusses the XML DocumentObject Model (DOM) and shows how to access XML data in
applications You learn how to read and write data from XML
documents, perform queries on XML documents, and validate XMLdocuments with the XML Schema In addition, you learn to populate aDataSet with data from an XML file and write data from a DataSet into
an XML file
Chapter 7, "Creating and Consuming XML Web Services," shows youhow to build scalable, loosely-coupled, platform-independent
Chapter 9, "Testing and Debugging XML Web Services," shows how todebug XML Web services and serviced components You also learn how
to use tracing and perform code instrumentation
Chapter 10, "Deploying XML Web Services and Windows Services,"explains the deployment options that the NET Framework provides.You learn to create setup programs that allow you to install your NETapplications In addition, you learn to implement versioning and side-by-side deployment
Trang 11suggested answer
Appendix B, "COM Interoperability," provides additional informationabout how to call unmanaged COM objects from within your managedapplications You learn to export COM types and create interop
assemblies from your COM type libraries
The Glossary provides definitions for many of the terms and conceptspresented in this training kit
Finding the Best Starting Point for You
Because this book is self-paced, you can skip some lessons and revisit themlater Use the following table to find the best starting point for you
Want to review information about
specific topics from the exam
Use the "Where to Find Specific Skills
in This Book" section that follows thistable
Where to Find Specific Skills in This Book
The following tables provide a list of the skills measured on certification Exam
70-310, Developing XML Web Services and Server Components with Microsoft Visual Basic NET and the Microsoft NET Framework, or Exam 70-320,
Developing XML Web Services and Server Components with Microsoft Visual C# NET and the Microsoft NET Framework The tables that follow indicate skills
and where in this book you will find the lesson or lessons relating to those skills
Exam skills are subject to change without prior notice at the sole
discretion of Microsoft
Table A-1 Creating and Managing Microsoft Windows Services,
Trang 14serviced component, a NET Remoting
object, and an XML Web service
Chapter 2, Lessons 4 and 6;Chapter 3, Lesson 5; Chapter 4,Lesson 6; and Chapter 8,
Lesson 4Access unmanaged code from a Windows
Manipulate a DataSet schema Chapter 5, Lesson 3and Chapter 6, Lesson
6Manipulate DataSet relationships Chapter 5, Lesson 3
Create a strongly typed DataSet Chapter 5, Lesson 3and Chapter 6, Lesson
6Access and manipulate XML data Chapter 6, Lessons 1,
2, 3, 4, 5, and 6
Access an XML file using the Document
Object Model (DOM) and an XmlReader
Chapter 6, Lessons 1and 2
Transform DataSet data into XML data Chapter 6, Lesson 6
Use XPath to query XML data Chapter 6, Lesson 3
Trang 15Generate and use an XSD schema Chapter 6, Lesson 4
Write a SQL statement that retrieves XML
data from a SQL Server database
Chapter 5, Lessons 2and 3; and Chapter 6,Lesson 6
Update a SQL Server database using XML Chapter 5, Lessons 2and 3; and Chapter 6,
Lesson 6Validate an XML document Chapter 6, Lesson 5
Trang 16Use interactive debugging Chapter 9, Lesson 2
and Chapter 2,Lesson 3Resolve errors and rework code Chapter 9, Lessons 1and 2
Trang 174, Lesson 6; and Chapter 8,Lesson 4
Trang 18160 MB physical memory, 256 MB recommended
CD-ROM or DVD drive, 12x or faster recommended
A DVD drive is required to install the Visual Studio NETProfessional Evaluation Edition software
3.5 GB on installation drive, which includes 500 MB on system driveSuper VGA (800 X 600) or higher resolution monitor with 256 colorsMicrosoft Mouse or compatible pointing device
Software Requirements
The following software is required to complete the procedures in this course
Microsoft Windows 2000 or Microsoft Windows XP ProfessionalEdition
If IIS is not installed on your computer, you can install it byopening Add Or Remove Programs in Control Panel, andselecting Add/Remove �Windows Components SelectInternet Information Services (IIS) from the Components listand then follow the onscreen instructions to complete theinstallation
Microsoft Visual Studio NET Professional Edition or Visual Studio.NET Enterprise Developer Edition The Professional Edition is
Trang 19The Supplemental Course Materials CD-ROM contains a set of solution files tothe lab exercises at the end of each chapter
To access the solution files
1
Insert the Supplemental Course Materials CD-ROM into your CD-ROM drive
If Autorun is disabled on your machine, run StartCD.exe inthe root directory of the CD-ROM or refer to the
Readme.txt file
2 Select Solution Folder on the user interface menu, and then browse tothe chapter folder you want to view
The eBook
The CD-ROM also includes a fully searchable electronic version of the book Toview the eBook you must have Microsoft Internet Explorer 5.01 or later and theproper HTML components on your system If your system does not meet theserequirements, you can install Internet Explorer 6 SP1 from the CD-ROM prior toinstalling the eBook
To use the eBook
1
Insert the Supplemental Course Materials CD-ROM into your CD-ROM drive
If Autorun is disabled on your machine, run StartCD.exe inthe root directory of the CD-ROM or refer to the
Readme.txt file
2 Click eBook on the user interface menu and follow the prompts
Trang 20
The Exam Questions
The CD-ROM also includes an assessment tool that generates a 50-questionpractice exam with automated scoring and answer feedback
To install the sample exam questions on your hard disk drive
1 ROM drive
Insert the Supplemental Course Materials CD-ROM into your CD-If Autorun is disabled on your machine, run StartCD.exe inthe root directory of the CD-ROM or refer to the
Readme.txt file
2 Click Sample Exam Questions on the user interface menu and followthe prompts
The Microsoft Certified Professional Program
The Microsoft Certified Professional (MCP) program provides the best method
to prove your command of current Microsoft products and technologies
Microsoft, an industry leader in certification, is on the forefront of testingmethodology Our exams and corresponding certifications are developed tovalidate your mastery of critical competencies as you design and develop, orimplement and support, solutions with Microsoft products and technologies.Computer professionals who become Microsoft certified are recognized asexperts and are sought after industry-wide
The Microsoft Certified Professional program offers multiple certificationsbased on specific areas of technical expertise including:
Microsoft Certified Application Developer (MCAD) for Microsoft.NET
Qualified to develop and maintain department-level applications,
components, Web or desktop clients, or back-end data services
Trang 21Microsoft Certified Systems Administrator (MCSA) on Microsoft
�Windows 2000
Qualified to implement, manage, and troubleshoot existing network andsystem environments based on the Microsoft Windows 2000 and
Windows NET Server 2003 operating systems
Microsoft Certified Database Administrator (MCDBA) on MicrosoftSQL Server 2000
Qualified to derive physical database designs, develop logical datamodels, create physical databases, create data services using Transact-SQL, manage and maintain databases, configure and manage security,monitor and optimize databases, and install and configure MicrosoftSQL Server
Microsoft Certified Trainer (MCT)
Instructionally and technically qualified to deliver Microsoft OfficialCurriculum through a Microsoft Certified Technical Education Center(CTEC)
Trang 22Microsoft certification, one of the most comprehensive certification programsavailable for assessing and maintaining software-related skills, is a valuablemeasure of an individual's knowledge and expertise Microsoft certification isawarded to individuals who have successfully demonstrated their ability toperform specific tasks and implement solutions with Microsoft products Notonly does this certification provide an objective measure for employers to
consider, but it also provides guidance for what an individual should know to beproficient As with any skills-assessment and benchmarking measure,
certification brings a variety of benefits to the individual, and to employers andorganizations
Microsoft Certification Benefits for Individuals
As a Microsoft Certified Professional, you receive many benefits including:
Industry recognition of your knowledge and proficiency with Microsoftproducts and technologies
A Microsoft Developer Network subscription MCPs receive rebates ordiscounts on a one-year subscription to the Microsoft Developer
Network (http://msdn.microsoft.com/subscriptions) during the first year
http://www.microsoft.com/traincert/mcp/mcpsecure.asp and click the
"Other Benefits" link)
An MCP logo, certificate, transcript, wallet card, and lapel pin to
identify you as an MCP to colleagues and clients Electronic files oflogos and transcripts can be downloaded from the MCP secured Website (go to http://www.microsoft.com/traincert/mcp/mcpsecure.asp)
Trang 23Invitations to Microsoft conferences, technical training sessions, andspecial events
Free access to Microsoft Certified Professional Magazine Online, a
career and professional development magazine Secured content on the
Microsoft Certified Professional Magazine Online Web site includes the
current issue (available only to MCPs), additional online-only contentand columns, an MCP-only database, and regular chats with Microsoftand other technical experts
A discount on a membership to PASS (for MCPs only), the ProfessionalAssociation for SQL Server In addition to playing a key role in the onlyworldwide, user-run SQL Server user group endorsed by Microsoft,members enjoy unique access to a world of educational opportunities(go to http://www.microsoft.com/traincert/mcp/mcpsecure.asp)
An additional benefit is received by Microsoft Certified System Engineers(MCSEs):
A 50-percent rebate or discount off the estimated retail price of a one-year subscription to TechNet or TechNet Plus during the first year of
certification (Fulfillment details will vary, depending on your location.Please see your Welcome Kit.) In addition, about 95 percent of the CD-
Trang 24Reliable benchmarks for hiring, promoting, and career planning
Recognition and rewards for productive employees by validating their
�expertise
Retraining options for existing employees so they can work effectivelywith new technologies
Assurance of quality when outsourcing computer services
Requirements for Becoming a Microsoft Certified Professional
Certification requirements differ for each certification and are specific to theproducts and job functions addressed by the certification
To become a Microsoft Certified Professional, you must pass rigorous
certification exams that provide a valid and reliable measure of technical
proficiency and expertise These exams are designed to test your expertise andability to perform a role or task with a product, and are developed with the input
of professionals in the industry Questions in the exams reflect how Microsoftproducts are used in actual organizations, giving them "real-world" relevance
Microsoft Certified Professional candidates are required to pass oneoperating system exam Candidates can also pass additional Microsoftcertification exams to further qualify their skills with other Microsoft
Trang 25Microsoft Certified Systems Engineers are required to pass five coreexams and two elective exams
Microsoft Certified Systems Administrators are required to pass threecore exams and one elective exam that provide a valid and reliable
measure of technical proficiency and expertise
Microsoft Certified Database Administrators are required to pass threecore exams and one elective exam that measure technical proficiencyand expertise
Microsoft Certified Solution Developers are required to pass three coreMicrosoft Windows operating system technology exams and one
BackOffice technology elective exam
Microsoft Certified Trainers are required to meet instructional and
technical requirements specific to each Microsoft Official Curriculumcourse they are certified to deliver The MCT program requires ongoingtraining to meet the requirements for the annual renewal of certification.For more information about becoming a Microsoft Certified Trainer,visit http://www.microsoft.com/traincert/mcp/mct or contact a regionalservice center near you
Technical Training for Computer Professionals
Technical training is available in a variety of ways: instructor-led classes, onlineinstruction, or self-paced training available at thousands of locations worldwide
Self-Paced Training
For motivated learners who are ready for the challenge, self-paced instruction isthe most flexible, cost-effective way to increase your knowledge and skills
A full line of self-paced print and computer-based training materials is availabledirect from the source��Microsoft Press Microsoft Official Curriculum
course-ware kits from Microsoft Press are designed for advanced computersystem pro�fessionals and are available from Microsoft Press and the MicrosoftDeveloper �Division Self-paced training kits from Microsoft Press featureprint-based instructional materials, along with CD-ROM��based product
Trang 26Mastering Series provides in-depth, interactive training on CD-ROMs for
experienced developers They're both great ways to prepare for the MicrosoftCertified Professional (MCP) exams
Online Training
For a more flexible alternative to instructor-led classes, turn to online instruction.It's as near as the Internet, and it's ready whenever you are Learn at your ownpace and on your own schedule in a virtual classroom, often with easy access to
an online instructor Without ever leaving your desk, you can gain the expertiseyou need Online instruction covers a variety of Microsoft products and
technologies It includes options ranging from Microsoft Official Curriculum tochoices available nowhere else It's training on demand, with access to learningresources 24 hours a day Online training is available through Microsoft
Certified Technical Education Centers (CTECs)
Microsoft Certified Technical Education Centers
Microsoft Certified Technical Education Centers are the best source for
instructor-led training that can help you prepare to become a Microsoft CertifiedProfessional The Microsoft CTEC program is a worldwide network of qualifiedtechnical training organizations that provide authorized delivery of MicrosoftOfficial Curriculum courses by Microsoft Certified Trainers to computer
professionals
For a listing of CTEC locations in the United States and Canada, visit the Website at http://www.microsoft.com/traincert/ctec
Technical Support
Every effort has been made to ensure the accuracy of this book and the contents
of the companion disc If you have comments, questions, or ideas regarding thisbook or the companion disc, please send them to Microsoft Press using either ofthe following methods:
E-mail:
TKINPUT@MICROSOFT.COM
Trang 27Microsoft Press
Attn: MCAD/MCSD Training Kit: Developing XML Web Services and
Server Components with Microsoft Visual Basic NET and Microsoft Visual C# NET Editor
One Microsoft Way
Redmond, WA 98052-6399
The Microsoft Press Web site (http://www.microsoft.com/mspress/support)
provides corrections for books Please note that product support is not offeredthrough this Web site For further information regarding Microsoft softwaresupport options, please connect to http://www.microsoft.com/support or callMicrosoft Support Network Sales at (800) 936-3500
For information about ordering the full version of any Microsoft software, pleasecall Microsoft Sales at (800) 426-9400 or visit http://www.microsoft.com
Trang 28To complete the lessons in this chapter, you
Must have Microsoft Visual Studio NET installed on your computerMust be familiar with development and deployment of Windows-based,Web-based, and Console-based applications
Must be able to create, compile, and execute Microsoft Visual Basic.NET and Microsoft Visual C# applications
Each chapter in this book concludes with a lab containing a series of exercisesthat reinforce the concepts and skills presented in the lessons Completed
versions of these applications are included on the Supplemental Course
Materials CD-ROM so that you can compare your results You can also use thecompleted applications as a reference if you get stuck while completing an
exercise The \Solution folder on the CD-ROM contains the code required tocomplete each lab so that you won't need to enter the code manually
Trang 29Microsoft NET is software that enables you to develop applications for differentenvironments and devices For example, you can build eXtensible Markup
�Language (XML) Web services and Web applications for a highly distributedenvironment such as the Internet You can also create traditional Windows-basedapplications, server components, and applications that can run on any device,such as a PC or a mobile device In addition, NET enables seamless data
exchange between various applications and devices The NET Framework is theinfrastructure that provides the execution engine and run-time services to
written in different languages and for different environments .NET enablesvarious applications to exchange data by using XML Web services In addition,.NET provides remoting infrastructure that allows applications running in
different processes, on the same or different computers, to exchange data usingbinary or HTTP protocols
Trang 30Smart Client software
This software allows a client, a PC, or a mobile device to access datafrom any location or device by using XML Web services
.NET Server infrastructure
This provides a highly secure and scalable platform for deploying NETapplications The NET Server infrastructure includes Windows 2000Servers, Windows NET Servers, and NET Enterprise Servers
XML Web services
These are core to application integration in the NET environment Theyallow Internet as well as intranet applications, written in different
languages and hosted on different platforms, to exchange data usingstandard protocols such as HTTP, XML, and SOAP (XML Web
Trang 31As shown in Figure 1.1, XML Web services comprise the core components thatenable a client application to exchange data with another client or server
application Using XML Web services, server applications can also exchangedata with each another In addition, applications running on any device can
exchange data with the applications running on any other device
Understanding the NET Framework and Its Role in NET
The NET Framework is the infrastructure for building applications using NET.The NET Framework provides a consistent object-oriented programming modelthat you can use to build all types of applications The approach for creatingvarious applications such as Windows-based applications and XML Web
services is the same To create a NET application, you create a class and definethe functionality of the application in terms of properties, events, and methods ofthe class Even for Web applications, the code that controls the behavior of theWeb page is encapsulated within a class In addition, classes support object-oriented features such as inheritance, encapsulation, and polymorphism
Therefore, classes are �fundamental to programming in the NET environment.You can create classes in any language supported by the NET Framework A
Trang 32Framework allows language interoperability and supports cross-language
inheritance
The European Computer Manufacturers Association (ECMA) standard definesthe Common Language Specification (CLS), which contains the rules for
language interoperability The code written in a CLS-compliant language isinteroperable with the code written in another CLS-compliant language becausethe code written in a CLS-compliant language is compiled into an intermediatelanguage (IL) code The run-time engine executes the IL code This ensuresinteroperability between CLS-compliant languages
The NET Framework provides four CLS-compliant languages: Microsoft VisualBasic NET, Microsoft Visual C#, Microsoft Visual C++ NET, and MicrosoftVisual J# NET Visual C# was ratified by ECMA as an international standard onDecember 13, 2001 The compilers of these languages generate an intermediatecode, called Microsoft Intermediate Language (MSIL), which makes programswritten in the NET languages interoperable Therefore, in the NET Framework,you can use any language to create applications, and these applications can
interoperate with the applications written by others in different languages
The ECMA standard, Common Language Infrastructure (CLI), defines the
specifications for the infrastructure that the IL code needs for execution TheCLI provides a common type system (CTS) and services such as type safety andmanaged code execution The NET Framework provides the infrastructure andservices per the CLI specifications These include
Common language runtime
This includes the CLI and provides the execution environment to NETapplications All the NET language compilers compile the source codeinto MSIL code, which the common language runtime loads and
executes when you run an application
Common type system
This provides the necessary data types, value and object types, whichyou need to develop applications in different languages All the NETlanguages share a CTS This implies that a String in Visual Basic NET
Trang 33.NET languages have access to the same class libraries In addition, alllanguages are equally powerful There is no superior language in NET;Visual Basic NET is as powerful as Visual C# or Visual C++ NET
Type safety
The NET Framework ensures that operations to be performed on onevalue or object are performed on that value or object only To do this,the NET Framework requires that each value or object has a type andthat each reference to a value or an object also has a type
Managed code execution
The NET Framework loads and executes the NET applications, andmanages the state of objects during program execution In addition, the.NET Framework automatically allocates memory and provides an
The common language runtime consists of components that load the IL code of a
Trang 34Figure 1.2 shows the components of the NET Framework
Figure 1-2 .NET Framework components
The code that runs within the common language runtime is called managed code,whereas the code that runs outside the common language runtime is called
unmanaged code The common language runtime provides an interoperabilitylayer, which allows both the managed code and the unmanaged code to
interoperate with each other
Various components within the common language runtime work together toprovide the infrastructure and the run-time services The common languageruntime and its components are described in Lesson 2
Trang 35As described in the previous lesson, the common language runtime is one of themain components of the NET Framework It provides the run-time environmentand various run-time services to applications Various components of the
common language runtime work together to provide the run-time infrastructure
to the applications that run on the NET Framework By learning the commonlanguage run-time architecture, the various components of the common languageruntime, and the functions of each common language runtime component, youwill be able to describe how the common language runtime functions within the.NET Framework
After this lesson, you will be able to
Describe the architecture of the common language runtime
Describe how different components of the common language runtimework together to provide the run-time environment and services
Estimated lesson time: 20 minutes
Common Language Runtime Architecture
The common language runtime consists of various components that provide therun-time environment and run-time services for your applications These
components load the IL code of an application into the runtime, compile the ILcode into native code, execute the code, and enforce security In addition, thesecomponents implement type safety and provide automatic memory managementand thread support The components of the common language runtime also
provide an exception manager, a common debugger, and other system services,such as base class library support and interoperability
Figure 1.3 shows the various components that constitute the common
language runtime
Trang 36Class loader, which loads classes into the runtime
MSIL to native code compiler, which converts MSIL code into nativecode
Code manager, which manages the code during execution
Garbage collector, which performs automatic memory management.Security engine, which enforces security restrictions
Type checker, which enforces strict type checking
Thread support, which provides multithreading support to applications.Exception manager, which provides a mechanism to handle the run-time
�exceptions
Debug engine, which allows you to debug different types of
applications
COM marshaler, which allows NET applications to exchange data withCOM applications
Base class library support, which provides the types that the
applications need at run time
Trang 37Common Language Runtime Components
For a program to run within the common language runtime and benefit from themanaged execution environment, you need to write the source code of the
program in a CLS-compliant language The compilers of CLS-compliant
languages compile the source code and generate an intermediate code, calledMSIL code, and metadata The MSIL code contains a CPU-independent set ofinstructions, which describes how to load, store, initialize, and call methods onobjects MSIL code also contains instructions that enable you to perform
arithmetic and logical operations, access memory directly, control the flow ofexecution, handle exceptions, and perform other operations Before you executethe MSIL code, you need to compile it into CPU-specific instructions To
execute the code, the runtime requires information about the code that is in themetadata The metadata describes the code and defines the types that the codecontains as well as references to other types that the code uses at run time TheMSIL code and the metadata are located in a portable executable file
When you execute a portable executable file, the class loader loads the MSIL
Trang 38memory Before the code is executed, it is passed to the native code compiler forcompilation The IL to native code compiler contains just-in-time (JIT)
compilers for different CPU architectures and compiles the IL code into a nativeinstruction set The IL to native code compilation occurs when a method is calledfor the first time For subsequent calls to the method, the existing JIT-compiledcode is executed Figure 1.4 shows the JIT compilation process
to identify the objects that are no longer required by the program and removesthem from memory
During program execution, the type checker ensures that all objects and values,and the references to those objects and values, have a valid type The type
Trang 39assigned to a variable of integer type The type checker raises an error if a stringvalue is assigned to an integer variable In addition, the type checker also
ensures that only valid operations such as addition, subtraction, division, andmultiplication are performed on an integer value
The common language runtime controls the code at run time The security
engine of the common language runtime enforces restrictions on the code andcontrols the access to system resources such as the hard disk, network
connections, and other system resources
The applications running within the common language runtime can utilize themanaged multithreading support The NET Framework allows a single process
to be divided into one or more subprocesses called application domains Eachapplication domain can contain one or more threads The runtime monitors allthe threads that have executed code within its process
The common language runtime also allows managed code to interoperate withunmanaged code One of the components of the common language runtime is the
COM marshaler, which performs marshaling of data when data passes between managed and unmanaged execution environments Marshaling manages the
The common language runtime also provides a common debug engine, whichenables you to debug an application written in any language supported by the.NET Framework The common debug engine supports debugging applicationsrunning on local and remote machines
The process by which different components of the common language runtime
Trang 40provide the infrastructure and run-time services to managed code is called themanaged execution process During managed execution, managed code utilizesthe automatic memory management provided by the garbage collector The nextlesson discusses the managed execution process.