Pages

Friday, November 2, 2012

Dependency Injection


First, let’s examine the idea of dependency injection by walking through a simple example. Let’s say you’re writing the next blockbuster game, where noble warriors do battle for great glory. First, we’ll need a weapon suitable for arming our warriors.
class Sword 
{
    public void Hit(string target)
    {
        Console.WriteLine("Chopped {0} clean in half", target);
    }
}
Then, let’s create a class to represent our warriors themselves. In order to attack its foes, the warrior will need an Attack() method. When this method is called, it should use its Sword to strike its opponent.
class Samurai
{
    readonly Sword sword;
    public Samurai() 
    {
        this.sword = new Sword();
    }

    public void Attack(string target)
    {
        this.sword.Hit(target);
    }
}
Now, we can create our Samurai and do battle!
class Program
{
    public static void Main() 
    {
        var warrior = new Samurai();
        warrior.Attack("the evildoers");
    }
}
As you might imagine, this will print Chopped the evildoers clean in half to the console. This works just fine, but what if we wanted to arm our Samurai with another weapon? Since the Sword is created inside the Samurai class’s constructor, we have to modify the implementation of the class in order to make this change.
When a class is dependent on a concrete dependency, it is said to be tightly coupled to that class. In this example, the Samurai class is tightly coupled to the Sword class. When classes are tightly coupled, they cannot be interchanged without altering their implementation. In order to avoid tightly coupling classes, we can use interfaces to provide a level of indirection. Let’s create an interface to represent a weapon in our game.
interface IWeapon
{
    void Hit(string target);
}
Then, our Sword class can implement this interface:
class Sword : IWeapon
{
    public void Hit(string target) 
    {
        Console.WriteLine("Chopped {0} clean in half", target);
    }
}
And we can alter our Samurai class:
class Samurai
{
    readonly IWeapon weapon;
    public Samurai() 
    {
        this.weapon = new Sword();
    }

    public void Attack(string target) 
    {
        this.weapon.Hit(target);
    }
}
Now our Samurai can be armed with different weapons. But wait! The Sword is still created inside the constructor of Samurai. Since we still need to alter the implementation of Samurai in order to give our warrior another weapon, Samurai is still tightly coupled to Sword.
Fortunately, there is an easy solution. Rather than creating the Sword from within the constructor of Samurai, we can expose it as a parameter of the constructor instead.
class Samurai
{
    readonly IWeapon weapon;
    public Samurai(IWeapon weapon) 
    {
        this.weapon = weapon;
    }

    public void Attack(string target) 
    {
        this.weapon.Hit(target);
    }
}
Then, to arm our warrior, we can inject the Sword via the Samurai ‘s constructor. This is an example of dependency injection (specifically, constructor injection). Let’s create another weapon that our Samurai could use:
class Shuriken : IWeapon
{
    public void Hit(string target)
    {
        Console.WriteLine("Pierced {0}'s armor", target);
    }
}
Now, we can create an army of warriors:
class Program
{
    public static void Main() 
    {
        var warrior1 = new Samurai(new Shuriken());
        var warrior2 = new Samurai(new Sword());
        warrior1.Attack("the evildoers");
        warrior2.Attack("the evildoers");
    }
}
This results in the following output to be printed to the console:
Pierced the evildoers armor.
Chopped the evildoers clean in half.
This is called dependency injection by hand, because each time you want to create a Samurai, you must first create some implementation of IWeapon and then pass it to the constructor of Samurai. Now that we can change the weapon the Samurai uses without having to modify its implementation, the Samurai class could be in a separate assembly from Sword – in fact, we can create new weapons without needing the source code of the Samurai class!
Dependency injection by hand is an effective strategy for small projects, but as your application grows in size and complexity, it becomes more and more cumbersome to wire all of your objects up. What happens when the dependencies have dependencies of their own? What happens when you want to add a (e.g. caching, tracing to a log, auditing etc.) decorator in front of each instance of a given dependency? You can easily end up spending most of your time creating and wiring together objects, when you could be writing code that adds real value to your software. This is where dependency injection libraries / frameworks like Ninject can help.

Ref:- Here


For Eg:-
 class Client
    {
        static void Main(string[] args)
        {
            var con1 = new Assembly(new SQLConnection());
            Console.Write(con1.WriteConnection() + "\n" );
            var con2 = new Assembly(new MySQLConnection());
            Console.Write(con2.WriteConnection() + "\n");
            var oracle = new Assembly(new OracleConnection());
            Console.Write(oracle.WriteConnection());
            Console.Read();
        }
    }

    public interface IConnection
    {
        string GetConnection(string con);
    }

    public class SQLConnection : IConnection
    {
        public string GetConnection(string conn)
        {
            return conn;
        }
    }

    public class MySQLConnection : IConnection
    {
        public string GetConnection(string conn)
        {
            return conn;
        }
    }

    public class OracleConnection : IConnection
    {
        public string GetConnection(string con)
        {
            return con;
        }
    }


    //This is a assembly which will be loosely coupled in spite of any connection
    public class Assembly
    {
        readonly IConnection objCon;
       //We inject connection in constructor
        public Assembly(IConnection conn)
        {
            this.objCon = conn;
        }

        public string WriteConnection()
        {
            return this.objCon.GetConnection(this.objCon.ToString());
        }
    }
Thanks,
Amit

Thursday, July 5, 2012

Apple push notification in c#

Apple push notification in c#


P12 Certificate:-Apple requires that each organization maintain their own certificate to ensure a secure mechanism for their corporate devices to communicate across Apple’s push notification messaging network.
For now we have created our development certificate and placed it on p12 File folder on server.

Ref URL:- http://arashnorouzi.wordpress.com/2011/04/01/sending-apple-push-notifications-in-asp-net-%E2%80%93-part-2-generating-apns-certificates/


Device Token:- Device Token is required.

Message:- Notification Message.

We have used the following code for development of APNS as reference

Sample code Download Link
http://arashnorouzi.wordpress.com/2011/06/
https://github.com/arashnorouzi/Moon-APNS

Monday, March 19, 2012

LightBox problem with Internet Explorer


Its usually find that Lightbox create some problems with IE. Recently i was working in lightbox and faced the same problem. Lightbox gallery work fine in every browser except IE. After some Googling i found the following solution to the problem.

First:-

Put all the javascript Ref at the bottom of the web page but before closing tag i.e </body>
instead of head tag.

Code snippet:

<body>
<div>HTML data<div>
<div>HTML data<div>
<div>HTML data<div>
   <script src="/lib/jquery-1.6.2.min.js" type="text/javascript"></script>
    <script src="/lib/jquery.jcarousel.js" type="text/javascript"></script>  
</body>

Second:-

Call jquery noconflict method to remove confliction between jquery libraries. Have a look at below piece of code.

Code snippet:

<body>
<div>HTML data<div>
<div>HTML data<div>
<div>HTML data<div>
   <script src="/lib/jquery-1.6.2.min.js" type="text/javascript"></script>
    jQuery.noConflict()   
    <script src="/lib/jquery.jcarousel.js" type="text/javascript"></script>  
</body>

Above ways help me to solve the lightbox problem in IE.
Hope it will be helpful for you all.

Thanks,
Amit

Sunday, February 12, 2012

AJAX in Javascript


What is AJAX?

AJAX = Asynchronous JavaScript and XML.

AJAX is a technique for creating fast and dynamic web pages.

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.

Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

The XMLHttpRequest Object

All modern browsers support the XMLHttpRequest object (IE5 and IE6 use an ActiveXObject).

The XMLHttpRequest object is used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Create an XMLHttpRequest Object

All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:
variable=new XMLHttpRequest();

Old versions of Internet Explorer (IE5 and IE6) uses an ActiveX Object:
variable=new ActiveXObject("Microsoft.XMLHTTP");

To handle all modern browsers, including IE5 and IE6, check if the browser supports the XMLHttpRequest object. If it does, create an XMLHttpRequest object, if not, create an ActiveXObject:
Example
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

Send a Request To a Server

To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();

Method     Description
open(method,url,async)     Specifies the type of request, the URL, and if the request should be handled asynchronously or not.

method: the type of request: GET or POST
url: the location of the file on the server
async: true (asynchronous) or false (synchronous)
send(string)     Sends the request off to the server.

string: Only used for POST requests

GET or POST?

GET is simpler and faster than POST, and can be used in most cases.

However, always use POST requests when:

    A cached file is not an option (update a file or database on the server)
    Sending a large amount of data to the server (POST has no size limitations)
    Sending user input (which can contain unknown characters), POST is more robust and secure than GET

GET Requests

A simple GET request:
Example
xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();

Try it yourself »

In the example above, you may get a cached result.

To avoid this, add a unique ID to the URL:
Example
xmlhttp.open("GET","demo_get.asp?t=" + Math.random(),true);
xmlhttp.send();


Server Response

To get the response from a server, use the responseText or responseXML property of the XMLHttpRequest object.
Property     Description
responseText     get the response data as a string
responseXML     get the response data as XML data

The responseText Property

If the response from the server is not XML, use the responseText property.

The responseText property returns the response as a string, and you can use it accordingly:
Example
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

Try it yourself »

The responseXML Property

If the response from the server is XML, and you want to parse it as an XML object, use the responseXML property:
Example

xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length;i++)
  {
  txt=txt + x[i].childNodes[0].nodeValue + "<br />";
  }
document.getElementById("myDiv").innerHTML=txt;

Sunday, February 5, 2012

How to add Users for databases on Sql Server 2008

How to add Users for databases on Sql Server 2008

Following are the steps for adding users on Sql server.

Step:1
Got to Security-> Logins on server.

Step: 2
Right click on Logins. Add Login name and select SQL Server authentication. Set password and Confirm password.
Unchecked Enforce password expiration option.

Step: 3
Go to Server Roles and select public option

Step: 4
Go to User Mapping and select Db_Owner, Public  Option and mapped it with database from databases.

After following the above steps you will find recently added user will be automatically added on the database.

Tuesday, January 24, 2012

Custom ViewEngine in MVC


When application start in MVC, framework first look for view in views folder. If its unable to find there then it will go for shared folder. If its still unable to find view over there then it will throw an error. By default MVC firstly look into views folder then shared folder.
Like this we can also create our own custom folder and give functionality to look on that folder too. MVC provide a class under framework "WebFormViewEngine" which is responsbile for finding views.
In order to set custom folder functionality first create a folder in Views folder then override a method "FindView" which is provided in WebFormViewEngine.

The first thing we are going to do to create our custom ViewEngine, is define the paths that we want to use for our master pages, view pages, and shared pages.


 //Master Pages:
 ~/Templates
 it use to be ~/Views/Shared or the controllers view
 //View Pages:
 ~/Views
 //Shared Pages:
 ~/Common
 it use to be ~/Views/Shared

public SimpleViewEngine ()
{
 /* {0} = view name or master page name
 * {1} = controller name
 */
 // create our master page location
 MasterLocationFormats = new[] {
 "~/Templates/{0}.master"
} //create our views and common shared locations ViewLocationFormats = new[] { "~/Views/{1}/{0}.aspx", "~/Common/{0}.aspx", }; //create our partial views and common shared locations PartialViewLocationFormats = new[] { "~/Views/{1}/{0}.ascx", "~/Common/{0}.ascx" }; } //Global.asax, similar to the same way we register new routes. public static void RegisterViewEngines(ViewEngineCollection viewEngines) { viewEngines.Clear(); viewEngines.Add(new SimpleViewEngine()); } public static void RegisterRoutes(RouteCollection routes) { ... } protected void Application_Start() { RegisterRoutes(RouteTable.Routes); RegisterViewEngines(ViewEngines.Engines); }

Calculator for adding dynamic numbers in javascript

Problem:- Genrate dynamic textboxes for adding dynamic numbers. If user entered three in textbox than genrate three textboxes and add values entered in that textboxes by user. Below is the code in javascript for solving problem.
This calculator can add two-digit numbers and display the result. First enter how many numbers you want to enter and press Change button. Then enter your numbers in the table and press Recalculate. Any blank or non-numeric input would be skipped while adding the numbers



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Javascript Calculator</title>
</head>
<body>
    This calculator can add two-digit numbers and display the result. First enter how
    many numbers you want to enter and press Change button. Then enter your numbers
    in the table and press Recalculate. Any blank or non-numeric input would be skipped
    while adding the numbers.<br />
    <br />
    <br />
    Number of Rows:
    <input type="text" id="NumberToAdd" value="" style="width: 30px" maxlength="2">&nbsp;&nbsp;<input
        type="button" value='Change' onclick="javascript:NumberToAdd(this) " />
    <br />
    <br />
    <table cellspacing="0" cellpadding="4" id="tblID">
    </table>
    <input type="button" value='Recalculate Sum' onclick="javascript:AddTotal()" />
</body>
</html>
<script language="javascript" type="text/javascript">

    //function Get the input from user for total number to be add
    function NumberToAdd() {
        //Clear existing HTML
        DeleteAllRows();
        //Get total numbers of rows dynimcally add
        var totalNumber = document.getElementById("NumberToAdd").value;
        if (totalNumber != null) {
            //Genrate rows as per input given by user i.e 'totalNumber'
            for (var i = 1; i <= totalNumber; i++) {
                addRow("tblID", i);
            }
        }
        return false;
    }

    //Remove all existing rows
    function DeleteAllRows() {
        var table = document.getElementById('tblID');
        var rows = table.rows;
        while (rows.length)
            table.deleteRow(rows.length - 1);
    }

    //function adding row at runtime
    function addRow(tableID, i) {
        //Get table object
        var table = document.getElementById(tableID);
        //Find total numbers of rows
        var rowCount = table.rows.length;
        //Add row count to table
        var row = table.insertRow(rowCount);

        //Add Label to first cell of row
        var cell1 = row.insertCell(0);
        var element1 = document.createElement("label");
        element1.type = "label";
        element1.innerHTML = "Number" + i;
        cell1.appendChild(element1);

        //Add Input control to second cell of row
        var cell2 = row.insertCell(1);
        var element2 = document.createElement("input");
        element2.id = "number" + i;
        element2.type = "text";
        element2.maxlength = "2";
        cell2.appendChild(element2);
    }

    //function Adding the number as per rows data added at runtime
    function AddTotal() {
        var total = 0;
        var totalNumber = document.getElementById("NumberToAdd").value;
        for (var i = 1; i <= totalNumber; i++) {
            if (document.getElementById("number" + i).value != "" && (parseInt(document.getElementById("number" + i).value)).toString() != "NaN")
                total = parseInt(total) + parseInt(document.getElementById("number" + i).value);
        }

        //Check weather Result element exist
        if (document.getElementById("result") == null) {
            //Adding row to show add total result
            var table = document.getElementById("tblID");
            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);
            row.id = "result";

            //Add Label to first cell of row
            var cell1 = row.insertCell(0);
            var element1 = document.createElement("label");
            element1.type = "label";
            element1.innerHTML = "TOTAL";
            cell1.appendChild(element1);

            //Add Input control to second cell of row
            var cell2 = row.insertCell(1);
            var element2 = document.createElement("label");
            element2.id = "resultCell";
            element2.type = "label";
            element2.innerHTML = total;
            cell2.appendChild(element2);
        }
        //if result element exist then override the result
        else
            document.getElementById("resultCell").innerHTML = total;
    }


</script>

Thursday, January 19, 2012

.NET Framework

The Microsoft .NET Framework is a software framework that can be installed on computers running Microsoft Windows operating systems.

It includes a large library of coded solutions to common programming problems and a common language infrastructure that manages the execution of programs written specifically for the framework.

The .NET Framework supports several programming languages which allows language interoperability, whereby each language can utilize code written in other languages; in particular, the .NET library is available to all the programming languages that .NET encompasses.

The framework's Base Class Library provides

user interface
data access
database connectivity
cryptography
web application development
numeric algorithms
network communications

The class library is used by programmers, who combine it with their own code to produce applications.



Programs written for the .NET Framework execute in a software environment that manages the program's runtime requirements. Also part of the .NET Framework, this runtime environment is known as the Common Language Runtime (CLR). The CLR provides the appearance of an application virtual machine so that programmers need not consider the capabilities of the specific CPU that will execute the program.

The CLR also provides other important services such as

security
memory management
exception handling

The class library and the CLR together constitute the .NET Framework. In other words, from a programmer's point of view, .NET can be understood as a runtime environment and a comprehensive base class library.

The primary role of the CLR is to locate, load, and manage .NET types on your behalf. The CLR also takes care of a number of low-level details such as memory management; creating application domains, threads, and object context boundaries; and performing various checks.

Another building block of the .NET platform is the Common Type System (CTS). The CTS specification fully describes all possible data types and programming constructs supported by the runtime, specifies how these entities can interacts each other, and details how they are represented in the .NET metadata format.

Understand that a given .NET-aware language might not support each and every feature defined by the CTS. The Common Language Specification (CLS) is related specification that defines a subset of common types and programming constructs that all .NET programming languages can agree on. Thus, if we build .NET types that only expose CLS-compliant features, we can rest assured that all .NET-aware languages can consume them. Conversely, if we make use of a data type or programming construct that is outside of the bounds of the CLS, we cannot guarantee that every .NET programming language can interact with our .NET code library.


Base Class Libraries


In addition to the CLR and CTS/CLS specifications, the .NET platform provides a base class library that is available to all .NET programming languages. Not only does this base class library encapsulate various primitives such as threads, file input/output (I/O), graphical rendering, and interaction with various external hardware devices, but it also provides support for a number of services required by most real-world applications.




C# and .NET Framework
C#'s core syntax looks very similar to the syntax of Java. Both C# and Java are members of the C family of programming languages. C# is a cleaned-up version of Java as Java is a cleaned-up version of C++.

C# has adopted a number of constructs traditionally found in various functional languages such as LISP or Haskell. Furthermore, with the advent of LINQ, C# supports a number of programming constructs that make it quite unique in the programming landscape.

Here are core C# features:

No pointers required! C# programs typically have no need for direct pointer manipulation.
Automatic memory management through garbage collection. C# does not support delete keyword.
Formal syntactic constructs for classes, interfaces, structures, enumerations, and delegates.
The C++-like ability to overload operators for a custom type, without the complexity such as making sure to return *this to allow chaining is not your problem.
Support for attribute-based programming. This brand of development allows us to annotate types and their members to further qualify their behavior.
The ability to build generic types and generic members. Using generics, we are able to build very efficient and type-safe code that defines numerous placeholders specified at the time we interact with the generic item.
Support for anonymous methods, which allow us to supply an inline function anywhere a delegate type is required.
Numerous simplifications to the delegate/event method model, including covariance, contravariance, and method group conversion.
The ability to define a single type across multiple code files using partial keyword.
Support for strongly typed queries (LINQ - Language Integrated Query) used to interact with various forms of data.
Support for anonymous types, which allow us to model the shape of a type rather than its behavior.
The ability to extend the functionality of an existing type using extension methods.
Inclusion of a lambda operator (=>), which even further simplifies working with .NET delegate types.
A new object initialization syntax, which allows us to set property values at the time of object creation.

The most important point to understand about the C# is that it can only produce code that can execute within the .NET runtime. We could never use C# to build a native COM server or an unmanaged WIN32 API specification.

The term used to describe the code targeting the .NET runtime is managed code. The binary unit that contains the managed code is termed an assembly. Conversely, code that cannot be directly hosted by the .NET runtime is termed unmanaged code.


.NET Features

Interoperability
Because computer systems commonly require interaction between new and older applications, the .NET Framework provides means to access functionality that is implemented in programs that execute outside the .NET environment. Access to COM components is provided in the System.Runtime.InteropServices and System.EnterpriseServices namespaces of the framework; access to other functionality is provided using the P/Invoke feature.


Common Runtime Engine

The Common Language Runtime (CLR) is the execution engine of the .NET Framework. All .NET programs execute under the supervision of the CLR, guaranteeing certain properties and behaviors in the areas of memory management, security, and exception handling.


Language Independence
The .NET Framework introduces a Common Type System, or CTS. The CTS specification defines all possible data types and programming constructs supported by the CLR and how they may or may not interact with each other conforming to the Common Language Infrastructure (CLI) specification. Because of this feature, the .NET Framework supports the exchange of types and object instances between libraries and applications written using any conforming .NET language.


Base Class Library

The Base Class Library (BCL), part of the Framework Class Library (FCL), is a library of functionality available to all languages using the .NET Framework. The BCL provides classes which encapsulate a number of common functions, including file reading and writing, graphic rendering, database interaction, XML document manipulation and so on.


Simplified Deployment
The .NET Framework includes design features and tools that help manage the installation of computer software to ensure that it does not interfere with previously installed software, and that it conforms to security requirements.


Security
The design is meant to address some of the vulnerabilities, such as buffer overflows, that have been exploited by malicious software. Additionally, .NET provides a common security model for all applications.


Portability
The design of the .NET Framework allows it to theoretically be platform agnostic, and thus cross-platform compatible. That is, a program written to use the framework should run without change on any type of system for which the framework is implemented. While Microsoft has never implemented the full framework on any system except Microsoft Windows, the framework is engineered to be platform agnostic, and cross-platform implementations are available for other operating systems.
Microsoft submitted the specifications for the Common Language Infrastructure (which includes the core class libraries, Common Type System, and the Common Intermediate Language), the C# language, and the C++/CLI language to both ECMA and the ISO, making them available as open standards. This makes it possible for third parties to create compatible implementations of the framework and its languages on other platforms.



.NET-Aware Programming Languages

In addition to the five languages that shipped with the .NET Framework SDK 3.5 (C#, Visual Basic.NET, j#, C++/CLI, and JScript.NET), there are .NET compilers for Smalltalk, COBOL, and Pascal.


.NET Assembly

Regardless of which .NET languages we choose, we need to understand that despite the fact that .NET binaries take the same file extension as COM servers and unmanaged Win32 binaries (*.dll or *.exe), they have absolutely no internal similarities. For instance, *.dll .NET binaries do not export methods to facilitate communications with the COM runtime (given that .NET is not COM). Furthermore, .NET binaries are not described using COM type libraries and are not registered into the system registry.

Perhaps most important, .NET binaries do not contain platform specific instructions, but rather platform-agnostic intermediate language (IL) and type metadata.

(note) IL (Intermediate Language), CIL (Common Intermediate Language), and MSIL (Microsoft Intermediate Language) are all describing the same thing.


assembly

When a *.dll or *.exe has been created using a .NET-aware compiler, the resulting module is bundled into an assembly.

An assembly contains CIL code, which is conceptually similar to Java bytecode in that is not compiled into platform specific instructions until absolutely necessary such as CIL is referenced for use by the .NET runtime.

The CIL code is housed in .NET assemblies. As mandated by specification, assemblies are stored in the Portable Executable (PE) format, common on the Windows platform for all dll and exe files.

In addition to CIL instructions, assemblies also contain metadata that describes the characteristics of every type within the binary. In other words, all CIL is self-describing through .NET metadata. The CLR checks the metadata to ensure that the correct method is called. Metadata is usually generated by language compilers but developers can create their own metadata through custom attributes. Metadata contains information about the assembly, and is also used to implement the reflective programming capabilities of .NET Framework.

For instance, if we have a class names Circle, the type metadata describes details such as its baseclass Shape, which interfaces are implemented by Circle, as well as a full description of each member supported by the Circle.

.NET metadata is a dramatic improvement to COM type metadata. COM binaries are typically described using an associated type library (which is little more than a binary version of Interface Definition Language (IDL) code). The problem with COM type information are that it is not guaranteed to be present and the fact the IDL code has no way to document the externally referenced servers that are required for the correct operation of the current COM server. In contrast, .NET metadata is always present and is automatically generated by a given .NET aware compilers.

assembly2

In addition to CIL and type metadata, assemblies themselves are also described using metadata, which is officially termed a manifest. The manifest contains information about the current version of the assembly, culture information (used for localizing string and image resources), and a list of all externally referenced assemblies that are required for proper execution.


Benefits of CIL (Common Intermediate Language)

What is gained by compiling source code into CIL rather than directly to a specific instruction set?
One benefit is language integration. Since each .NET-aware compiler produces nearly identical CIL instructions, all languages are able to interact within a well-defined binary arena.

Given that CIL is platform-agnostic, the .NET Framework itself is platform-agnostic, providing the same benefits Java developers have accustomed to: single code base running on several OS. Actually, there is an international standard for the C# language, and a large subset of the .NET platform and implementation already exist for many non-Windows OS.

(note) IL (Intermediate Language), CIL (Common Intermediate Language), and MSIL (Microsoft Intermediate Language) are all describing the same thing.


CIL Compile to Platform-Specific Instructions

Since assemblies contain CIL instructions, rather than platform-specific instructions, CIL code must be compiled on the fly before use. The entity that compiles CIL code into meaningful CPU instructions is termed a just-in-time (JIT) compiler, which sometimes referred as Jitter. The .NET runtime environment leverages a JIT compiler for each CPU targeting the runtime, each optimized for the underlying platform.

As a given Jitter compiles CIL instructions into corresponding machine code, it will cache the results in memory in a manner suited to the target OS. In this way, if a call is made to a method named PrintDocument(), the CIL instructions are compiled into platform-specific instructions on the first invocation and retained in memory for later use. Therefore, the next time PrintDocument() is called, there is no need to recompile the CIL.


.NET Metadata

In addition to CIL instructions, a .NET assembly contains metadata. It describes each and every type (class, structure, enumeration, etc.) defined in the binary, as well as the members of each type (properties, methods, events, etc.). It is always the job of the compiler (not the programmer) to emit the latest type metadata. Because .NET metadata is so meticulous, assemblies are completely self-describing entities.

Metadata is used by numerous aspects of the .NET runtime environment, as well as by various development tools. For instance, the IntelliSense feature provided by tools such as Visual Studio is made possible by reading an assembly's metadata at design time. Metadata is also used by various object browsing utilities, debugging tools, and the C# compiler itself. To be sure, metadata is the backbone of numerous .NET technologies including Windows Communication Foundation (WCF), XML web services, the .NET remoting layer, reflection, late binding, and object serialization.


.NET Common Language Runtime (CLR)

Programmatically speaking, the term runtime can be understood as a collection of external services that are required to execute a given compiled unit of code. For example, when developers are using the MFC to create a new application, they are aware that their code requires the MFC runtime library (i.e. mfc42.dll). Other languages also have a corresponding runtime. VB6 codes are ties to a runtime module or two such as msvbvm60.dll. Java codes are tied to the Java Virtual Machine (JVM).

The .NET platform offers yet another runtime system. The key difference between the .NET runtime and the various other runtimes is the fact that the .NET runtime provides a single well-defined runtime layer that is shared by all languages and platforms that are .NET-aware.

The crux of the CLR is physically represented by a library called mscoree.dll (the Common Object Runtime Execution Engine). When an assembly is referenced for use, mscoree.dll is loaded automatically, which in turn loads the required assembly into memory. The runtime engine is responsible for a number of tasks. First, it is the entity in charge of resolving the location of an assembly and finding the requested type within the binary by reading the contained metadata. The CLR then lays out the type in memory, compiles the associated CIL into platform-specific instructions, performs any necessary security checks, and then executes the code.

In addition to loading our custom assemblies and creating custom types, the CLR will also interact with the types contained within the .NET base class libraries when required. Although the entire base class library has been broken into a number of discrete assemblies, the key assembly is mscorlib.dll. It contains a large number of core types that encapsulate a wide variety of common programming tasks as well as the core data types used by all .NET languages. When we build .NET solution, we automatically have access to this particular assembly.




.NET ildasm.exe (Intermediate Language Disassembler) Utility

ildasm1

Intermediate Language Disassembler utility (ildasm.exe), which ships with the .NET Framework 3.5 SDK, allows us to load up any .NET assembly and investigate its contents including the associated manifest, CIL code, and any type metadata.

To load (ildasm.exe): open a Visual Studio command prompt -> type ildasm -> Enter.

Then, proceed to the File -> Open menu command -> Navigate to an assembly to explore.

Here is the CIL code for the above project. ildasm.exe allows us to see CIL code.
CIL1

In addition to showing the namespaces, types, and members contained in a given assembly, (ildasm.exe) also allows us to view the CIL instructions for a given member. For instance, if we double-click the Main() method of the Program class of the CIL code, a separate window would display the underlying CIL.
CIL2

We can also view the type metadata for the currently loaded assembly by pressing Ctrl+M.
Metadata

Finally, we can view the contents of the assembly's manifest, simply double-click the MANIFEST icon.
Manifest




Platform-Independent .NET

.NET assemblies can be developed and executed on non-Microsoft OS (Mac OS X, Linux, and Solaris) thanks to CLI (Common Language Infrastructure).




CLI (Common Language Infrastructure)

Every programming language has a set of intrinsic type representing such object as integers, floating point numbers, characters, etc. Typically the characteristics of these types vary from one language to another and from platform to platform.

However, this lack of uniformity makes it difficult if we want programs to play well with other programs and libraries written in different languages. So, there must be a set of standards.

The Common Language Infrastructure (CLI) is a set of standards that ties all component of the .NET framework into a cohesive and consistent system. It lays out the concepts and architecture of the system and specifies the rules and convention to which all the software must adhere.

Both the CLI and C# have been approved as open international standard specifications by ECMA International.

Although most programmers don't need to know the details of the CLI specifications, we should at least be familiar with the meaning and purpose of the Common Type System and Common Language Specification.

Common Type System (CTS)
The Common Type System (CTS) defines the characteristics of the types that must be used in managed code. Some important aspect of the CTS are the following:
The CTS defines a rich set of intrinsic types, with fixed, specific characteristics for each type.
The types provided by a .NET-compliant programming language generally map to some specific subset of this defined set of intrinsic types.
One of the most important characteristics of the CTS is that all types are derived from a common base class - object.

Common Language Specification (CLS)
The Common Language Specification (CLS) specifies the rules, properties, and behaviors of a .NET-compliant programming language.