ABB
.NET Framework Architecture
VB C++ C# JScript Visual Studio.NET
Page 1
Common Language Runtime
Manages running code
n Verifies type safety n Provides garbage collection, error handling n Code access security for semi-trusted code
Common Language Specification ASP.NET Windows Forms
ADO.NET and XML Base Class Library Common Language Runtime Windows COM+ Services
Provides common type system
n Value types (integer, float, user defined, etc) n Objects, Interfaces
Provides access to system resources
n Native API, COM interop, etc.
Common Language Runtime
Base Class Library Support Thread Support Type Checker Security Engine IL to Native Compilers Code Manager Class Loader COM Marshaler Exception Manager Debug Engine
Exception handling
The CLR supports a standard exception- handling mechanism that works across all languages.
n Filters (lowest level) exceptions: [C#] try { //Some code that access a file }
Garbage Collector
catch(FileNotFoundException e) { Console.WriteLine("[Data File Missing] {0}", e); } n Prepare state for exception
ABB
Security support Debugging support
Page 2
The CLR checks to make sure that:
n The code is safe to execute n The code is not breaching any security requirements
The provided API for debuggers contains:
n Support for controlling program execution n Breakpoints n Exceptions n Control flow etc.
The security engine also supports:
n Code-access security n Declarative security checks
n Specified through administrative configuration or via attributes
n Imperative security checks
n Method code enforces security requirements
Interoperation Support
What is Assemblies
n
The Microsoft .NET Framework promotes interaction with:
n COM components n COM+ services n External type libraries etc.
Collection of functionality that is built versioned and deployed as a single implementation unit. The manifest: ( use MSIL disassembler Ildasm.exe to view)
n Establishes the identity, version, culture and digital signature. n Defines what files are included in the assembly n Specifies the types and resources that make up the assembly,
How to bridge the gap:
n COM Interop facility is a bridge between COM and the CLR n Platform Invoke (P/Invoke) facility makes it possible to call
included those that are exported from the assembly.
n Itemizes the compile-time dependencies on other assemblies. n Specifies the set of permissions required for the assembly to run
Windows API functions
properly. n
AssemblyInfo.cs sets the attributes
ABB
Single vs Multifile Private Assemblies
n Used by a single application n Stored in the same application directory as the application n Name does only need to be unique within the application scope n Guaranteed that the application will run with the bits it was built
Page 3
with
Shared Assemblies
Signing An Assembly
Calculus.dll
n Used by many applications at the same time n Must have a cryptographically unique strong name n Deployed in the global assembly cache %windir%\Assembly IL Metadata Manifest Assembly files (self & RUT.mod) Public assembly types (self & RUT.mod) Public Key Embedded in PE File Hash PE File Hash Value Signed with private key RSA Digital Signature
RSA Digital Signature
Embedded in PE File
Public Key
ABB
Satellite Assemblies How the Runtime Locates Assemblies
Page 4
en
sv
.NET PE File
Zh-CN n One core assembly with the code n Different resource assemblies for each culture JIT Compilers CLRs Virtual Execution Engine
Versioning And Policy
How Assembly References are Resolved part 1
n n
Default: Bind to version built against Can be overridden with policy
n Application-specific policy n Publisher policy
1.
Determines the correct assembly version by examining applicable configuration files.
1. Check the application configuration file for information that
overrides the version information stored in the calling assembly s manifest.
2. Examines the publisher policy file installed in the GAC with the
n Administrator policy or machine.config <dependentAssembly> <assemblyIdentityname="myasm" publicKeyToken="e9b4c4996039ede8" /> <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/> </dependentAssembly>
assembly.
1. May be overridden with <publisherPolicy apply=yes|no> in the
app config. 3. Checks the machine configuration called Machine.config located
in the config subdirectory of the run-time installation. The version presented here is final and cannot be overridden. 2.
If the assembly has been bound to before, use the previously loaded assembly.
JIT
en-US
Main code
Class Loader
Verifier
Managed Native Code
ABB
How Assembly References are Resolved part 2
Execution in the CLR
CLRs Virtual Execution Engine
Page 5
3. 4.
Checks the GAC for the assembly, if found, use it. Probes for the assembly in the following steps:
1. If configuration and publisher policy do not affect the original JIT Compiler Verifier Class Loader
reference and the request was made using Assembly.LoadFrom(), then use this information
2. If a <codebase> is found in the application configuration file
Call to uncompiled code
Managed Native Code
then use it, if not found at that specified location the request fails.
3. Further probing using application base, culture, name and
private binpath. 5.
Execution
Execution Support And Management Class Libraries (IL & Metadata)
If not found ask windows installer to install it. It acts as an install on demand feature.
.NET Framework Architecture
VB C++ C# JScript Visual Studio.NET
.NET Framework Namespace
System.Web Services Description Discovery Protocols Caching Configuration UI HtmlControls WebControls Security SessionState Design System.WinForms ComponentModel
Common Language Specification ASP.NET Windows Forms
System.Drawing Drawing2D Imaging Printing Text System.Xml XSLT XPath System Security ServiceProcess Text Threading Serialization
ADO.NET and XML Base Class Library Common Language Runtime Windows COM+ Services
System.Data ADO Design SQL SQLTypes
Collections Configuration Diagnostics Globalization
IO Net Reflection Resources
Runtime InteropServices Remoting Serialization
ABB
Language Interoperability A Unified Programming Model
Consistent API availability regardless of language and programming model
Page 6
n The CLR specifying and enforcing a common type system n Inherit implementation from other types implemented in other
languages
n Debuggers, profilers and other tools requires only to understand one
.NET Framework
RAD, Composition, Delegation Subclassing, Power, Expressiveness Stateless, Code embedded in HTML pages
environment, the MSIL
n Exceptions can be thrown across languages
VB Forms
MFC/ATL
ASP
Windows API
Languages that Support .NET
n Advanced multi-language features
n Cross language inheritance, exceptions
Windows Forms
n Over 20 languages support .NET
n APL n Cobol n Component Pascal n Eiffel n Haskell n Mercury n Oberon n Perl n Python n Scheme n SmallTalk n Standard ML n C++ n VB n JScript n C#
n n n
Uses virtual methods to override message responses No message loop Component model that supports events
MyButton.Click += new EventHandler (OnButtonClicked); private void OnButtonClicked (object sender, EventArgs e) { MessageBox.Show ("Click!");}
n n
Event is using delegates as function pointers Main form is started and then it is up to the components to fire events
ABB
Programming model
n
Page 7
Example Windows API
HWND hwndMain = CreateWindowEx( 0, "MainWClass ", "Main Window", WS_OVERLAPPEDWINDOW | WS_HSCROLL | WS_VSCROLL, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, (HWND)NULL, (HMENU)NULL, hInstance, NULL); ShowWindow(hwndMain, SW_SHOWDEFAULT); UpdateWindow(hwndMain);
Organization
n Organized in hierarchical namespaces
Unified type system
n Everything is an object n Boxing converts value types to objects
n No need for special variant type
Component Oriented
n Properties, methods & events are 1st class n Design-time functionality
.NET Framework
Form form = new Form(); form.Text = "Main Window"; form.Show();
Everything Is An Object
n
Everything Is An Object
n
Traditional views of primitive types
n C++, Java: Theyre magic n Smalltalk, Lisp: Theyre full-blown objects
Boxing
n Allocates box, copies value into it
Unboxing
n Checks type of box, copies value out
The .NET Framework unifies with no performance cost
n Deep simplicity throughout system
Improved extensibility and reusability
n New primitive types: Decimal, SQL n Collections, etc., work for all types
Dim i As Integer = 123 Dim o As Object = i Dim j As Integer = CInt(o) i o j 123 123 123
int i = 123; object o = i; int j = (int)o ;
System.Int32
ABB
From COM to .NET From COM to .NET
Page 8
COM Registration GUIDs .IDL files HRESULTs IUnknown AddRef /Release CoCreateInstance QueryInterface
.NET self describing components hierarchical namespaces source code to metadata structured exceptions Root object class Garbage collector new operator Type.GetInterface
n No registration required
n Code is completely self- describing n Simply xcopy components to application directory
n Zero-impact install
n Installing one application will not affect another
n Side-by -side execution
n Multiple component versions can co- exist
Integration with COM
Evolution of COM
n Deploy .NET classes as COM objects
n Register with RegAsm.exe
COM
COM+
n COM objects can be imported
n No ref counting or COM API needed
n .Net classes utilize COM+ services
n Transactions, Object pooling, etc
n Easily call system functions
n No marshaling for common cases
MTS
ABB
Overview of COM+ Services Object Pooling
Page 9
Some COM+ Services:
n n n n
Pools are:
n n
Transactions Object Pooling Queued Components (MSMQ) Security
A group of resources. Shared between clients.
Methods used for object pooling in .NET:
n
For a class to exploit COM+ Services, it must:
n
CanBePooled(), lets you tell COM+ whether your object can be pooled when this method is called. Activate( ) and Deactivate( ) to perform initialization and cleanup.
Derive from the ServicedComponent class
Transactions
n n
Attribute-Based Programming
Collections of operations that form a single logical unit of work are called transactions. Transaction must be atomic (i.e., either all or none of the operations in the transaction are completed).
Attributes are placed to signal characteristics about the code
n Either predefined or custom
n n
By taking advantage of COM+ Services transactions are easily implemented in .NET (as we shall see).
Interceptor programs look for special attributes and provide additional service if they are present. Used for accessing COM+ Services from within the .NET framework. The programmer does not need to know the details of how this is implemented to use COM+ Services. The .NET Reflection API can be used to implement
n n
ABB
Example: Transactions (C#)
Example adapted from OReillys .NET Framework Essentials
Page 10
Example: Transactions (alternative C#)
Example adapted from OReillys .NET Framework Essentials
using System; using System.EnterpriseServices; // Installation options omitted [Transaction(TransactionOption.Required] Public class Customer : ServicedComponent { public void Add(...) { try { // Add new customer to the system and update dbs ContextUtil.SetComplete(); // Commit } catch(Exception e) { ContextUtil.SetAbort(); } } }
using System; using System.EnterpriseServices; // Installation options omitted [Transaction(TransactionOption.Required] Public class Customer : ServicedComponent { [AutoComplete] public void Add(...) { // Add new customer to the system and update dbs } }
Overview of the Exercises
Exercise 1
1 2 3 Windows Application
n
Private Assembly
Goal:
n Get to know WinForms and how to create applications in .NET
using C# n
Shared Assembly
Requirements
n Must have Visual Studio.NET and the framework
1 2 3 Web Application
Prerequisites
n Know C++/Java or C#
n
Web Service
Deliverable
n A simple window based application
ABB
Exercise 1
n
Page 11
Exercise 2
Example view from exercise 1
n
Goal:
n Implement an interface that will be used in the following labs n Add a strong name to the interface and put it in the GAC n Get to know private assemblies
Requirements
n Lab 1 finished
Deliverable
n An assembly that provide a common interface for the successive
exercises
n A private assembly that use the common interface
Useful tools
n COM Interoperability
n TlbImp.exe Imports a COM type library into a proxy .NET assembly n RegAsm.exe Enters a .NET component into the registry n TlbExp.exe Exports a .NET components type information n AxImp.exe Creates a .NET proxy for an ActiveX control so that the control
Useful Tools
n Assembly management
n ildasm.exe examines assemblies and shows the manifest n Gacutil.exe adds and removes assemblies to the Global Assembly Cache n sn.exe generates and manages private and public keys XML n Al.exe Assembly generation utility is used to generate assemblies with
can be used in a .NET WinForm n Class Viewer
n WinCV.exe Used to view classes available in the GAC including all base
manifests and key manipulations
n NGEN.EXE The native Image Generator creates a native image and installs
it in the cache allowing assemblies to load faster n XML
n XSD.exe Used to work with XML Schema Definitions
n
classes n CLR resource loading
n Fuslogvw.exe helps to analyze the resource loading process
For example: Classes to XSD, XML to XSD
n .NET Configuration
n Mscorcfg.msc manages publication polices and assemblies
ABB
Additional Resources
n n n n n n n n n
Page 12
msdn.microsoft.com/net/ www.gotdotnet.com www.asp.net www.microsoft.com/trainingandservices www.msjogren.net/dotnet/swe/ msdn.microsoft.com/msdnmag/netindex.asp www.dotnetwire.com/ www.devx.com/dotnet/ NET Framework Essentials
n THuan Thai & Hoang Q. Lam, OREILLY 2001
www.msdn.microsoft.com
n Source for many papers/tutorials/tools etc.