Title: 'NET Framework Essentials
1.NET Framework Essentials
- Clemens F. Vasterscofounder and CTO,
newtelligence AG, GermanyMSDN Regional
Directorclemensv_at_newtelligence.com
2Agenda
- The Big Picture
- The Common Language Runtime
- Assemblies and the Loader
- Security
- Attributes and Metadata
3Agenda
- 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
5Framework, Languages, And Tools
6Framework, Languages, And Tools
Visual Studio.NET
Common Language Specification
ADO.NET and XML
Base Class Library
Common Language Runtime
Operating System
7Terminology "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
8Agenda
- The Big Picture
- The Common Language Runtime
- Assemblies and the Loader
- Security
- Attributes and Metadata
9Common 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
10CLR Execution Model Conceptual
Compilation
Code (IL)
Source Code
Metadata
Before installation or the first time each method
is called
11JIT
- 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!
12CLR 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
13CLR Execution Model The Host
Win32 Host Process ("The Stub" or your code)
14Inside Hello World
15NGen 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
16NGenMyth 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
17Love, 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
?
18The 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
19The 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
20Agenda
- The Big Picture
- The Common Language Runtime
- Assemblies and the Loader
- Security
- Attributes and Metadata
21Good 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
22Modules
- 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
23Assembly
- 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
24Assembly 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 ...
25Manifest 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
26Inspecting the Manifest
27Loader Scenarios 1/2
Everything from single Directory
28Loader Scenarios 2/2
Assembly in Global Assembly Cache
Configuration defines private Path
.NETGAC
29Loader Scenarios
30Mobile Code
Downloaded Assembly Cache
Configuration defines "Codebase"
Internet
.NETDAC
Windows Forms Control in IE
Remote Website
31Agenda
- The Big Picture
- The Common Language Runtime
- Assemblies and the Loader
- Security
- Attributes and Metadata
32Mobile Code
Downloaded Assembly Cache
Configuration defines "Codebase"
Internet
.NETDAC
Windows Forms Control in IE
Remote Website
33The 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
34Code Access Security for Mobile Code
35Code Group Hierarchy
36Managing Code Groups
37Agenda
- 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
39MetaData 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
40Generic Code Savers
Public Class Person Public Property
FirstName As String Public Property
DateOfBirth As String Public Sub Save()
Public Sub SearchAddress() End Class
41Attributes
- "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
42Using and Creating Attributes
43Agenda
- The Big Picture
- The Common Language Runtime
- Assemblies and the Loader
- Security
- Attributes and Metadata
- .NET Remoting
44Distributed 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
46Exposing 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
47Single 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
48Client-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"
49Server 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
50Server 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
51Activation 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()
52Using Remote ObjectsWeb Services Remoting-Style
53Agenda
- The Big Picture
- The Common Language Runtime
- Assemblies and the Loader
- Security
- Attributes and Metadata
- .NET Remoting
- ... and now some even cooler stuff ...
54The CodeDom
55Using C for Scripting
56Reflection.Emit
57Building Assemblies
58Questions ?
59IL 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
60IL in 5 Minutes Data Types
- Datentypen in IL sind die Datentypen der CLR
61IL 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"
62IL 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
63IL 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)
64IL in 5 Minutes Arithmetic
- Addition, Subtraktion, Multiplikation, Division,
Modulo... - add, sub, mul, div, rem
5
3
add
8
3.141592
3.141592
add
65IL 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 ?