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.

Tuesday, January 31, 2012

Command Redirection

Redirection is a function common to most command-line interpreters, that can redirect standard streams to user-specified locations. The input or output stream location is referred to as a handle.
Definition: Redirection is the switching of a standard stream of data so that it comes from a source other than its default source or or that it goes to some destination other than its default destination.
standard streams for input, output, and error
Redirection operatorDescription
>Writes the command output to a file or a device, such as a printer, instead of the Command Prompt window.
<Reads the command input from a file, instead of reading input from the keyboard.
>>Appends the command output to the end of a file without deleting the information that is already in the file.
>&Writes the output from one handle to the input of another handle.
<&Reads the input from one handle and writes it to the output of another handle.
|Reads the output from one command and writes it to the input of another command. Also known as a pipe.
The following table lists the available handles:
HandleNumeric equivalentDescription
STDIN0Keyboard input
STDOUT1Output to the Command Prompt window
STDERR2Error output to the Command Prompt window
UNDEFINED3-9These handles are defined individually by the application and are specific to each tool.
The numbers zero through nine (that is, 0-9) represent the first 10 handles. You can use Cmd.exe to run a program and redirect any of the first 10 handles for the program. To specify which handle you want to use, type the number of the handle before the redirection operator. If you do not define a handle, the default < redirection input operator is zero (0) and the default > redirection output operator is one (1). After you type the < or > operator, you must specify where you want to read or write the data. You can specify a file name or another existing handle.
To specify redirection to existing handles, use the ampersand (&) character followed by the handle number that you want to redirect (that is, &handle#). For example, the following command redirects handle 2 (that is, STDERR) into handle 1 (that is, STDOUT): 1<&2
Duplicating handles:
command 2> filenameRedirect any error message into a file
command 2>> filenameAppend any error message into a file
(command) 2> filenameRedirect any CMD.exe error into a file
command > file 2>&1Redirect errors and output to one file
command > file 2<&1Redirect output and errors to one file
command > fileA 2> fileBRedirect output and errors to separate files
command 2>&1 > filenameThis will fail!
Redirect to NUL (hide errors):
command 2> nulRedirect error messages to NUL
command >nul 2>&1Redirect error and output to NUL
command >filename 2> nulRedirect output to file but suppress error
(command) >filename 2> nulRedirect output to file but suppress CMD.exe errors

Note, any long filenames must be surrounded in "double quotes". A CMD error is an error raised by the command processor itself rather than the program/command.

Redirection with > or 2> will overwrite any existing file.

You can also redirect to a printer with > PRN or >LPT1

To prevent the > and < characters from causing redirection, escape with a caret: ^> or ^<


Using the pipe operator (|)
The pipe operator (|) takes the output (by default, STDOUT) of one command and directs it into the input (by default, STDIN) of another command. For example, the following command sorts a directory:
dir | sort
In this example, both commands start simultaneously, but then the sort command pauses until it receives the dir command's output. The sort command uses the dir command's output as its input, and then sends its output to handle 1 (that is, STDOUT).


Examples of redirection:
DIR >MyFileListing.txt
   
   DIR /o:n >"Another list of Files.txt"

   ECHO y| DEL *.txt

   ECHO Some text ^<html tag^> more text
   
   MEM /C >>MemLog.txt

   Date /T >>MemLog.txt

   SORT < MyTextFile.txt

   SET _output=%_missing% 2>nul

   DIR C:\ >List_of_C.txt 2>errorlog.txt
   
   FIND /i "Jones" < names.txt >logfile.txt

   DIR C:\ >List_of_C.txt & DIR D:\ >List_of_D.txt

   ECHO DIR C:\ ^> c:\logfile.txt >NewScript.cmd

   (TYPE logfile.txt >> newfile.txt) 2>nul

Wednesday, January 25, 2012

Concurrent Administrative Operations

Not all administrative tasks are allowed to run concurrently. In the table below, a black circle indicates two operations that cannot run in a database at the same time.
Grid showing tasks that can run concurrently
File shrink operations spend most processing time reallocating pages into areas retained after the shrink has completed; it then attempts to change the file size only as the last step. File shrink operations can be started while a backup is running, provided that the backup finishes before the file shrink operation attempts to change the size of the files.

Source : http://technet.microsoft.com/en-us/library/ms189315.aspx

Tuesday, January 24, 2012

Using Automatic Proxy Configuration

Automatic proxy (auto-proxy) makes system administration easier, because you can automatically configure proxy settings such as server addresses and bypass lists. To configure more advanced settings for auto-proxy, you can create a separate .js, .jvs, or .pac script file and then copy the file to a server location. Then, you can specify the server location for the script file within the Automatic Configuration settings of browser. The auto-proxy script file is executed whenever a network request is made. Within the script, you can configure multiple proxy servers for each protocol type; then, if a proxy server connection fails, browser automatically attempts to connect to another proxy server that you have specified.
PAC File
A proxy auto-config (PAC) file defines how web browsers and other user agents can automatically choose the appropriate proxy server (access method) for fetching a given URL. The Proxy auto-config file format was originally designed by Netscape in 1996 for the Netscape Navigator 2.0 and is a text file that defines at least one JavaScript function, FindProxyForURL(url, host), with two arguments. By convention, the PAC file is normally named proxy.pac.
The JS function syntax: string FindProxyForURL(url, host)
url The full URL being accessed or URL of the object
host The hostname extracted from the URL. This is only for convenience, it is the exact same string as between :// and the first : or / after that. The port number is not included in this parameter. It can be extracted from the URL when necessary.
return value A string describing the configuration. The return value of the function should be a semicolon seperated list of options from the following list:
DIRECT Connections should be made directly, without any proxies.
PROXY host:port The specified proxy should be used.
SOCKS host:port The specified SOCKS server should be used.
A null string is the same as DIRECT. Each option will be tried in turn until one is useable.
To use it, a PAC file is published to a web server, and client user agents are instructed to use it, either by entering the URL in the proxy connection settings of the browser or through the use of the WPAD protocol. Even though most clients will process the script regardless of the MIME type returned in the HTTP request, for the sake of completeness and to maximize compatibility, the web server should be configured to declare the MIME type of this file to be either application/x-ns-proxy-autoconfig or application/x-javascript-config.
Example :
1. function FindProxyForURL(url, host)
{
     if (isPlainHostName(host))
         return "DIRECT";
     else
          return "PROXY proxy:80";
}
2. function FindProxyForURL(url, host)
{
     if (url.substring(0, 5) == "http:")
     {
          return "PROXY proxy:80";
     }
     else if (url.substring(0, 4) == "ftp:")
     {
          return "PROXY fproxy:80";
     }
     else if (url.substring(0, 7) == "gopher:")
     {
          return "PROXY gproxy";
     }
     else if (url.substring(0, 6) == "https:")
     {
          return "PROXY secproxy:8080";
     }
     else
     {
          return "DIRECT";
     }
}
Autoconfigure the Proxy Settings from a Local Copy of the PROXY.PAC File (IE or Netscape) :
To use local copy of PROXY.PAC file, copy the file to some local directory, and point to it.
1. Copy the PROXY.PAC file to the C:\WINDOWS directory, or other directory of your choice.
2. In the browser proxy settings, configure the Automatic Proxy Configuration (Netscape) or Use Automatic Configuration Script (IE) URL to:
Netscape, use: file:///c|/windows/proxy.pac
Internet Explorer, use: file://c:/windows/proxy.pac
In Netscape, click on the Reload button.
The Web Proxy Auto-Discovery Protocol (WPAD)
WPAD is not designed to find the actual proxy settings, but to find the PAC script which tell the browser which settings to use. WPAD uses several methods for finding out location of the PAC script. If the method does not provide information about the port or the path name, then the client should use, as defaults, port 80 and /wpad.dat respectively. The client should not use a default host.