'NET Framework Essentials - PowerPoint PPT Presentation

1 / 58
About This Presentation
Title:

'NET Framework Essentials

Description:

Compiles IL code method-by-method on first call. Application is always executed natively ... Pre-compile, pre-load, pre-layout. Validate at execution time ... – PowerPoint PPT presentation

Number of Views:55
Avg rating:3.0/5.0
Slides: 59
Provided by: clem57
Category:

less

Transcript and Presenter's Notes

Title: 'NET Framework Essentials


1
.NET Framework Essentials
  • Clemens F. Vasterscofounder and CTO,
    newtelligence AG, GermanyMSDN Regional
    Directorclemensv_at_newtelligence.com

2
Agenda
  • The Big Picture
  • The Common Language Runtime
  • Assemblies and the Loader
  • Security
  • Attributes and Metadata

3
Agenda
  • The Big Picture
  • The Common Language Runtime
  • Assemblies and the Loader
  • Security
  • Attributes and Metadata

4
.NET Framework Design Goals
  • Unifies programming models
  • Dramatically simplifies development
  • Provides robust execution environment
  • Supports multiple programming languages
  • Natively supports XML Web Services

5
Framework, Languages, And Tools
6
Framework, Languages, And Tools
Visual Studio.NET
Common Language Specification
ADO.NET and XML
Base Class Library
Common Language Runtime
Operating System
7
Terminology "ABC"
  • CLR Common Language Runtime
  • One runtime for many programming languages
  • Intermediate Language (IL)
  • One intermediate, high-level assembly-style
    language that is emitted by language compilers
  • Assembly
  • Container for code, metadata and resources your
    new term for what you used to call "D-L-L"
  • Metadata
  • Information that describes the shape of data and
    the runtime behavior of a program

8
Agenda
  • The Big Picture
  • The Common Language Runtime
  • Assemblies and the Loader
  • Security
  • Attributes and Metadata

9
Common Language Runtime
  • Execution Environment for "managed code"
  • Managed?
  • Code resides on disk as IL
  • Must be translated into machine code
  • Code references other code
  • Other code residing in other Assemblies must be
    found
  • Memory must be managed
  • Server applications must be 100 leak free
  • .NET employs a Garbage Collector to do that job
  • Execution must be as secure as possible
  • Safeguard code against viruses and worms

10
CLR Execution Model Conceptual
Compilation
Code (IL)
Source Code
Metadata
Before installation or the first time each method
is called
11
JIT
  • Just In Time Compiler
  • Compiles IL code method-by-method on first call
  • Application is always executed natively
  • Machine code is kept in memory
  • Optimizing compiler
  • Register Allocation, Constant Folding, Copy
    Propagation, Eliminate Range Checks in Loops,
    Hoist Invariant Code, Loop Unroll, Common
    SubExpression Elimination (CSE),
    Processor-specific code generation, Method
    Inlining
  • Only in Release Builds!
  • Dont do performance testing using Debug Builds!

12
CLR Execution Model Physical
MyProg.xxx
Source Program
Compile
MyProg.exe
PE Header Metadata IL Binary
JIT-compile
Assembly
MethodTable
IL
x86
MT
Common Language Runtime
Processes Memory etc.
Operating System
13
CLR Execution Model The Host
Win32 Host Process ("The Stub" or your code)
14
Inside Hello World
15
NGen What Is It?An MSIL-to-Native Compiler
Eliminating JIT
  • Pre-compile, pre-load, pre-layout
  • Validate at execution time
  • May factor in processor type, other installed
    assemblies, etc.
  • If invalid, use the normal execution path
  • Goal faster start-up
  • Because of smaller start-up working set
  • Makes sense for desktop applications
  • Usually as part of assembly installation
  • Tool (ngen.exe) ships in Visual Studio .Net

16
NGenMyth Reality Performance Impact
  • Reduces working set
  • Startup time is reduced
  • Most noticeable if all code is NGened
  • Shared if many processes use same assembly
  • Runs (very) slightly slower
  • Double jump to runtime support routines
  • Call to jump across assemblies
  • Sometimes extra checks for class initialization
  • Same issue as domain-neutral lazy is costly
  • Assembly includes IL and native code
  • Your mileage may vary
  • Measure early, measure often and in the real
    world

17
Love, Peace and Garbage Collection
  • You love Managed Memory and Garbage Collection
    because ...
  • ... you wont spend another night until 4am
    hunting that sporadic memory leak
  • just to eventually fall asleep on your keyboard
  • ... silent accidental buffer overruns are
    caught
  • ... memory usage is optimised automatically
  • ... batch compacting of memory
  • ... malloc/free compact on each call or at least
    very frequently
  • ... one memory manager
  • remember GlobalAlloc, malloc, new, CoTaskMemAlloc
    ?

18
The Collector
  • Allocating memory
  • Mostly in-lined by JIT (in generated machine
    code)
  • Emitted machine code differs based on type of
    object allocated, size of instance, etc.
  • Works by identifying live objects
  • Live objects found walking memory from roots
  • Finding roots
  • Static fields
  • Thread stacks
  • Registers
  • Compacting active data

19
The Collector In Action
New Heap Begins with New Generation
Accessible References Keep Objects Alive
Preserves / Compacts Referenced Objects
Objects Left Merge with Older Generation
New Allocations Rebuild New Generation
20
Agenda
  • The Big Picture
  • The Common Language Runtime
  • Assemblies and the Loader
  • Security
  • Attributes and Metadata

21
Good Bye Registry, Good Bye Version-Hell
  • Assemblies
  • Container for Code, Metadata and Resources
  • One or more physical files
  • Enable "XCopy Deployment"
  • Basic principle is very simple
  • "All files in one directory"
  • "Objection! That is not new, is it?"
  • Not for simple DLLs but for components!
  • Registry is ignored
  • Assemblies are not loaded blindly
  • C, Java pick "whatever looks right"
  • .NET Loader Location, Version, Culture,
    Originator

22
Modules
  • Module is compiled unit
  • Much like C .obj file
  • Modules contain metadata and IL
  • Metadata describes structure
  • IL describes runtime behavior
  • Modules cannot be loaded independently
  • Must be contained in Assembly

23
Assembly
  • Assemblies are loadable entities enabling
  • Versioning
  • Code Reuse
  • Unique Code Identity
  • Code Access Security
  • Assemblies contain
  • Modules
  • Resources (string tables, files)
  • Consist of one or multiple physical files
  • Bundled by a "packing list" The Manifest

24
Assembly vs. Namespace
  • Namespaces are used to group identifiers
  • "Convenience" feature to make classes manageable
    and (fairly) uniquely named
  • Assemblies can contain several Namespaces
  • Namespaces can span multiple Assemblies
  • Same-name types in two Assemblies are different!
  • Independent concepts
  • Namespaces are imported in the source code
  • Assemblies are referenced by compiler switch

using System.Runtime.Remoting.Services
csc /rSystem.Runtime.Remoting.DLL ...
25
Manifest Standard Elements
  • Manifest is table with info records
  • Manifest contains info about
  • Assembly name
  • Version information
  • Strong name information
  • Culture information
  • Processor and OS
  • Files that make up this assembly
  • References to types and resources
  • Exported and local types

26
Inspecting the Manifest
27
Loader Scenarios 1/2
Everything from single Directory
28
Loader Scenarios 2/2
Assembly in Global Assembly Cache
Configuration defines private Path
.NETGAC
29
Loader Scenarios
30
Mobile Code
Downloaded Assembly Cache
Configuration defines "Codebase"
Internet
.NETDAC
Windows Forms Control in IE
Remote Website
31
Agenda
  • The Big Picture
  • The Common Language Runtime
  • Assemblies and the Loader
  • Security
  • Attributes and Metadata

32
Mobile Code
Downloaded Assembly Cache
Configuration defines "Codebase"
Internet
.NETDAC
Windows Forms Control in IE
Remote Website
33
The Problem with Mobile CodeSecurity
  • .NET Security
  • Not as paranoid as the Java Sandbox
  • Not as naïve as Authenticode
  • "Code Access Security"
  • Defines closely what is permitted for code
  • Code execution does not only depend on user
    permissions
  • Based on evidence about code origin and author
  • Categorisation of code in groups and zones
  • "Code Groups"
  • Controlled using policies

34
Code Access Security for Mobile Code
35
Code Group Hierarchy
36
Managing Code Groups
37
Agenda
  • The Big Picture
  • The Common Language Runtime
  • Assemblies and the Loader
  • Security
  • Attributes and Metadata

38
.NET Metadata Core Concepts
  • Metadata
  • Single location for type information and code
  • Code is literally contained within type
    information
  • Every .NET object can be queried for its type
  • Types' metadata can be explored using Reflection
  • Dynamic Type System
  • Highly dynamic and language independent
  • Types may be extended and built at run-time
  • Allows on-the-fly creation of assemblies
  • .NET Compilers use .NET to emit .NET code
  • Reflection.Emit

39
MetaData Type Info at Runtime
serializablepublic class Person
public event OnSaveChange onsv public Date
DOB public string FirstName public
string LastName public string Name
get return FirstName " "
LastName public void
Person(string First,string Last)
FirstNameFirstLastNameLast public
bool Save() System.Type t
this.GetType() foreach( FieldInfo f in
t.GetFields() ) ...
System.Type
Attributes
Events
Fields
Properties
Constructors
Parameters
Methods
40
Generic Code Savers
Public Class Person Public Property
FirstName As String Public Property
DateOfBirth As String Public Sub Save()
Public Sub SearchAddress() End Class
41
Attributes
  • "Sticky Notes" for code-elements
  • Describe behaviour of functions, properties,
    fields or classes
  • Enable implementaion of generic functionality one
    for (almost) all classes
  • How?
  • Using Attributes (C,VB)
  • WebMethod public void Func() ...
  • ltWebMethod()gt Public Sub Func() ... End Sub
  • WebMethod Attribut für WebService in ASP.NET
  • Attribute bauen und auswerten
  • Neue Klasse von "System.Attribute" ableiten
  • Via Reflection zur Laufzeit abfragen

42
Using and Creating Attributes
43
Agenda
  • The Big Picture
  • The Common Language Runtime
  • Assemblies and the Loader
  • Security
  • Attributes and Metadata
  • .NET Remoting

44
Distributed Components
Lx Server
.NET App
.NET Server
Internet
45
.NET Remoting Channels
  • Channels transport messages
  • Built-in channels TCP, HTTP
  • Extensible model Named Pipes as SDK sample
  • Establish endpoint-to-endpoint communication
  • Formatters render wire format (Binary, SOAP, ...)
  • Proxies map calls to messages
  • Architecture makes no assumptions about endpoint
    architecture

Channel
Server
Client
"Proxy"
Dis-patcher
46
Exposing Well-Known Objects
  • .NET's activation model is very unlike COM's
  • .NET rather resembles CORBA model (!)
  • If there is no actively listening endpoint no
    connection
  • No surrogates, no registry, no location
    transparency
  • EXE servers are not remotely activated
  • Simplifies Remoting greatly
  • Expose well-known object for clients to connect.
  • Bound to known channels with known name
  • Does not use static registration, prog-ids or
    class-id
  • Can expose "single call" or "singleton" objects

47
Single Call and Singletons
  • "Single Call" Objects
  • Object instance is created for each call on
    channel
  • Implements the stateless model of the web
  • "Singleton" Objects
  • One shared instance provided for all clients
  • Serves as "gateway" into stateful application
  • Object is created at registration time

48
Client-Side Activation
  • Client-Side Activation similar to COM
  • Client requests creation of remote object
  • Core difference Server must be running
  • Server Side Implementation
  • Class registered with RemotingConfiguration class
    or XML config file
  • RemotingConfiguration.RegisterActivatedServiceType
    ()
  • Runtime creates objects on client request
  • Client Side Implementation
  • Object created through Activator class
  • Alternatively Configuration and language binding
  • Allows creating remote objects using "new"

49
Server Setup Example
... HttpChannel chan new HttpChannel(8080) Cha
nnelServices.RegisterChannel(chan) RemotingConfi
guration. RegisterWellKnownServiceType(
typeof(ServerClass), "MyEndpointURI",
WellKnownObjectMode.SingleCall)
Channel registration
Object registration
Registers the single-call endpointhttp//myserve
r8080/MyEndpointURI
50
Server Configuration Example
ltconfigurationgt ltsystem.runtime.remotinggt
ltapplication name"MyFoo"gt ltservicegt
ltwellknown type"Foo, common
objectUri"Foo.soap
mode"Singleton" /gt lt/servicegt
ltchannelsgt ltchannel ref"http
name"MyHttpChannel" port"9000"gt
ltserverProvidersgt ltformatter
ref"soap" /gt lt/serverProvidersgt
lt/channelgt lt/channelsgt lt/applicationgt
lt/system.runtime.remotinggt lt/configurationgt
Declare singleton service endpoint
Associate channel with application
Associate formatter with channel
51
Activation illustrated
tcp//server8501/uriD
http//server8080/uriB
TCP8501
HTTP8080
RemotingServices.Connect()
AppDomain
Identity Table
Activator.GetObject()
uriA
uriB
uriC
uriD
Languagebinding
Context
Object
Object
o Activator.GetObject("http//...")o.methodCal
l()
Object
Object
o new myClass()o.methodCall()
52
Using Remote ObjectsWeb Services Remoting-Style
53
Agenda
  • The Big Picture
  • The Common Language Runtime
  • Assemblies and the Loader
  • Security
  • Attributes and Metadata
  • .NET Remoting
  • ... and now some even cooler stuff ...

54
The CodeDom
  • ltltTBDgtgt

55
Using C for Scripting
56
Reflection.Emit
  • ltltTBDgtgt

57
Building Assemblies
58
Questions ?
59
IL in 5 Minutes The Stack
Push
Pop
  • IL is a stack-oriented language
  • Arguments for methods, operators are pushed onto
    the stack.
  • Return values are on the stack
  • But Local variables, arguments are not on the
    stack!
  • Stack ist polymorphic
  • All Elements are System.Object typed

5
true
MyClass
FileStream
3.141592
60
IL in 5 Minutes Data Types
  • Datentypen in IL sind die Datentypen der CLR

61
IL in 5 Minutes Push
  • Constants are pushed using ldc.type, ldstr
  • Local variables are pushed with ldloc.n
  • Arguments are pushed with ldarg.n

ldarg.0
ldc.r4 3.141592
Push
Push
ldloc.1
true
Push
3.141592
3.141592
"String"
"String"
"String"
62
IL in 5 Minutes Pop
  • Methods, Operators pop arguments automatically ?
    numbered slots for ldarg
  • Explicit "pop" to removed unused elements

call System.IO.StreamWriter.Write
StreamWriter
StreamWriter
pop
Write(string)
"String"
MyClass
MyClass
true
true
63
IL in 5 Minutes Method Calls
  • Instance identity for methods is implicit first
    argument not for static methods
  • Arguments popped off the stack into args
  • Return value pushed onto stack

string
System.String
"Hello World!"
CompareTo(string)
0 (u4)
3.141592
3.141592
call System.StringCompareTo(string)
64
IL in 5 Minutes Arithmetic
  • Addition, Subtraktion, Multiplikation, Division,
    Modulo...
  • add, sub, mul, div, rem

5
3
add
8
3.141592
3.141592
add
65
IL in 5 Minutes Branching
  • In IL, Branches are absolute oder conditional
    jumps to predefined labels
  • In JITed code, jumps branch to a local offset
    within the same method
  • No cross method jumps and long jumps

ldc.i4 5 ldc.i4 4 blt jump_target ... ... jump_tar
get
5 lt 4 ?
Write a Comment
User Comments (0)
About PowerShow.com