Wednesday, February 29, 2012

How the .NET Runtime Resolves Type References

Lets, consider the below source code:

public sealed class Program
{
public static void Main()
{
System.Console.WriteLine("Hi");
}
}
This code is compiled and built into an assembly, say Program.exe. When you run this application, the CLR loads and initializes. Then the CLR reads the assembly's CLR header, looking for the MethodDefToken that identifies the application's entry point method (Main). From the MethodDef metadata table, the offset within the file for the method's IL code is located and JIT-compiled into native code, which includes having the code verified for type safety. The native code then starts executing. Following is the IL code for the Main method. To obtain this output, run ILDasm.exe, chose the View menu's Show Bytes menu item, and then double click the Main method in the tree view.
.method public hidebysig static void Main() cil managed
// SIG: 00 00 01
{
.entrypoint
// Method begins at RVA 0X2050
// Code size 11 (0xb)
.maxstack 8
IL_0000: /* 72 | (70)000001 */
ldstr "Hi"
IL_0005: /* 28 | (0A)000003 */
call void [mscorlib]System.Console::WriteLine(string)
IL_000a: /* 2A | */
ret
} // end of method Program::Main
When JIT-compiling this code, the CLR detects all references to types and members and loads their defining assemblies (if not already loaded). As you can see, the IL code above has a reference to System.Console.WriteLine. Specifically, the IL call instruction references metadata token 0A000003. This token identifies entry 3 in the MemberRef metadata table (table 0A). The CLR looks up this MemberRef entry and sees that one of its fields refers to an entry in a TypeRef table (the System.Console type). From the TypeRef entry, the CLR is directed to an AssemblyRef entry:
"MSCorLib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089".
At this point, the CLR knows which assembly it needs. Now the CLR must locate the assembly in order to load it.

When resolving a referenced type, the CLR can find the type in one of three places:
  • Same file Access to a type that is in the same file is determined at compile time (sometimes referred to as early bound). The type is loaded out of the file directly, and execution continues.
  • Different file, same assembly The runtime ensures that the file being referenced is, in fact, in the assembly's FileRef table of the current assembly's manifest. The runtime then looks in the directory where the assembly's manifest file was loaded. The file is loaded, its hash value is checked to ensure the file's integrity, the type's member is found, and execution continues.
  • Different file, different assembly When a referenced type is in a different assembly's file, the runtime loads the file that contains the referenced assembly's manifest. If this file doesn't contain the type, the appropriate file is loaded. The type's member is found, and execution continues.
If any errors occur while resolving a type reference—file can't be found, file can't be loaded, hash mismatch, and so on—an appropriate exception is thrown.

Below figure illustrates how type binding occur:
Figure: Flowchart showing how, given IL code that refers to a method or type, the CLR uses metadata to locate the proper assembly file that defines a type 

XAML : Extensible Application Markup Language

XAML (short for Extensible Application Markup Language, and pronounced "zammel") is a markup language used to instantiate .NET objects. Although XAML is a technology that can be applied to many different problem domains, its primary role in life is to construct WPF user interfaces. In other words, XAML documents define the arrangement of panels, buttons, and controls that make up the windows in a WPF application.
It’s important to understand that WPF doesn’t require XAML. There’s no reason Visual Studio couldn’t use the Windows Forms approach and create code statements that construct WPF windows. But if it did, window would be locked into the Visual Studio environment and available to programmers only.
The XAML standard is quite straightforward. Below are few ground rules:
  • Every element in a XAML document maps to an instance of a .NET class. The name of the element matches the name of the class exactly.
  • As with any XML document, one element can be nested inside another. However, nesting is usually a way to express containment.
  • You can set the properties of each class through attributes. However, in some situations an attribute isn’t powerful enough to handle the job. In these cases, you’ll use nested tags with a special syntax.
XAML Language:
  • Declarative object syntax
  • Use to define the static structure and configuration of an object hierarchy
  • Not specific to WPF
  • Easier to write development tools
  • Relatively easy to edit and understand
  • Expresses object hierarchies in a more compact form
  • Objects must have default constructor
  • Requires type conversion
XAML Constructs:

Architecture of WPF

Architecture in the Presentation Layer
  • "The software architecture of a program or computing system is the structure or structures of the system, which comprise software elements, the externally visible properties of those elements, and the relationships among them."
    - From the book Software Architecture in Practice (2nd edition), (Bass, Clements, Kazman;Addison-Wesley 2003)
  • WPF has a rich and extensible architecture for designing compelling UI applications
WPF uses a multi layered architecture. At the top, application interacts with a high-level set of services that are completely written in managed C# code. The actual work of translating .NET objects into Direct3D textures and triangles happens behind the scenes, using a lower level unmanaged component called milcore.dll.
milcore.dll is implemented in unmanaged code because it needs tight integration with Direct3D and because it’s extremely performance-sensitive.
Figure : WPF rendering architecture
Key components:
  • PresentationFramework.dll holds the top-level WPF types, including those that represent windows, panels, and other types of controls. It also implements higher-level programming abstractions such as styles. Most of the classes you’ll use directly come from this assembly.
  • PresentationCore.dll holds base types, such as UIElement and Visual, from which all shapes and controls derive. If you don’t need the full window and control abstraction layer, you can drop down to this level and still take advantage of WPF’s rendering engine.
  • WindowsBase.dll holds even more basic ingredients that have the potential to be reused outside of WPF, such as DispatcherObject and DependencyObject, which introduces the plumbing for dependency properties.
  • milcore.dll is the core of the WPF rendering system and the foundation of the Media Integration Layer (MIL). Its composition engine translates visual elements into the triangle and textures that Direct3D expects. Although milcore.dll is considered a part of WPF, it’s also an essential system component for Windows Vista. In fact, the Desktop Window Manager (DWM) in Windows Vista uses milcore.dll to render the desktop.
  • milcore.dll is sometimes referred to as the engine for “managed graphics.” Much as the common language runtime (CLR) manages the lifetime of a .NET application, milcore.dll manages the display state. And just as the CLR saves you from worrying about releasing objects and reclaiming memory, milcore.dll saves you from thinking about invalidating and repainting a window.
  • WindowsCodecs.dll is a low-level API that provides imaging support (for example, processing, displaying, and scaling bitmaps and JPEGs).
  • Direct3D is the low-level API through which all the graphics in a WPF are rendered.
  • User32 is used to determine what program gets what real estate. As a result, it’s still involved in WPF, but it plays no part in rendering common controls.
The Class Hierarchy
Figure shows a basic overview with some of the key branches of the class hierarchy:
Figure : The fundamental classes of WPF

Windows Presentation Foundation (WPF)

The Windows Presentation Foundation (WPF) is an entirely new graphical display system for Windows. WPF is designed for .NET, influenced by modern display technologies such as HTML and Flash, and hardware-accelerated. It’s also the most radical change to hit Windows user interfaces since Windows 95.

A standard Windows application relies on two well-worn parts of the Windows operating system to create its user interface:
User32 provides the familiar Windows look and feel for elements such as windows, buttons, text boxes, and so on.
GDI/GDI+ provides drawing support for rendering shapes, text, and images at the cost of additional complexity (and often lackluster performance).

The new frameworks simply deliver better wrappers for interacting with User32 and GDI/GDI+. It can provide improvements in efficiency, reduce complexity, and add pre-baked features so you don’t have to code them yourself; but they can’t remove the fundamental limitations of a system component that was designed more than a decade ago.

DirectX: The New Graphics Engine
Microsoft created one way around the limitations of the User32 and GDI/GDI+ libraries: DirectX. Its design mandate was speed, and so Microsoft worked closely with video card vendors to give DirectX the hardware acceleration needed for complex textures, special effects such as partial transparency, and three-dimensional graphics.
In WPF, the underlying graphics technology isn’t GDI/GDI+. Instead, it’s DirectX. Remarkably, WPF applications use DirectX no matter what type of user interface you create. As a result, even the most mundane business applications can use rich effects such as transparency and anti-aliasing. You also benefit from hardware acceleration, which simply means DirectX hands off as much work as possible to the GPU (graphics processing unit), which is the dedicated processor on the video card.

Note:
• DirectX is more efficient because it understands higher-level ingredients such as textures and gradients, which can be rendered directly by the video card. GDI/GDI+ doesn’t, so it needs to convert them to pixel-by-pixel instructions, which are rendered much more slowly by modern video cards.
• The goal of WPF is to offload as much of the work as possible on the video card so that complex graphics routines are render-bound (limited by the GPU) rather than processor-bound (limited by your computer’s CPU). That way, you keep the CPU free for other work, you make the best use of your video card, and you are able to take advantage of performance increases in newer video cards as they become available.
WPF TIERS
Video cards differ significantly. When WPF assesses a video card, it considers a number of factors, including the amount of RAM on the video card, support for pixel shaders (built-in routines that calculate per-pixel
effects such as transparency), and support for vertex shaders (built-in routines that calculate values at the vertexes of a triangle, such as the shading of a 3-D object). Based on these details, it assigns a rendering tier value.
WPF recognizes three rendering tiers. They are as follows:
Rendering Tier 0. The video card will not provide any hardware acceleration. This corresponds to a DirectX version level of less than 7.0.
Rendering Tier 1. The video card can provide partial hardware acceleration. This corresponds to a DirectX version level greater than 7.0 but less than 9.0.
Rendering Tier 2. All features that can be hardware accelerated will be. This corresponds to a DirectX version level greater than or equal to 9.0.