152
98-372 Microsoft .NET Fundamentals

98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Embed Size (px)

Citation preview

Page 1: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

98-372 Microsoft .NET Fundamentals

Page 2: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

1.1 Understand Basic Application Settings

Page 3: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Application Settings

• Make it easy to create, store, and maintain custom application and user preferences on the client computer.• Useful for important data that you don’t want to include in the

application’s code. Examples include:• Database connection strings• User preferences, such as a color scheme, font sizes, etc.

• Individual settings can be “scoped” as Application settings or User settings

Page 4: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

.config Files

• Generally, Application Settings are stored in .config files:• App.config for Windows Forms, WPF, and other desktop

applications• Web.config for ASP.NET web applications

• Settings that are specific to individual users (“user-scoped”) are stored in a file named user.config, where ‘user’ is the user name of the person currently running the application.

Page 5: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Lesson Review

• List 3 reasons why developers use application settings?

Page 6: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

1.2 Events and Events Handling in the .NET

framework

Page 7: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Event-driven Programming

• Event-driven programming is a model or paradigm in which the flow of program execution is determined by events.• Often, these events are forms of user input (such as mouse clicks,

key presses, or touch-screen interactions).• An event is like a signal to another part of the application.

• A simple example is a Save button on a Microsoft Windows form. • When the user clicks the button, that causes a “signal” to be sent

to code that saves the current data.

Page 8: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Events

• Events are actions that occur in a program that the developer can respond to, or handle, in code.

• When an event occurs, we say that it has been “raised.”

• In addition to mouse clicks, what are some other events in .NET applications?

Page 9: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Event Handlers

• Event handlers are methods or procedures that are invoked when the corresponding event is raised.

• In addition to the terms “raised” and “handled,” developers may also use the terms “publish” and “subscribe.”• A class can publish an event, and another class can subscribe to

that event.

Page 10: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Delegates

• Delegates are objects that refer to methods.

• In political diplomacy, a delegate is a person authorized to represent another (a person or an organization), such as when a government sends delegates to represent the country at the Olympics. Likewise, a delegate in this case stands in for, or represents, a method.

• .NET applications use delegates to connect events to event handlers.

Page 11: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Lesson Review

• Explain the event-driven programming model, including the roles of events and event handlers.

Page 12: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

1.3 Exception Handling

Page 13: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Types of Errors

• Syntax errors occur when code does not meet the rules (or “syntax”) of the programming language in use. • For example, using incorrect case (such as ‘If’ in C# code) is a

syntax error.• Syntax errors occur at compile time. An application cannot compile

—and therefore cannot run—if the code contains syntax errors.

Page 14: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

• Logic errors occur when code executes but does not behave in the intended manner. Consider the following if statement:

if (x < 0 && x > 10)This code follows C# syntax, and it will not crash the application. However, it is not likely to be what the developer intended.• Logic errors are often simply called bugs.

• Exceptions occur when something unexpected happens that disrupts the flow of the application.

Page 15: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Exceptions

• An exception is an event that is raised when a method encounters a condition that prevents it from executing.

• Often, this is due to invalid data.

• Exceptions that are not handled will cause the application to terminate

Page 16: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Common types of Exceptions

• There are many different types of exceptions. Commonly encountered exceptions include:• A DivideByZeroException

• Occurs when there is an attempt to divide a value by zero, as shown in the Anticipatory Set.

• A FileNotFoundException • Occurs when an attempt to access a file that does not exist on disk

fails. This would happen if the code refers to an incorrect file name or path, or the file does not exist.

Page 17: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Handling Exceptions

• Structured exception handling allows the developer to address potential exceptions so that the application doesn’t terminate, or at least it allows for a graceful termination of the application.• Exception handling uses the try, catch, and finally keywords

(in Visual Basic: Try, Catch, and Finally) to attempt actions that may not succeed, to handle failures, and to clean up resources afterwards.

For example, the code from the Anticipatory Set in the presentation throws a DivideByZeroException.

Page 18: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

try• The try (or Try) keyword is used to indicate that a block of code

should be monitored for exceptions.• You can think of it as giving a warning to the application that there

may be trouble ahead—so watch out!

catch• The catch (or Catch) keyword is used to designate a block of code

used to handle an exception if one is thrown.• You can use multiple catch blocks to handle different types of

exceptions.

Page 19: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Example of try/catch Bloacks

int SafeDivision(int x, int y)

{

try

{

return (x / y);

}

catch (System.DivideByZeroException dbz)

{

System.Console.WriteLine("Division by zero!");

return 0;

}

}

Page 20: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

finally

• The code in a finally (or Finally) block always executes last, just before the error-handling block loses scope, regardless of whether the code in the catch blocks has executed.

• finally blocks are not mandatory in structured exception handling, but they provide a great place for cleanup code (such as code for storing important data, closing files, etc).

Page 21: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Lesson Review

• List three basic types of errors.

• What are exceptions?

• What keywords are used to handle exceptions in applications?

Page 22: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

2.1 Understand .NET Class Hierarchies

Page 23: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Assemblies

• An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality.

• Each time you create a .NET application, you are creating an assembly. • There are other types of assemblies as well, such as class libraries.

Page 24: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Namespaces

Namespaces are organizational units used for two purposes:

1. To organize the many classes within the .NET Framework

2. To help control scope and avoid name collisions (having two classes with the same name)

Page 25: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Namespace Example

• The Button type commonly used in Forms applications is nested within several namespaces:

• The fully qualified name for the Button class is System.Windows.Forms.Button.

System Namespace

Windows Namespace

Forms Namespace

Button Class

Page 26: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Using and Imports Statements

• Because using fully qualified names can be cumbersome (as with the Button example), .NET languages provide a way to shorten references.• In Microsoft C#, this is done by adding using statements at the top

of your code.• Microsoft Visual Basic uses the Imports statement.• These statements allow developers to refer to Button rather than System.Windows.Forms.Button.

Page 27: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Object Class

• All classes in the .NET Framework are ultimately derived from a class called Object. • In other words, all classes in the .NET Framework—and all classes

you define in your applications—inherit from Object, either directly or indirectly.

• The Object class includes a small number of methods that are often overridden but derived classes, such as Equals(Object), ToString(), and Finalize().

Page 28: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

System Namespaces

• The System namespace contains fundamental classes and base classes that define commonly used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.• These classes and their members provide a foundation of classes,

types, and methods for creating applications. This extensive library is one of the primary strengths of developing with the .NET Framework.

Page 29: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Lesson Review

1. What are assemblies?

2. Why does the .NET Framework use namespaces?

Page 30: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

2.2 Object-Oriented Concepts in the .NET

Framework

Page 31: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Object-oriented programming(OOP)

• OOP is a programming paradigm or model in which classes and objects work together to create a program or application.

• It enables developers to think about a problem in a way that is similar to how we look at the real world—many objects that interact with each other.

• The fundamental building blocks of object-oriented programs are classes and objects.

Page 32: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Classes and Objects

• Classes are like blueprints or recipes for objects. • You can create multiple houses from one blueprint and multiple

batches of cookies from one recipe.• Each house (or each batch of cookies) is referred to as an instance.

• Classes and objects are not the same thing; a class is not an object, just as a recipe is not a batch of cookies.

Page 33: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Inheritance

• Inheritance is a technique in which a class inherits the attributes and behaviors of another class.• Allows the developer to reuse, extend, and modify an existing class.Example:• The Aircraft class might define the basic characteristics and behaviors

of a flying vehicle. Methods in that class might include Fly(), TakeOff(), and Land().• The Helicopter class could add a method called Hover(), which might

replace or “override” the TakeOff() method so that takeoffs are vertical.

Page 34: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

• The class whose members are inherited is called the base class.

• The class that inherits those members is called the derived class. • In our previous example, Aircraft is the base class; Helicopter is the

derived class.• Some developers refer to a base class as a superclass or a parent

class; a derived class could then be called a subclass or a child class.• We can test the validity of an inheritance relationship with the so-

called “Is-A” test. “A helicopter is an aircraft,” so that is an appropriate use of inheritance.• However, the Car class should not inherit from Aircraft because “a

car is an aircraft” doesn’t make sense

Page 35: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Inheritance in .NET Languages

• In Microsoft C#, inheritance is established using the colon (:)public class Helicopter : Aircraft {}

• In Microsoft Visual Basic, inheritance is indicated with the Inherits keyword:Public Class Helicopter Inherits AircraftEnd Class

Page 36: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Polymorphism

• Polymorphism is a language feature that allows a derived class to be used interchangeably with its base class.• In our example, a Helicopter can be treated like an Aircraft when

the developer writes code. If you developed a JumboJet class, it could also be used like an Aircraft.

• Polymorphism is especially useful when working with collections, such as lists or arrays. A collection of Aircraft could be populated with Helicopter instances and JumboJet instances, making the code much more flexible.

Page 37: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Interfaces

• An interface defines a set of properties, methods, and events, but it does not provide any implementation.• It is essentially a contract that dictates how any class implementing

the interface must be implemented.• Consider a power outlet in the wall, which is similar to an interface.

It dictates that any appliance that wants to use that power must follow some basic rules: how many prongs are required, the shape and spacing of those prongs, and so on.

• An object cannot be instantiated (“constructed”) from an interface.

Page 38: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Lesson Review

1. Explain the relationship between a base class and a derived class.

2. Why do developers use polymorphism?

3. How is an interface like a contract?

Page 39: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

2.3 Understand .NET Namespaces

Page 40: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Namespaces

• Namespaces are organizational units used for two purposes:• To organize the many classes within the .NET Framework• To help control scope and avoid name collisions

Page 41: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Name Collisions

• Sometimes a developer of a class library will encounter difficulties caused by the use of similar names in another library. • For example, a developer writing a library for handling game pad

input might have several classes and methods related to the gamepad buttons; however, the name Button is already used for buttons on Microsoft Windows forms.

• This type of conflict is called a name collision.• Namespaces avoid name collisions by allowing the developer to use a

fully qualified name to reference a class.

Page 42: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Namespace Example

• The Button type commonly used in Forms applications is nested within several namespaces:

• The fully qualified name for the Button class is System.Windows.Forms.Button.

System Namespace

Windows Namespace

Forms Namespace

Button Class

Page 43: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Fully Qualified Names

• Fully qualified names are object references that are prefixed with the name of the namespace in which the object is defined.

o In our previous example, the gamepad developer can create a class called Button; if he or she wishes to use a Forms button as well, he can use the following fully qualified name when referencing that particular button control:

System.Windows.Forms.Buttono This ensures that the compiler will use the Button control

rather than the class that the developer implemented.

Page 44: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Using/Imports Directives

• Because using fully qualified names can be cumbersome (as with the Button example), .NET languages provide a way to shorten references.• In C#, this is accomplished by adding using directives at the top of

your code.• In Visual Basic, it is accomplished using the Imports directive.• So long as there are no name collisions, these strategies allow

developers to refer to ListBox, rather than System.Windows.Forms.Listbox.

Page 45: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Namespaces in .NET Applications

• When you create a new project in Visual Studio, it automatically defines a new namespace with the same name as your project.• By default, all classes that you add to the project within Visual Studio will use this

default namespace. However, you can easily define your own namespace using the namespace (C#) or Namespace (Visual Basic) keyword.• In C#:namespace MyNewNamespace{}

• In Visual Basic:Namespace MyNewNamespaceEnd Namespace

Page 46: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Lesson Review

• What is fully Qualified namespace?

• What is the fully Qualified namespace for Button Class ?

Page 47: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

2.4 Understand and Create Class Libraries

Page 48: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Reusing Classes

• Often, a class developed for one application may be useful in another application.• For example, if a developer creates a class with methods for

calculating shipping costs for an internal inventory system, that class may be helpful when developing a retail website where the customer may want to know shipping costs.

• If you rewrite the code—or copy it to the second project—you have maintainability concerns.• If you fix a bug or make any improvement in one of the projects,

you have to make the same change in the other.• To avoid this problem, developers often use class libraries

Page 49: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Class Library

• A class library is a collection of classes (and related code) that is packaged for reuse.• Unlike an application, typically packaged as an executable (.exe) file, a

class library project creates a dynamic-link library (.dll) file.• There are several key advantages of class libraries:

• DLLs are easy to distribute and easy to replace when making software revisions.

• A DLL can be used by developers in many different programming languages regardless of the language used for creating the class library.

Page 50: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Lesson Review

• What is the DLL ?

• What is the use of Class library?

Page 51: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

2.5 Data Types in the .NET Framework

Page 52: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Data Types

• Data types are classifications that determine how data is stored and what operations can be performed on the data.• Data types apply to all values that can be stored in computer memory

or participate in the evaluation of an expression. • Every variable, literal, constant, enumeration, property, procedure

parameter, procedure argument, and procedure return value has a data type.

• A variable is defined by specifying an identifier (i.e., the name of the variable) and its data type

Page 53: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Data Type Categories

• Data types can be either built-in or user-defined.• Programming languages provide built-in support for many

commonly used data types. Examples include int/Integer, double/Double, char/Char, and bool/Boolean.

• Data types also can refer to user-defined data types, such as classes and interfaces.

• More important, data types are either value types or reference types

Page 54: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Value Type VS Reference Types

• Value types directly store a value.

• Value types are like a pocket holding coins—the money itself is stored in the pocket.

• Examples: all numeric types (byte, int, double, decimal, etc.) as well as bool, char, and all structures.

Page 55: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

• Reference types do not store a value; they contain a pointer (or “reference”) to a memory container where the actual value is stored.

o Reference types are like a check—it is not actual money but a reference to the bank account where the money is stored.

o Examples: String, all arrays, and all Class types (such as Button and TextBox

• The difference between value types and reference types may seem subtle, but it can have important implications

Page 56: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Arrays

• Generally, use square brackets to specify the index of an individual member of the array.

rosterNames[5]o The number is an integer that starts with 0 for the first entry in the

array.• Limitation:

o The size of an array cannot be changed after the array is created.

Page 57: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Collections in the .NET framework

• The .NET Framework provides specialized classes for storing and retrieving “collections” of related or similar data.• Example: the roster for a class of students. To store their names,

you could make many String variables; however, a collection would allow you to keep all the names in one object.

• Most of the collection classes in the .NET Framework implement the same interfaces (from the System.Collections namespace).

Page 58: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Lesson Review

• What is the use of “Collections” in .net framework?

Page 59: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

2.6 Understand Generics

Page 60: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Generics

• Generics are types that let you tailor a method, class, structure, or interface to the precise data type it acts upon.• Although generics have other uses, they are used most commonly in

collections.• In collections, using generics eliminates the need to cast objects

prior to processing or using them.• In short, a generic type is a type that uses generic type parameters

Page 61: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Need for Generics

• Collection classes such as ArrayList are untyped, meaning that they can contain any object derived from System.Object—which is to say, almost anything.• However, the flexibility of an untyped collection is offset by a big

limitation: The contents of the collection must be cast to the type that you wish to use. • Developers then have to take steps to ensure that only the correct

objects get stored in the object; even then, it may be cumbersome to use the objects in the collection.

• Generics allow developers to specify types when objects are created.

Page 62: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Generic Type Parameters

• A generic type parameter is the placeholder or template that a generic type uses.• Generic type parameters are specified with angle brackets ( < >)• We will look at the List class, which is the generic equivalent ArrayList. To declare a List object, use a generic type parameter as follows: List<String> myListOfStrings;• In this example, the generic type parameter indicates that the

collection will store String objects.

Page 63: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Using Generics

List<String> myList = new List<String>();

myList.Add(“Microsoft");myList.Add(“Visual");myList.Add(“Studio");

Page 64: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

3.1 fundamentals of MSIL and CLI

Page 65: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

MSIL

• When Microsoft Visual Studio compiles (or “builds”) source code written in one of the .NET languages, that code is first converted into MSIL.• MSIL is a CPU-independent set of instructions that can be converted

efficiently to native code.• By default, this MSIL code is stored in a file format known as “portable

executable” or PE.• A PE file also includes metadata, such as information about all the

classes in your code.

Page 66: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

JIT Compiler

• The MSIL code generated when a project is built cannot run by itself—it in turn must be compiled into native code for the target machine architecture. • This last compilation step is handled by a JIT compiler.

• It is called “just in time” because it compiles the code during program execution.

• The JIT compiler does not compile the entire application; rather, it compiles the code it needs as it runs and saves the resulting native code in memory so that it is available for additional calls.

Page 67: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

• JIT compilers are platform-specific and part of the .NET Framework.• A PE file will not execute on a machine that does not have the

appropriate .NET Framework installed—the MSIL can’t be converted to native code without it!

Page 68: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Lesson Review

1. List the steps that .NET code goes through as part of the execution process?

2. What is the function of MSIL?

3. What does the JIT compiler do?

Page 69: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

3.2 Understand the Use of Strong Naming

Page 70: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Strong Names

• The Microsoft .NET Framework provides the ability to create “strong names” for an assembly to provide a layer of security; they also provide a unique identity for an assembly, which helps prevent name collisions.• A strong name is a .NET assembly name plus a version number (and

other information) that uniquely identifies the assembly

Page 71: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Strong Name Security

• Strong names ensure that an assembly is authentic—that it has not been modified or replaced by an unauthorized party.• If assemblies are not secured, third parties (including people with

malicious intentions) could replace an assembly with one of their own creation and compromise the integrity and security of the application.

• Strong names work by using public key cryptography. • A public key can be used to verify that the assembly was created

by someone who had the corresponding private key.

Page 72: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Components of a Strong Name

In the .NET Framework, a strong name consists of five parts:1. A simple name—typically just the file name (without extension)2. The version number3. A public key4. (Optional) Culture information, such as “en-us” (English – United

States) or “fr” (France), for example5. (Optional) The target processor architecture

Page 73: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

GAC

• Each computer installed with the common language runtime has a machine-wide code cache called the Global Assembly Cache (GAC).• The GAC is a system folder, typically C:\Windows\assembly.

• The GAC stores assemblies specifically designated to be shared by several applications on the computer.• Share assemblies by installing them into the GAC only when

needed.

Page 74: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Advantages of Using the GAC

• Security• The system folder used for the GAC typically is protected by

administrator rights. When combined with strong naming, using the GAC makes sharing with it secure.

• Version management• Because multiple versions of an assembly can all be stored in the

GAC, applications built against older versions are still able to execute.

• Central location• The GAC provides a centralized location for all shared assemblies.

Page 75: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Lesson review

• Explain the purpose and components of a strongly named assembly

• What is the use of GAC?

Page 76: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

3.3-3.4 Understand Version Control ,

Assemblies, and Metadata

Page 77: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Versioning Basics

• Versioning of projects in the .NET Framework is done at the assembly level—that is, each assembly has its own version that is independent of other assemblies.• Each assembly has a version number as part of its identity. Two

otherwise identical assemblies with different version numbers are considered by the run time to be completely different assemblies. • By default, the common language runtime will run only applications

with the assembly versions they were built with; this policy can be overridden by the developer.

Page 78: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Version Number

• This version number is represented as a four-part string with the following format:

<major version>.<minor version>.<build number>.<revision>

• For example, version 1.5.1254.0 indicates 1 as the major version, 5 as the minor version, 1254 as the build number, and 0 as the revision number.

Page 79: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Version Number Components

• Major: Assemblies with the same name but different major versions are not interchangeable.

• Minor: If the name and major version number on two assemblies are the same, but the minor version number is different, this indicates significant enhancement with the intention of backward compatibility.

Page 80: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

• Build: A difference in build number represents a recompilation of the same source. Different build numbers might be used when the processor, platform, or compiler changes.

• Revision: Assemblies with the same name, major and minor version numbers, and different revisions are intended to be fully interchangeable. A higher revision number might be used in a build that fixes a security hole in a previously released assembly.

Page 81: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Metadata

• Metadata is defined as “data about data.” • Metadata provides a description (or other details) about a file or a set

of data.• Many web pages include metadata that provides information about

the page: its author, the authoring tool used to create the page, keywords about the content, and so on.• This information can be accessed and used for a variety of purposes,

such as cataloging the page for a search engine or optimizing the way that the page is displayed.

Page 82: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Assembly Metadata

• In the .NET Framework, every assembly contains a collection of data that describe how the elements in the assembly relate to each other.• This metadata is important for making assemblies usable across

languages, and it ensures that assemblies are “self-describing.”• An assembly’s metadata contains everything needed to interact

with another assembly or module. • Metadata enable the use of attributes, or user-defined metadata, that

give the developer more control over how an assembly behaves at run time.

Page 83: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Assembly Manifest

• Assembly metadata is stored in a PE file (or a portion of a PE file).• In the case of a single-file assembly, the manifest is contained in

the single file; if an assembly includes multiple files (such as resources), the compiler creates a separate manifest file.

• Used by the Just-In-Time (JIT) compiler when the application is executed.

• Stored as Extensible Markup Language (XML). View a manifest file using a standard text editor.

Page 84: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Assembly Manifest Components

• Assembly name and version number• Information about the culture or language the assembly supports• Strong name information (a public key)• List of all files in the assembly• Type reference information: Information used by the run time to map

a type reference to the file that contains its declaration and implementation• Information on referenced assemblies: A list of other assemblies that

are referenced statically by the assembly

Page 85: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Lesson Review

• Where does the .NET compile store assembly metadata? Give a few examples of the type of data that it stores.

Page 86: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

4.1 Understand .NET File Classes

Page 87: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

File Class

• The .NET Framework provides the File class for many of the basic tasks associated with file I/O.

o Methods in the File class are static, so they can be called without instantiating an object.

• Methods include:o Exist: Determines whether the specified file exists.o Move: Moves a specified file to a new location, providing the

option to specify a new file name. o Delete: Deletes the specified file.o Create: Creates a new (or overwrites an existing) specified file.

Page 88: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Streams

The .NET Framework uses streams for reading from and writing to files. Think of a stream as a set of data that has a beginning and an end, and in

which a cursor indicates the current position in the stream.

There are three fundamental stream operations:o Reading data from the streamo Writing data to the streamo Seeking (getting and/or setting the position of the cursor within the stream)

Beginning of file

End offile

Cursor

Page 89: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

FileStream Class

• There are many different types of streams, and many sources of data, such as memory, a Transmission Control Protocol/Internet Protocol (TCP/IP) socket, and so on. • The FileStream class (System.IO.FileStream) creates a

stream around a file, allowing the developer to read and write data.• Once a developer has created a stream, the StreamReader and StreamWriter classes provide methods for working with text files—a common task in application development.

Page 90: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

StreamReader Class

• The StreamReader class (System.IO.StreamReader) is designed to work with character (as opposed to byte) data.• It provides methods for reading a sequential series of characters and

is often used to read text files.• Once instantiated, a StreamReader object exposes several

methods for reading text. • Methods include:

• Read(), which returns the next character from the stream.• ReadLine(), which reads the next line and returns the data as a

string.

Page 91: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

StreamWriter Class

• The StreamWriter class (System.IO.StreamWriter) provides write functionality. Like StreamReader it is also intended to work with streams with character data.• Again, StreamWriter provides constructors for creating an

instance with a stream object or a file name.• Methods include:

• Write, for writing one character to a text stream.• WriteLine, which writes data plus a line terminator to the

stream.

Page 92: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Lesson Review

• What is the use of StreamWriter Class ?

• What is the use of StreamReader Class?

Page 93: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

4.2 Understand Console I/O

Page 94: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Console Applications

• The simplest type of application in the .NET Framework is a console application.• Console applications rely on text input and output at the

command line as a user interface.• A console application can be defined as a program that accesses three

basic data streams: standard input, standard output, and standard error data streams.

Page 95: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Console Output• Many programmers learn to use System.Console.WriteLine very

early, both as a way to make simple applications and as a debugging.• Console.Write and Console.WriteLine (with a variety of

overloads) write data to the standard output stream WriteLine adds a line terminator.• Example:

System.Console.Write(“Hello ”);System.Console.WriteLine(“World”);System.Console.WriteLine(“The End”);

Outputs the following:Hello WorldThe End

Page 96: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Console Input

• Console.Read retrieves and returns the next character entered.

• Console.ReadKey retrieves and returns data indicating the character or function key entered, including modifier keys used (such as SHIFT, ALT, CTRL).

• Console.ReadLine retrieves and returns (as a string) one line (a sequence of characters terminated by a line feed or line feed). Typically, the line is terminated when the user presses the ENTER key.

Page 97: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Lesson Review

• Explain how the Console class can be used to create a simple, text-based user interface.

Page 98: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

4.3 Understand XML Classes in the .NET

Framework

Page 99: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

XML

• XML is a markup language for formatting data in a document.• Like HTML for web pages, XML uses tags identified by angle

brackets: < > </ >

• Unlike HTML, XML does not specify how data should look; instead, it identifies how the data is structured. • An HTML document may specify that “Microsoft Word” will be

displayed in a large, bold font; an XML document might simply identify “Microsoft Word,” with no information about how to display it.

Page 100: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

XML Example

<?xml version="1.0" encoding="utf-8"?><ComputerSales> <Computer name="Desktop"> <ProcessorSpeed>2.0 GHz</ProcessorSpeed> <RAM>4 Gb</RAM> <HDD>500 Mb</HDD> </Computer> <Computer name="Laptop"> <ProcessorSpeed>1.8 GHz</ProcessorSpeed> <RAM>2 Gb</RAM> <HDD>250 Mb</HDD> </Computer></ComputerSales>

Page 101: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

XmlReader and XmlWriter Classes

• The .NET Framework includes these two classes (in the System.Xml namespace) for reading and writing XML.• Both classes are abstract, so you cannot create objects from them.

• The System.Xml namespace also includes XmlTextReader and XmlTextWriter, which can be instantiated and used to read and write XML data.

Page 102: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Reading XML

• To read XML, first create an instance of the XmlTextReader class. It has constructors that will accept a Stream, a file name, or a Uniform Resource Locator (URL).• The XmlTextReader.Read method reads the next node of the

XML. It returns a boolean indicating the success of the operation.• Use properties such as Name and Value to access information about

the current node

Page 103: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Writing XML

• Instantiating an XmlTextWriter object exposes methods that allow the developer to write well-formed XML.• Much of the process for creating the XML involves using method pairs

that write corresponding tag pairs:• WriteStartDocument and WriteEndDocument opens and

closes an XML document.• WriteStartElement and WriteEndElement delimit an

element, with the first method accepting strings to indicate the name and value of the element.

• WriteStartAttribute and WriteEndAttribute start and end attributes for the current element.

Page 104: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

XML Schema

• XML Schema is a technology that allows developers to specify the structure of an XML document, including data type information. • XML Schema can be defined in an XSD file.

• XML Schemas are actually defined using XML, so you don’t have to learn a new format or language just for that purpose.

• Developers can use XmlValidatingReader (which implements the XmlReader class) to validate XML against an XSD file.

Page 105: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

5.1-5.2 Understand System security namespace, Authentication, and

Authorization

Page 106: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings
Page 107: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

System.Security Namespace

• The System.Security namespaces contain classes that represent the Microsoft .NET Framework security system and permissions.• The classes in this namespace provide a framework for working with

the common runtime language security system.• One of the foundations of this security system is the concept of

permissions.• Note: although cryptography is not addressed specifically in this

lesson, the System.Security namespace also provides cryptographic services.

Page 108: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Permissions

• The .NET Framework allows code to perform only those operations that the code has permission to perform. It uses objects called permissions to enforce these restrictions.• There are two types of permissions, each with a specific purpose:

• Role-Based Security Permissions—provides a mechanism for discovering whether a user has a particular identity or is a member of a specified role.

• Code Access Permissions—represent access to a protected resource or the ability to perform a protected operation.

Page 109: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Role-Based Security

• Real-world security systems often use roles to determine the amount of access that various people have to a building.• As an example, consider a bank.

• A person classified as a “customer” has very limited access—he or she can probably only get into the lobby and other public areas, such as the restrooms.

• A “teller” can access the public areas, plus the area behind the counter or window.

• The “manager” can access all those areas, plus the safe.

Page 110: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Authentication and Authorization

• Role-based security depends on two processes: authentication and authorization. • Authentication is the process of verifying the identity of the person or

user, using the concept of credentials.• In the bank example, an employee’s credentials might be a photo-

ID card that is worn visibly at all times. Similarly, a school might use ID cards or uniforms to identify different roles.

• In many applications, the credential is the user’s password.

Page 111: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Authorization is the process of determining whether a person or user is allowed to perform a task.

o In the bank example, the employee ID might have a magnetic strip that is swiped to unlock a door. If the swiped card belongs to someone who is authorized to enter (based on that person’s role), the door opens

Page 112: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

PrincipalPermission Class

• The .NET Framework provides the PrincipalPermission class (in the System.Security.Permissions namespace) to handle role-based security.• The PrincipalPermission class represents the identity or role

that the principal must match. • A principal’s identity information can be accessed directly and role

and identity checks performed in the code when needed.

Page 113: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Code Access Permissions

• In addition to role-based security, .NET uses code access permissions.

• Code access permissions are permission objects that help protect resources and operations from unauthorized use. • Rather than relying on roles to determine if a user has permission,

this model is designed to prevent untrusted or unauthorized code from performing privileged or dangerous actions.

Page 114: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

• Each code access permission represents one of the following rights: • The right to access a protected resource, such as files or

environment variables• The right to perform a protected operation, such as accessing

unmanaged code• All code access permissions can be requested or demanded by code,

and the Common Language Runtime decides which permissions, if any, to grant the code

Page 115: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

.NET Code Access Permissions

• FileDialogPermission: Access files that have been selected by the user in an Open dialog box.• FileIOPermission: Read, append, or write files or directories.• PrintingPermission: Access printers.• RegistryPermission: Read, write, create, or delete registry keys

and values.• SecurityPermission: Execute, assert permissions, call into

unmanaged code, skip verification, and other rights.• SqlClientPermission: Access Microsoft SQL Server databases.• UIPermission: Access user interface functionality

Page 116: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Lesson Review

1. Explain how a role-based security system works.2. Explain the difference between authentication and authorization.3. How is code access security different than role-based security?

Page 117: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

6.1 Understand Language

Interoperability

Page 118: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Language Interoperability

• Language interoperability is the ability of code to interact with code that is written in a different programming language. • For example, a developer working in Microsoft C# can reference

and use code written in Microsoft Visual Basic.• Language interoperability is an important feature of the .NET

Framework; it can help maximize code reuse and improve the efficiency of the development process.

Page 119: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

CLR and language Interoperability

• .NET Framework enables cross-language interoperability through its use of the CLR.• The CLR is a run-time environment that executes .NET code. It

supports language interoperability by doing the following:• Providing a common system of data types that all .NET languages

can use.• Using metadata to store data about custom types; the CLR can

read this metadata and use the defined classes, regardless of their original language.

Page 120: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Interoperability Features Provided by the CLR

.NET Framework code benefits from the CLR’s support for language interoperability in the following ways:

• Types can inherit implementation from other types, pass objects to another type’s methods, and call methods defined on other types, regardless of the language the types are implemented in.• Debuggers, profilers, or other tools are required to understand only

one environment—the Microsoft intermediate language (MSIL) and metadata for the CLR—and they can support any programming language that targets the .NET CLR.

Page 121: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Common Language Specification

• There is no guarantee that the functionality of the types that you create can be fully used by the programming languages that other developers use. • For example, the code may use features that are not available in

the other language.• To ensure that your managed code is accessible to developers who

are using other programming languages, the .NET Framework provides the Common Language Specification (CLS).

Page 122: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

• The CLS describes a fundamental set of language features and defines rules for how those features are used.

• Code that is CLS-compliant can be used effectively by any .NET language, since it only uses features that are common to all .NET languages.

Page 123: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Use Assemblies from other languages• Developers can use CLS-compliant assemblies from a different

language in the same way they use assemblies from the same language—by adding a reference.• From the Project menu, select Add Reference.• To add a DLL, do the following: in the Add Reference dialog box,

choose the Browse tab and locate the desired dynamic-link library (DLL) file.

• To add a project, do the following: Select the Project tab and choose the desired project.

Page 124: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

.NET Language Parity

• Beginning with .NET version 4.0, Microsoft has focused on establishing language parity. • That is, the teams that develop .NET are striving to make sure that

language features are consistent (or “equal”) across all the .NET languages.

• This has the effect of expanding the CLS so that more features are CLS-compliant, and more code that developers write is interoperable across languages.

Page 125: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Lesson review

1. What is language interoperability?2. What is the CLS?3. What is language parity?

Page 126: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

6.2 Understand Type Safety

Page 127: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Type Safety

• Code is considered “type-safe” if it accesses only the memory locations that it is authorized to access.• Type safety is not mandatory, but it provides the following important

security benefits:o When code is type-safe, the Common Language Runtime (CLR) can

run assemblies in isolation, so they do not affect one another adversely.

o Type-safe code cannot call unmanaged code without permission, which helps prevent malicious code from doing any damage.

Page 128: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Type safety Verification

• Type safety is checked in the Just-In-Time (JIT) compilation process.• The JIT compiler checks the assembly’s metadata and the Microsoft

Intermediate Language (MSIL) code for the method to be compiled; it verifies that the code is type-safe.• This verification is optional and will be bypassed if the code has been

granted SecurityPermission with the passed enum member SkipVerification.

Page 129: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Unsafe code in C#

• “Unsafe” or unverifiable C# code can be executed in a context that is defined as unsafe.• Such code is not necessarily dangerous; it is just code whose safety

cannot be verified by the CLR. The CLR, therefore, will execute unsafe code only if it is in a fully trusted assembly.

• If you use unsafe code, it is your responsibility to ensure that your code does not introduce security risks or pointer errors.

Page 130: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Strong Types

• C# is a strongly typed language. Every variable and constant has a type, as does every expression that evaluates to a value.• Microsoft Visual Basic allows undeclared variables and variables

without a type, so it is not a strongly typed language. • Example: If a variable is used without declaring a type—or without

declaring the variable at all—the compiler will assign a type implicitly.

• It is usually best to use strong typing by specifying data types for all variables.

Page 131: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Benefits of Strong Typing

• It enables Microsoft IntelliSense support for variables and objects. • This allows the developer to see the properties and other

members as the code is entered.• It takes advantage of compiler type checking.

• This catches statements that can fail at run time due to errors such as overflow. It also catches calls to methods on objects that do not support them.

• It results in faster execution of code.

Page 132: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Common Type System(CTS)

• The CTS defines how types are declared, used, and managed in the CLR. • This is an important part of the run time’s support for cross-

language integration. • The CTS performs the following functions:

• Establishes a framework that helps enable cross-language integration, type safety, and high-performance code execution.

• Provides an object-oriented model that supports the complete implementation of many programming languages.

Page 133: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Security Policies

• Security policy is the configurable set of rules that the CLR follows when it decides what it will allow code to do. • Administrators set security policy and the run time enforces it. • The run time helps ensure that code can access only the resources—

and call only the code—allowed by security policy.• Whenever an attempt is made to load an assembly, the run time uses

security policy to determine which permissions to grant to the assembly.

Page 134: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Lesson Review

• Why is type safety important?• Microsoft Visual C# is a “strongly typed” language—what does this

mean?• List benefits of using strong types.

Page 135: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

7.1 Understand Resource Allocation

Page 136: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

.NET Garbage Collection

• The Microsoft .NET Framework’s garbage collector manages the allocation and release of memory for your application.• The garbage collector provides the following benefits:

• It enables you to develop an application without having to free memory.

• Allocates objects on the managed heap efficiently. • .NET Framework provides the GC (garbage collector) class for

manually controlling garbage collection

Page 137: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

.NET Memory Fundamentals

• Each process has its own space, referred to as virtual memory. All processes on the same computer share the same physical memory.• By default, on 32-bit computers, each process has a 2-GB user-mode

virtual address space.• Application developers work only with virtual address space and

never manipulate physical memory directly. • The garbage collector allocates and frees virtual memory for you

on the managed heap

Page 138: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Virtual Memory

• Virtual memory can be in three states: • Free: the block of memory has no references to it and is available

for allocation.• Reserved: the block of memory is available for your use and

cannot be used for any other allocation request. However, you cannot store data to this memory block until it is committed.

• Committed: the block of memory is assigned to physical storage.

Page 139: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Initiating Garbage Collection

• Garbage collection occurs when one of the following conditions is true:• The system has low physical memory.• The memory that is used by allocated objects on the managed

heap surpasses an acceptable threshold. This threshold is adjusted continuously as the process runs.

• The GC.Collect method is called. • Developers rarely need to call GC.Collect because the garbage

collector runs continuously. This method is used primarily for unique situations and testing.

Page 140: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

The Collection Process

Garbage collection consists of the following steps: 1. The garbage collector searches for managed objects that are

referenced in managed code.2. It tries to finalize objects that are not referenced.3. It frees objects that are not referenced and reclaims their memory.

Page 141: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Stacks and Heaps

• Variables are stored in either a stack or heap based on their type:• Value types (e.g., int, double, float) go on the stack.• Reference types (e.g., String, Object) go on the heap.• - Value types in classes are stored with the instance of the class

on the heap.• In managed code, the heap is managed by the garbage collector;

therefore, it is referred to as the managed heap.

Page 142: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Lesson Review

• What is the use of Stack?

• What is the use of Heap?

Page 143: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

7.2 Difference Between Managed and

Unmanaged Applications

Page 144: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Native Code

• The term “native code” refers to code that is targeted for a specific hardware/operating system architecture. • It is sometimes called “machine code” or “machine language.”• Native code is said to “run on the processor”; that is, it does not

require any further translation or conversion to be understood by the computer’s hardware.

• Eventually, all code must be compiled into the target machine’s language.

Page 145: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Managed Code

• Managed code is “managed” by an environment called the Common Language Runtime (CLR).• It’s called “Common Language” Runtime because it is the same

regardless of the language used to develop the application or assembly.

• From the perspective of an application developer or programmer, one of the most important tasks of the CLR is resource (memory) management—it allocates the available memory and releases that memory when no longer needed

Page 146: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Unmanaged Execution Process

In general, the steps for executing unmanaged code are as follows:1.Develop the source code in a high-level programming language (C

or Pascal, for example).2.Compile the source code into machine language.3.The processor executes the machine-language code.

Page 147: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Managed Execution Process

The steps for executing managed code are as follows:1.Develop the source code in a high-level programming language

(Microsoft C# or Microsoft Visual Basic, for example).2.Compile the source code into Microsoft Intermediate Language

(MSIL).3.At run time, MSIL is “just-in-time (JIT)”-compiled into machine-

language code.4.The processor executes the machine-language code.

Page 148: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

MSIL

• The high-level compiler converts source code into MSIL code.• MSIL is a CPU-independent set of instructions that can be converted

to native code efficiently.• Because it’s CPU-independent, MSIL is the same regardless of the

target platform.• Likewise, MSIL is language-independent; and an application will be

compiled into MSIL regardless of the .NET language used during development.

Page 149: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

JIT Compilation

• The MSIL code generated when a project is built cannot run by itself—it in turn must be compiled into native code for the target machine architecture. • When a managed application is executed, the CLR uses a JIT compiler

to create native code.• It is called “just in time” because it compiles the code during

program execution. • The native code is executed by the processor; when the application

has finished executing, the CLR disposes of the native code.

Page 150: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Benefits of Managed code and the CLR• Automatic memory management

• Developers do not need to write code to allocate and release memory.

• Type safety• Managed code cannot access unauthorized memory locations.

• Security• The CLR controls code access and helps prevent the execution of

dangerous code.

Page 151: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

• Language interoperability• The CLR allows developers to use code libraries written in

different programming languages.

• Platform independence• The developer does not need to target source code for a specific

platform—the JIT compiler will convert the code as necessary.

Page 152: 98-372 Microsoft.NET Fundamentals. 1.1 Understand Basic Application Settings

Lesson Review

1. What is native code?2. What are the characteristics of managed code?3. How is managed code execution different from native code

execution?