+ All Categories
Home > Documents > Module 2: Introduction to a Managed Execution...

Module 2: Introduction to a Managed Execution...

Date post: 28-Jan-2020
Category:
Upload: others
View: 0 times
Download: 0 times
Share this document with a friend
36
Contents Overview 1 Writing a .NET Application 2 Compiling and Running a .NET Application 11 Lab 2: Building a Simple .NET Application 29 Review 32 Module 2: Introduction to a Managed Execution Environment
Transcript
Page 1: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

Contents

Overview 1

Writing a .NET Application 2

Compiling and Running a .NET Application 11

Lab 2: Building a Simple .NET Application 29

Review 32

Module 2: Introduction to a Managed Execution Environment

Page 2: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation. Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. 2001-2002 Microsoft Corporation. All rights reserved. Microsoft, ActiveX, BizTalk, IntelliMirror, Jscript, MSDN, MS-DOS, MSN, PowerPoint, Visual Basic, Visual C++, Visual C#, Visual Studio, Win32, Windows, Windows Media, and Window NT are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

Page 3: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

Module 2: Introduction to a Managed Execution Environment 1

Overview

! Writing a .NET Application

! Compiling and Running a .NET Application

*****************************illegal for non-trainer use******************************

This module introduces the concept of managed execution and shows you how to quickly build applications that use the Microsoft® .NET Framework common language runtime environment. A simple Hello World version of a console application illustrates most of the concepts that are introduced in this module.

Because this course is an introduction to programming in the .NET Framework, you should spend some time reading the .NET Framework software development kit (SDK) documentation. In fact, the labs, demonstrations, and material for this module and other modules in this course are based on several tutorials in the .NET Framework SDK.

After completing this module, you will be able to:

! Create simple console applications in C#. ! Explain how code is compiled and executed in a managed execution

environment. ! Explain the concept of garbage collection.

Topic Objective To provide an overview of the module topics and objectives.

Lead-in This module introduces the concept of managed execution and shows you how to quickly build applications that use the Microsoft .NET Framework common language runtime environment.

Page 4: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

2 Module 2: Introduction to a Managed Execution Environment

"""" Writing a .NET Application

! Using a Namespace

! Defining a Namespace and a Class

! Entry Points, Scope, and Declarations

! Console Input and Output

! Case Sensitivity

*****************************illegal for non-trainer use******************************

Because all supported languages use the Common Type System and the .NET Framework base class library, and run in the common language runtime, programs in the supported languages are similar. The most significant difference in programming with the supported languages is syntax.

In this module, and in Modules 3 and 4, Notepad is used as the source code editor, instead of the Microsoft Visual Studio® .NET development environment. The examples in these modules are simple enough to be compiled and built directly from a command prompt window. Working in Notepad will allow you to focus on the compilation and execution processes.

Topic Objective To introduce the topics in the section.

Lead-in Because all supported languages use the Common Type System and the .NET Framework class library, and run in the common language runtime, programs in the supported languages are similar.

Delivery Tip Stress the importance of understanding the process of compiling and running the .NET applications. Using Visual Studio .NET at this time may obscure the underlying processes.

Note

Page 5: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

Module 2: Introduction to a Managed Execution Environment 3

Demonstration: Hello World

*****************************illegal for non-trainer use******************************

In this demonstration, you will learn how to build a simple application in C#.

! To create the source code in C# 1. Open Notepad and type the following code:

// Allow easy reference to System namespace classes using System; // Create class to hold program entry point class MainApp { public static void Main() { // Write text to the console Console.WriteLine(�Hello World using C#!�); } }

2. Save the file as HelloDemoCS.cs

Topic Objective To demonstrate how to build a simple application in C#.

Lead-in In this demonstration, you will learn how to build a simple application in C#.

Delivery Tip As this is a short, simple demonstration, you may want to let students try it themselves.

Page 6: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

4 Module 2: Introduction to a Managed Execution Environment

! To compile the source code and build an executable program

To use Visual Studio .NET tools within a command prompt window, the command prompt window must have the proper environment settings. The Visual Studio .NET Command Prompt window provides such an environment. To run a Visual Studio .NET Command Prompt window, click Start, All Programs, Microsoft Visual Studio .NET, Visual Studio .NET Tools, and Visual Studio .NET Command Prompt.

• From a Visual Studio .NET Command Prompt window, type the following syntax: csc HelloDemoCS.cs Running the resulting executable will generate the following output: Hello World using C#!

Important

Page 7: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

Module 2: Introduction to a Managed Execution Environment 5

Using a Namespace

! Classes Can Be Fully Referenced

! Or the Namespace of a Class Can Be Referenced

# No need to fully qualify contained class names

// declares a FileStream objectSystem.IO.FileStream aFileStream;

// declares a FileStream objectSystem.IO.FileStream aFileStream;

using System.IO;...

FileStream aFileStream;

using System.IO;...

FileStream aFileStream;

*****************************illegal for non-trainer use******************************

You can fully reference classes, as in the following example, in which an instance of System.IO.FileStream is declared by using C#:

System.IO.Filestream aFileStream; However, it is more convenient to reference the required namespaces in your program. Using the namespace effectively disposes of the need to qualify all class library references, as in the following example:

using System.IO; ... FileStream aFileStream; For example, in order to have convenient access to System objects, you must use the System namespace.

Topic Objective To describe how to use namespaces in the .NET Framework.

Lead-in You can fully reference classes in which an instance of System.IO.FileStream is declared by using C#:

Page 8: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

6 Module 2: Introduction to a Managed Execution Environment

Defining a Namespace and a Class

! C# Supports Creation of Custom Namespaces and Classes Within Those Namespaces

namespace CompCS {public class StringComponent {

...}

}

namespace CompCS {public class StringComponent {

...}

}

*****************************illegal for non-trainer use******************************

C# supports the creation of custom namespaces and classes within those namespaces.

The following is the general rule for naming namespaces: CompanyName.TechnologyName For example: Microsoft.Office This is merely a guideline. Third-party companies can choose other names.

Namespaces in C# In C#, you use the namespace statement to define a new namespace, which encapsulates the classes that you create, as in the following example:

namespace CompCS { public class StringComponent { ... } } Note that a namespace may be nested in other namespaces, and a single namespace may be defined in multiple files. A single source code file may also define multiple namespaces.

Topic Objective To describe how to define namespaces and classes in C#.

Lead-in C# supports the creation of custom namespaces and classes within those namespaces.

Tip

Page 9: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

Module 2: Introduction to a Managed Execution Environment 7

Entry Points, Scope, and Declarations

! In C#, the External Entry Point for a Program Is in a Class

! C# Supports the Use of a Period As a Scope Resolution Operator

! In C#, Objects Must Be Declared Before They Can Be Used and Are Instantiated Using the New Keyword

class MainApp { public static void Main()

{. . .}}

class MainApp { public static void Main()

{. . .}}

Console.WriteLine ("First String");Console.WriteLine ("First String");

Lib.Comp myComp = new Lib.Comp();Lib.Comp myComp = new Lib.Comp();

*****************************illegal for non-trainer use******************************

Every executable program must contain an external entry point, where the application begins its execution. In C#, all code must be contained in methods of a class.

Entry Points in C# To accommodate the entry point code in C#, you must first specify the class, as in the following example:

class MainApp {...} Next, you specify the entry point for your program. The compiler requires this entry point to be a public static method called Main, as in the following example:

public static void Main () {...}

Scope C# uses the period as a scope resolution operator. For example, you use the syntax Console.WriteLine when referencing the WriteLine method of the Console object.

Declaring and Instantiating Variables In C#, you must declare a variable before it can be used. To instantiate the object, use the new keyword. The following example in C# shows how to declare an object of type Comp, in namespace Lib, with the name myComp:

Lib.Comp myComp = new Lib.Comp();

Topic Objective To describe how to create program entry points in C#.

Lead-in Every executable program must contain an external entry point, where the application begins its execution.

Page 10: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

8 Module 2: Introduction to a Managed Execution Environment

Console Input and Output

! Console Class Methods

# Read, ReadLine, Write, and WriteLine

Console.WriteLine("Hello World using C#!");Console.WriteLine("Hello World using C#!");

*****************************illegal for non-trainer use******************************

You can use the common language runtime Console class of the System namespace for input and output to the console of any string or numeric value by using the Read, ReadLine, Write, and WriteLine methods.

The following example shows a C# program that outputs a string to the console:

using System; class MainApp { public static void Main() { // Write text to the console Console.WriteLine(�Hello World using C#!�); } }

Topic Objective To describe how to use Console class methods in C#.

Lead-in You can use the runtime Console class of the System namespace for input and output to the console of any string or numeric value by using the Read, ReadLine, Write, and WriteLine methods.

Page 11: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

Module 2: Introduction to a Managed Execution Environment 9

Case Sensitivity

! Do Not Use Names That Require Case Sensitivity

# Components should be fully usable from both case-sensitive and case-insensitive languages

# Case should not be used to distinguish between identifiers within a single name scope

! Avoid the Following

class customer {...}class Customer {...}

void foo(int X, int x)

class customer {...}class Customer {...}

void foo(int X, int x)

*****************************illegal for non-trainer use******************************

Microsoft Visual C++® and C# are case-sensitive, but Microsoft Visual Basic® is not case-sensitive. To ensure that a program is compliant with the Common Language Specification (CLS), however, you must take special care with public names. You cannot use case to distinguish between identifiers within a single name scope, such as types within assemblies and members within types.

The following examples show situations to avoid:

! Do not have two classes or namespaces whose names differ only by case. class customer { ... } class Customer { ... }

! Do not have a function with two parameters whose names differ only by case. void foo(int X, int x)

This constraint enables Visual Basic (and potentially other case-insensitive languages) to produce and use components that have been created in other case-sensitive languages. This constraint does not apply to your definitions of private classes, private methods on public classes, or local variables.

Topic Objective To describe case sensitivity issues in programming languages.

Lead-in C++ and C# are case-sensitive, but Visual Basic is not case-sensitive.

Page 12: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

10 Module 2: Introduction to a Managed Execution Environment

To fully interact with other objects regardless of the language they were implemented in, objects must expose to callers only those features that are common to all the languages they must interoperate with. For this reason, a set of language features has been defined, called the Common Language Specification (CLS), which includes common language features that are needed by many applications. The CLS rules define a subset of the common type system; that is, all the rules that apply to the common type system apply to the CLS, except where stricter rules are defined in the CLS. If your component uses only CLS features in the API that it exposes to other code (including derived classes), the component is guaranteed to be accessible from any programming language that supports the CLS. Components that adhere to the CLS rules and use only the features included in the CLS are said to be CLS-compliant components.

Note

Page 13: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

Module 2: Introduction to a Managed Execution Environment 11

"""" Compiling and Running a .NET Application

! Compiler Options! The Process of Managed Execution! Metadata! Microsoft Intermediate Language! Assemblies! Common Language Runtime Tools! Just-In-Time Compilation! Application Domains! Garbage Collection

*****************************illegal for non-trainer use******************************

Most aspects of programming in the .NET Framework are the same for all compatible languages; each supported language compiler produces self-describing, managed Microsoft intermediate language (MSIL) code. All managed code runs using the common language runtime, which provides cross-language integration, automatic memory management, cross-language exception handling, enhanced security, and a consistent and simplified programming model.

This section introduces basic concepts of a managed execution environment and presents new terminology. Many of these concepts are covered in greater detail in subsequent modules in this course, in subsequent courses, and in the .NET Framework SDK documentation.

Topic Objective To introduce the topics in the section.

Lead-in Most aspects of programming in the .NET Framework are the same for all compatible languages; each supported language compiler produces self-describing, managed Microsoft intermediate language (MSIL) code.

Delivery Tip Emphasize that you are primarily introducing new concepts and terminology. Be prepared to postpone answering questions that pertain to later modules. Encourage students to start reading the .NET Framework SDK documentation.

Key Points String literals in an application are stored and transported as clear text. Therefore, you should avoid putting sensitive information such as passwords in string literals.

Page 14: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

12 Module 2: Introduction to a Managed Execution Environment

Compiler Options

! Compile Directly from a Command Prompt Window

! Use /t to indicate target

! Use /reference to reference assemblies

>csc HelloDemoCS.cs>csc HelloDemoCS.cs

>csc /t:exe HelloDemoCS.cs>csc /t:exe HelloDemoCS.cs

>csc /t:exe /reference:assemb1.dll HelloDemoCS.cs>csc /t:exe /reference:assemb1.dll HelloDemoCS.cs

*****************************illegal for non-trainer use******************************

The .NET Framework includes a command line compiler for C#. The file name of the compiler is Csc.exe.

Compiling in C# To compile the source code for the Hello World application presented in the Hello World demonstration at the beginning of this module, type the following:

csc HelloDemoCS.cs This syntax invokes the C# compiler. In this example, you only need to specify the name of the file to be compiled. The compiler generates the program executable, HelloDemoCS.exe.

Topic Objective To introduce compiler options in C#.

Lead-in The .NET Framework includes a command line compiler for C#.

Page 15: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

Module 2: Introduction to a Managed Execution Environment 13

Command Line Options In C#, you can obtain the complete list of command line options by using the /? switch as follows:

csc /? Common options include the /out switch, which specifies the name of the output file, and the /target switch, which specifies the target type. By default, the name of the output file is the name of the input file with an .exe extension. The default for the target type is an executable program.

The following example shows the use of both the /out and /t switches in C#:

csc /out:HelloDemoCS.exe /t:exe HelloDemoCS.cs The /t switch is equivalent to the /target switch.

For more information about compiler options, see the .NET Framework SDK documentation.

Using the /reference Compilation Option When referring to other assemblies, you must use the /reference compilation switch. The /reference compilation option allows the compiler to make information in the specified libraries available to the source that is currently being compiled.

The following example shows how to build an executable program from the command line by using the /reference compilation option.

csc /r:assemb1.dll,assemb2.dll /out:output.exe input.cs The /r switch is equivalent to the /reference compilation switch.

Page 16: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

14 Module 2: Introduction to a Managed Execution Environment

The Process of Managed Execution

Class LoaderClass LoaderClass Loader

JIT Compilerwith optionalverification

JIT CompilerJIT Compilerwith optionalwith optionalverificationverification

ExecutionExecution

Security ChecksSecurity Checks

EXE/DLL(MSIL and metadata)

EXE/DLL(MSIL and metadata)

ClassLibraries

(MSIL and metadata)

ClassLibraries

(MSIL and metadata)

Trusted,pre-JITedcode only

Call to anuncompiled

method

Runtime Engine

ManagedNative Code

CompilerCompiler SourceCode

SourceCode

*****************************illegal for non-trainer use******************************

In the .NET Framework, the common language runtime provides the infrastructure for a managed execution environment. This topic introduces fundamental concepts of compiling and executing code in a managed execution environment and identifies new terminology.

Compiling Source Code When you develop an application in the .NET Framework, you can write the source code in any programming language as long as the compiler that you use to compile the code targets the common language runtime. Compilation of the source code produces a managed module. The managed module is contained within a physical file also known as a portable executable (PE) file.

The file may contain the following items:

! Microsoft Intermediate Language (MSIL) The compiler translates the source code into MSIL, a CPU-independent set of instructions that can be efficiently converted to native code.

! Type Metadata This information fully describes types, members, and other references, and is used by the common language runtime at run time.

! A Set of Resources For example, .bmp or .jpg files.

Topic Objective To introduce fundamental concepts of compiling and executing code in a managed execution environment.

Lead-in In the .NET Framework, the common language runtime provides the infrastructure for a managed execution environment.

Page 17: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

Module 2: Introduction to a Managed Execution Environment 15

If the C# compiler�s target option is either exe or library, then the compiler produces a managed module that is an assembly. Assemblies are a fundamental part of programming with the .NET Framework. Assemblies are the fundamental units of sharing, deployment, security, and versioning in the common language runtime. The .NET common language runtime only executes MSIL code that is contained in an assembly.

If the C# compiler�s target option is module, then the compiler produces a managed module that is not an assembly, it does not contain a manifest and cannot be executed by the common language runtime. A managed module can be added to an assembly by the C# compiler, or by using the .NET�s Assembly Generation Tool, Al.exe.

Subsequent topics in this module cover MSIL, metadata, and assemblies in more detail.

Executing Code When a user executes a managed application, the operating system loader loads the common language runtime, which then begins executing the module�s managed MSIL code. Because current host CPUs cannot execute the MSIL instructions directly, the common language runtime must first convert the MSIL instructions into native code.

The common language runtime does not convert all of the module�s MSIL code into CPU instructions at load time. Instead, it converts the instructions when functions are called. The MSIL is compiled only when needed. The component of the common language runtime that performs this function is called the just-in-time (JIT) compiler. JIT compilation conserves memory and saves time during application initialization.

For more information about the JIT compiler, see Just-In-Time Compilation in this module.

Application Domain Operating systems and runtime environments typically provide some form of isolation between applications. This isolation is necessary to ensure that code running in one application cannot adversely affect other, unrelated applications.

Application domains provide a secure and versatile unit of processing that the common language runtime can use to provide isolation between applications. Application domains are typically created by runtime hosts, which are responsible for bootstrapping the common language runtime before an application is run.

Page 18: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

16 Module 2: Introduction to a Managed Execution Environment

Metadata

! Declarative Information Emitted at Compile Time

! Included with All .NET Framework Files and Assemblies

! Metadata Allows the Runtime to:

# Load and locate code

# Enforce code security

# Generate native code at runtime

# Provide reflection

*****************************illegal for non-trainer use******************************

Every compiler that targets the common language runtime is required to emit full metadata into every managed module. This topic explains how the common language runtime uses metadata.

Definition of Metadata Metadata is a set of data tables, which fully describe every element that is defined in a module. This information can include data types and members with their declarations and implementations, and references to other types and members.

Metadata provides the common language runtime with all the information that is required for software component interaction. It replaces older technologies, such as Interface Definition Language (IDL) files, type libraries, and external registration. Metadata is always embedded in the .exe or .dll file containing the MSIL code. Therefore, it is impossible to separate metadata from the MSIL code.

Topic Objective To explain how metadata is used in the common language runtime.

Lead-in Every compiler that targets the common language runtime is required to emit full metadata into every managed module.

Page 19: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

Module 2: Introduction to a Managed Execution Environment 17

Uses for Metadata Metadata has many uses, but the following uses are most important:

! Locating and loading classes Because metadata and MSIL are included in the same file, all type information in that file is available to the common language runtime at compile time. There is no need for header files because all types in a particular assembly are described by the assembly�s manifest.

! Enforcing security The metadata may or may not contain the permissions required for the code to run. The security system uses permissions to prevent code from accessing resources that it does not have authority to access.

Other uses for metadata include:

! Resolving method calls. ! Setting up runtime context boundaries. ! Providing reflection capability.

For more information about metadata, see �Metadata and Self-Describing Components� in the .NET Framework SDK documentation.

For more information about verification of type safety, see Module 4, �Deployment and Versioning,� in Course 2349B, Programming with the Microsoft .NET Framework (Microsoft Visual C#� .NET).

Page 20: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

18 Module 2: Introduction to a Managed Execution Environment

Microsoft Intermediate Language

! Produced by Each Supported Language Compiler

! Converted to Native Language by the Common Language Runtime's JIT Compilers

*****************************illegal for non-trainer use******************************

Microsoft intermediate language (MSIL), sometimes called managed code, is the set of instructions that the compiler produces as it compiles source code. This topic explains MSIL and the general process for converting MSIL to native code.

Compiled MSIL Regardless of their logical arrangement, most assemblies contain code in the form of MSIL. MSIL is a CPU-independent machine language created by Microsoft in consultation with third-party compiler vendors. However, MSIL is a much higher-level language than most CPU machine languages.

MSIL contains instructions for many common operations, including instructions for creating and initializing objects, and for calling methods on objects. In addition, it includes instructions for arithmetic and logical operations, control flow, direct memory access, and exception handling.

Conversion to Native Code Before MSIL code can be executed, it must be converted to CPU-specific or native code by a JIT compiler. The common language runtime provides an architecture-specific JIT compiler for each CPU architecture. These architecture-specific JIT compilers allow you to write managed code that can be JIT compiled and executed on any supported architecture.

Any managed code that calls platform-specific native APIs or libraries can only run on a specific operating system.

For more information about MSIL, see the .NET Framework SDK documentation.

Topic Objective To introduce MSIL and JIT compilation.

Lead-in Microsoft intermediate language, sometimes called managed code, is the set of instructions that the compiler produces as it compiles source code.

Note

Page 21: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

Module 2: Introduction to a Managed Execution Environment 19

Assemblies

AssemblyAssembly

ManifestManifest

Multiple Managed Modules andResource FilesAre Compiled to Produce an Assembly

Managed Module(MSIL and Metadata)Managed Module

(MSIL and Metadata)

Managed Module(MSIL and Metadata)Managed Module

(MSIL and Metadata)

.html

.gif

Resource Files

*****************************illegal for non-trainer use******************************

The common language runtime uses an assembly as the functional unit of sharing and reuse.

Definition of an Assembly An assembly is a unit of class deployment, analogous to a logical .dll. Each assembly consists of all the physical files that make up the functional unit: any managed modules, and resource or data files.

Conceptually, assemblies provide a way to consider a group of files as a single entity. You must use assemblies to build an application, but you can choose how to package those assemblies for deployment.

An assembly provides the common language runtime with the information that it needs to understand types and their implementations. As such, an assembly is used to locate and bind to referenced types at run time.

Topic Objective This topic introduces the concept of an assembly and the role of the assembly manifest.

Lead-in The common language runtime uses an assembly as the functional unit of sharing and reuse.

Page 22: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

20 Module 2: Introduction to a Managed Execution Environment

The Assembly Manifest An assembly contains a block of data known as a manifest, which is a table in which each entry is the name of a file that is part of the assembly. The manifest includes the metadata that is needed to specify the version requirements, security identity, and the information that is used to define the scope of the assembly and resolve references to resources and classes. Because the metadata makes an assembly self-describing, the common language runtime has the information it requires for each assembly to execute.

All applications that are executed by the common language runtime must be composed of an assembly or assemblies. All files that make up an assembly must be listed in the assembly�s manifest. The manifest can be stored in single-file assemblies or multi-file assemblies:

! Single-file assemblies When an assembly has only one associated file, the manifest is integrated into a single PE file.

! Multi-file assemblies When an assembly has more than one associated file, the manifest can be a standalone file, or it can be incorporated into one of the PE files in the assembly.

For more information about assemblies, see �Assemblies� in the .NET Framework SDK documentation.

Page 23: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

Module 2: Introduction to a Managed Execution Environment 21

Common Language Runtime Tools

! Runtime Utilities for Working with MSIL

# MSIL Assembler (ilasm.exe) produces a final executable binary

# MSIL Disassembler (ildasm.exe) inspects metadata and code of a managed binary

*****************************illegal for non-trainer use******************************

The common language runtime provides two tools that you can use to test and debug MSIL code.

! The MSIL Assembler The MSIL Assembler (Ilasm.exe) takes MSIL as text input and generates a PE file, which contains the binary representation of the MSIL code and required metadata. The basic syntax is as follows:

ilasm [options] filename [options]

! The MSIL Disassembler You can use the MSIL Disassembler (Ildasm.exe) to examine the metadata and disassembled code of any managed module. You will use this tool to examine MSIL code in Lab 2, Building a Simple .NET Application.

Topic Objective This topic describes how the MSIL Assembler and MSIL Disassembler work.

Lead-in The common language runtime provides two tools that you can use together to test and debug MSIL code.

Page 24: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

22 Module 2: Introduction to a Managed Execution Environment

Demonstration: Using the MSIL Disassembler

*****************************illegal for non-trainer use******************************

This demonstration shows how to use the MSIL Disassembler to view an assembly�s metadata.

Viewing Assembly Metadata by Using the MSIL Disassembler In the following procedures, you will see how to use the MSIL Disassembler (Ildasm.exe) to view the contents of the HelloDemoCS.exe assembly.

! To run the MSIL Disassembler on the HelloDemoCS.exe assembly • At a Visual Studio .NET Command Prompt window, change the directory to

<install folder>\Democode\Mod02 where the sample file HelloDemoCS.exe has been copied, and type the following command: ildasm HelloDemoCS.exe

Topic Objective To demonstrate how the MSIL Disassembler works.

Lead-in This demonstration shows how to use the MSIL Disassembler to view an assembly�s metadata.

Page 25: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

Module 2: Introduction to a Managed Execution Environment 23

After you expand the MainApp icon, the MSIL Disassembler graphical user interface (GUI) displays information about the file HelloDemoCS.exe, as shown in the following illustration:

! To display the contents of the manifest 1. Double-click MANIFEST.

The MANIFEST window appears, as follows:

2. Close the Manifest window, and then close ILDASM.

Page 26: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

24 Module 2: Introduction to a Managed Execution Environment

Just-In-Time Compilation

! Process for Code Execution

# MSIL converted to native code as needed

# Resulting native code stored for subsequent calls

# JIT compiler supplies the CPU-specific conversion

*****************************illegal for non-trainer use******************************

As previously stated in this module, MSIL code must be converted into native code before it can execute. Because an intermediate step is involved, the common language runtime optimizes the compilation process for efficiency.

The Code Execution Process The common language runtime compiles MSIL as needed. This just-in-time, or JIT, compiling saves time and memory. The basic process is as follows:

1. When the common language runtime loads a class type, it attaches stub code to each method.

2. For subsequent method calls, the stub directs program execution to the common language runtime component that is responsible for compiling a method�s MSIL into native code. This component of the common language runtime is frequently referred to as the JIT compiler.

3. The JIT compiler compiles the MSIL and the method�s stub is substituted with the address of the compiled code. Future calls to that method will not involve the JIT compiler because the compiled native code will simply execute.

Topic Objective To describe JIT compilation and introduce JIT compiler options.

Lead-in MSIL code must be converted into native code before it can execute. Because an intermediate step is involved, the common language runtime optimizes the compilation process for efficiency.

Page 27: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

Module 2: Introduction to a Managed Execution Environment 25

Application Domains

! Historically, Process Boundaries Used to Isolate Applications

! In the Common Language Runtime, Application Domains Provide Isolation Between Applications

# The ability to verify code as type-safe enables isolation at a much lower performance cost

# Several application domains can run in a single process

! Faults in One Application Cannot Affect Other Applications

*****************************illegal for non-trainer use******************************

Historically, process boundaries have been used to isolate applications running on the same computer. Each application is loaded into a separate process, which isolates the application from other applications running on the same computer.

The applications are isolated because memory addresses are process-relative; a memory pointer passed from one process to another cannot be used in any meaningful way in the target process. In addition, you cannot make direct calls between two processes. Instead, you must use proxies, which provide a level of indirection.

Managed code must be passed through a verification process before it can be run (unless the administrator has granted permission to skip the verification). The verification process determines whether the code can attempt to access invalid memory addresses or perform some other action that could cause the process in which it is running to fail to operate properly.

Code that passes the verification test is said to be type-safe. The ability to verify code as type-safe enables the common language runtime to provide as great a level of isolation as the process boundary, at a much lower performance cost.

Application domains provide a secure and versatile unit of processing that the common language runtime can use to provide isolation between applications. You can run several application domains in a single process with the same level of isolation that would exist in separate processes, but without incurring the additional overhead of making cross-process calls or switching between processes. The ability to run multiple applications within a single process dramatically increases server scalability.

Topic Objective To describe how application domains provide application isolation.

Lead-in Historically, process boundaries have been used to isolate applications running on the same computer.

Page 28: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

26 Module 2: Introduction to a Managed Execution Environment

Isolating applications is also important for application security. For example, you can run controls from several Web applications in a single browser process in such a way that the controls cannot access each other's data and resources.

The isolation provided by application domains has the following benefits:

! Faults in one application cannot affect other applications. Because type-safe code cannot cause memory faults, using application domains ensures that code running in one domain cannot affect other applications in the process.

! Individual applications can be stopped without stopping the entire process. Using application domains enables you to unload the code running in a single application.

You cannot unload individual assemblies or types. Only a complete domain can be unloaded.

Code running in one application cannot directly access code or resources from another application. The common language runtime enforces this isolation by preventing direct calls between objects in different application domains. Objects that pass between domains are either copied or accessed by proxy. If the object is copied, the call to the object is local. That is, both the caller and the object being referenced are in the same application domain. If the object is accessed through a proxy, the call to the object is remote. In this case, the caller and the object being referenced are in different application domains. Cross-domain calls use the same remote call infrastructure as calls between two processes or between two computers.

Note

Page 29: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

Module 2: Introduction to a Managed Execution Environment 27

Multimedia: Application Loading and Single-File Assembly Execution

*****************************illegal for non-trainer use******************************

Applications that are implemented by using MSIL code require the common language runtime to be installed on the user�s computer in order to run. The common language runtime manages the execution of code. For example, when an application that is implemented as a single-file private assembly is run, the following tasks are performed:

! The Microsoft Windows® loader loads the PE file. The PE file contains a call to a function found in the file MSCorEE.dll.

! Windows loads the file MSCorEE.dll and transfers control to it to initialize the common language runtime.

! The common language runtime parses the metadata of the application assembly, and then the JIT compiler compiles the code.

! The common language runtime then locates the PE file�s managed entry-point (the Main method in the case of a C# program), and transfers control to this entry point.

If the application calls a private assembly:

! The common language runtime uses probing to locate the referenced assembly, beginning in the application�s root directory and then traversing the subfolders until the assembly is located.

• If the assembly is not found, a TypeLoadException error occurs.

• If the assembly is found, it is loaded by the common language runtime.

The common language runtime loader parses the manifest in the referenced assembly. The JIT compiler then compiles the required code in the assembly and passes control to the called function.

Topic Objective To describe how assembly code is executed.

Lead-in In this demonstration, you will see how a single-file private assembly is loaded and executed.

Delivery Tip To start the animation, click the button in the lower-left corner of the slide. The animation plays automatically. To pause or rewind the animation, click the controls in the lower-left of the screen.

Page 30: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

28 Module 2: Introduction to a Managed Execution Environment

Garbage Collection

! Garbage Collection Provides Automatic Object Memory Management in the .NET Framework

! You No Longer Need to Track and Free Object Memory

*****************************illegal for non-trainer use******************************

This topic introduces memory management in the .NET Framework.

For more information about memory and resource management, see Module 9, �Memory and Resource Management,� in Course 2349B, Programming with the Microsoft .NET Framework (Microsoft Visual C# .NET).

Current Memory Management Model When you create an object programmatically, you generally follow these steps:

1. Allocate memory for the object 2. Initialize the memory 3. Use the object 4. Perform cleanup on the object 5. Free the object�s memory

If you forget to free memory when it is no longer required or try to use memory after it has been freed, you can generate programming errors. The tracking and correction of such errors are complicated tasks because the consequences of the errors are unpredictable.

Memory Management in the .NET Framework The common language runtime uses a heap called the managed heap to allocate memory for all objects. This managed heap is similar to a C-Runtime heap, however you never free objects from the managed heap. In the common language runtime, garbage collection is used to manage memory deallocation. The garbage collection process frees objects when they are no longer needed by the application.

For more information about garbage collection, see Module 9, �Memory and Resource Management,� in Course 2349B, Programming with the Microsoft

.NET Framework (Microsoft Visual C# .NET).

Topic Objective To introduce memory and resource management in the .NET Framework.

Lead-in Every program uses resources, such as files, screen space, network connections, and database resources.

Page 31: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

Module 2: Introduction to a Managed Execution Environment 29

Lab 2: Building a Simple .NET Application

*****************************illegal for non-trainer use******************************

Objectives After completing this lab, you will be able to:

! Write, compile, and run a simple application in C#. ! Use the MSIL Disassembler to examine an assembly.

Lab Setup Only solution files are associated with this lab. The solution files for this lab are in the folder <install folder>\Labs\Lab02\Solution.

Estimated time to complete this lab: 20 minutes

Topic Objective To introduce the lab.

Lead-in In this lab, you will learn how to write, compile, and run a simple application in C# and how to use the MSIL Disassembler to examine an assembly.

Page 32: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

30 Module 2: Introduction to a Managed Execution Environment

Exercise 1 Creating the Program in C#

In this exercise, you will create the source code for a small console application that takes user input and writes a string to the console by using C#. The lab uses the classic Hello World application to allow you to focus on basic concepts in a managed execution environment.

To help you concentrate on the syntactical aspects of this lab, you will use Notepad to create and edit the source files. From a command prompt window, you will then compile the application and test the resulting executable program.

! Write the source code 1. Open Notepad and create a class in C# called MainApp. 2. Import the System namespace. 3. Define the program entry point.

The entry point takes no arguments and does not return a value. 4. Create methods that accomplish the following:

a. Print the following text to the console: �Type your name and press Enter�.

b. Read in the resulting user input. c. Print the text �Hello� and append to the text the value that was read in.

5. Save the file as HelloLabCS.cs in the <install folder>\Labs\Lab02 folder.

! Build and test the program

To use Microsoft Visual Studio .NET tools within a command prompt window, the command prompt window must have the proper environment settings. The Visual Studio .NET Command Prompt window provides such an environment. To run a Visual Studio .NET Command Prompt window, click Start, All Programs, Microsoft Visual Studio .NET, Visual Studio .NET Tools, and Visual Studio .NET Command Prompt.

1. From a Visual Studio .NET Command Prompt window, type the syntax to build an executable program from HelloLabCS.cs.

2. Run the resulting executable program. Your C# program should generate the following output: Type your name and press Enter When you press ENTER, the program outputs the text �Hello � and whatever text you typed as input.

Important

Page 33: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

Module 2: Introduction to a Managed Execution Environment 31

Exercise 2 Using the MSIL Disassembler

In this exercise, you will use the MSIL Disassembler to open a single assembly and familiarize yourself with the assembly manifest.

In subsequent labs, you will explore assemblies in greater detail.

! Examine the metadata for the Hello World applications 1. Open a Visual Studio .NET Command Prompt window. 2. From the Visual Studio .NET Command Prompt window, type:

>ildasm /source

3. Open HelloLabCS.exe and double-click Manifest. 4. Note the following:

a. The externally referenced library named mscorlib b. The assembly name HelloLabCS c. Version information (for the HelloLabCS assembly and mscorlib)

5. Close the Manifest window, double-click MainApp, double-click Main, and view the MSIL and source code.

Page 34: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

32 Module 2: Introduction to a Managed Execution Environment

Review

! Writing a .NET Application

! Compiling and Running a .NET Application

*****************************illegal for non-trainer use******************************

1. Name the root namespace for types in the .NET Framework. The System namespace is the root namespace for types in the .NET Framework.

2. What class and methods can your application use to input and output to the console? You can use the common language runtime�s Console class of the System namespace for input and output to the console of any string or numeric value by using the Read, ReadLine, Write, and WriteLine methods.

3. When compiling code that makes references to classes in assemblies other than mscorlib.dll what must you do? You must use the /reference compilation switch. The /reference compilation option allows the compiler to make information in the specified libraries available to the source that is currently being compiled. The /r switch is equivalent to /reference.

4. What is the code produced by a .NET compiler called? Microsoft intermediate language (MSIL), sometimes called managed code.

Topic Objective To reinforce module objectives by reviewing key points.

Lead-in The review questions cover some of the key concepts taught in the module.

Page 35: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

Module 2: Introduction to a Managed Execution Environment 33

5. What .NET component compiles MSIL into CPU specific native code? The just-in-time (JIT) compiler.

6. What feature of .NET ensures that object memory is freed? The garbage collection process.

Page 36: Module 2: Introduction to a Managed Execution Environmentganesans.weebly.com/uploads/2/2/8/9/228926/course-2349-module-2.pdf · Lab 2: Building a Simple .NET Application 29 Review

THIS PAGE INTENTIONALLY LEFT BLANK


Recommended