Tuesday, 10 January 2012

Language Fundamentals in VB.NET

Constants &Variables
A variable is a named memory location. They are programming elements that can change during program execution. Data that needs to be stored in memory & accessed at a later time are stored in variables. Instead of referring to the memory location by the actual memory address you refer to it with a variable name.
Variables are declared as follows
Dim a as Integer
  They can also be initialized at the time of declaration as follows:
Dim a as Integer = 10
  Constants are very similar to variables. The main difference is that the value contained in memory cannot be changed once the constant is declared. When you declare a constant its value is also specified and this value cannot be changed during program execution.
   Constants are used in situations where we need to keep the value in some memory location constant. If you use hard-coded values, and the value is changed then it has to be changed in all the locations in the code where it has been used. Instead if we are using constants, all we will need to do is to change the value of the constant. This would propagate the changes to our entire application.
Constants are declared as follows
Const x as Integer
VB.NET supports block-level scoping of variables. That is you can declare and use variables as and when you need them. Thus, if a variable is required within a ‘for’ block it can be declared within the block and its scope will be the end of the block.

Simple Types (Primitive Data types)
Simple or value type variables are those, which are assigned space in the stack instead of the heap. All the primitive types such as int, double etc are value type variables. The simple types basically consist of Boolean and Numeric types, where Numeric is further divided into Integral and Floating Point.
    The first rule of value types is that they cannot be null. Anytime you declare a variable of value type, you have allocated the number of bytes associated with that type on the stack and are working directly with that allocated array of bits. In addition, when you pass a variable of value type, you are passing that variable’s value and not a reference to the underlying object.
Object Type
Object type or reference type variables are those, which are allocated storage space in the heap. Reference type objects can be null. When a reference type is allocated under the covers a value is allocated on the heap and a reference to that value is returned. There are basically four reference types: classes, interfaces, delegates and arrays.
Class Type
Custom data types are available in .NET framework in the form of classes or class type. It is nothing but a set of data and related behavior that is defined by the developer.
   Object type and class type are both reference type variables. The only difference comes from the fact that object type consists of objects predefined and available with the .NET framework such as string whereas class type consists of custom user defined data types such as the Class Employee given below.
 Class Employee
Dim empid As Integer
Dim empname As String
Public Sub New()
empid = 10
empname = "Reshmi"
End Sub
End Class

Overloading and Overriding of the Class
Overloading provides the ability to create multiple methods or properties with the same name, but with different parameters lists. This is a feature of polymorphism. It is accomplished by using the Overloads keyword in VB.NET. A simple example would be an addition function, which will add the numbers if two integer parameters are passed to it and concatenate the strings if two strings are passed to it.
Class test
Public Overloads Function Add(ByVal x As Integer, ByVal y As Integer)
Return x + y
End Function
Public Overloads Function Add(ByVal x As String, ByVal y As String)
Return x & y
End Function
Shared Sub main()
Dim a As new test
Dim b As Integer
Dim c As String
b = a.Add(1, 2)
c = a.Add("Reshmi", " Nair")
System.Console.Writeline(b)
System.Console.Writeline(c)
End Sub
End Class
O/P:
3
Reshmi Nair

Overriding
Class inheritance causes the methods and properties present in the base class also to be derived into the derived class. There might arise a situation wherein you would like to change the functionality of an inherited method or property. In such cases we can override the method or property of the base class. This is another feature of polymorphism. You can accomplish this in VB.NET by using the Overridable keyword with the base class method and the Overrides keyword with the derived class method.
Public Class shapes
Public Overridable Sub display()
Console.WriteLine("Shapes")
End Sub
End Class
Public Class square
Inherits shapes
Public Overrides Sub display()
Console.WriteLine("This is a square")
End Sub
End Class
Public Class rectangle
Inherits shapes
Public Overrides Sub display()
Console.WriteLine("This is a rectangle")
End Sub
End Class
The above example is just an indication to how overriding can be implemented in either VB.NET.

Properties
   Properties are named members of classes, structs, and interfaces. They provide a flexible mechanism to read, write, or compute the values of private fields through accessors.
    Properties are an extension of fields and are accessed using the same syntax. Unlike fields, properties do not designate storage locations. Instead, properties have accessors
that read, write, or compute their values.
Get accessor
The execution of the get accessor is equivalent to reading the value of the field.
The following is a get accessor that returns the value of a private field name:
Dim name as String ’ the name field
Property Name() As String ’ the name property
Get
Return name
End Get
End Property
Set accessor
The set accessor is similar to a method that returns void. It uses an implicit parameter called value, whose type is the type of the property. In the following example, a set accessor is added to the Name property:
Dim name as String ’ the name field
Property Name() As String ’ the name property
Get
Return name
End Get
Set(ByVal Value As String)
Name = value
End Set
End Property
When you assign a value to the property, the set accessor is invoked with an argument that provides the new value. For example:
e1.Name = "Reshmi" // The set accessor is invoked here
It is an error to use the implicit parameter name (value) for a local variable declaration in a set accessor.

How to make a Property Read Only/Write Only
There are times when we may want a property to be read-only – such that it can’t be changed. This is where read-only properties come into the picture. A Read Only property is one which includes only the get accessor, no set accessor.
For instance,
Public ReadOnly Property EmpID() as Integer
Get
Return empid
End Get
End Property
Similar to read-only properties there are also situations where we would need something known as write-only properties. In this case the value can be changed but not retrieved. To create a write-only property, use the WriteOnly keyword and only implement the set block in the code as shown in the example below.
Public WriteOnly Property e as string
Set
e = Value
End Set
End Property
Structures :
   A structure allows you to create your own custom data types and it contains one or more members that can be of different data types. It can contain fields, methods, Etc., Structures are very similar to classes but there are some restrictions present in the case of structures that are absent in the case of classes. For example you cannot initialize structure members. Also you cannot inherit a structure whereas classes can be inherited.
Another important feature of structures differentiating it from classes is that a structure can't have a default parameter-less constructor or a destructor. A structure is created on the stack and dies when you reach the closing brace in C# or the End structure in VB.NET.
   But one of the most important differences between structures and classes is that structures are referenced by value and classes by reference. As a value type, allocated on the stack, structs provide a significant opportunity to increase program efficiency. Objects on the stack are faster to allocate and de-allocate. A struct is a good choice for data-bound objects, which don’t require too much memory. The memory requirements should be considered based on the fact that the size of memory available on the stack is limited than the memory available on the heap.
Thus we must use classes in situations where large objects with lots of logic are required.

Struct – Code: Sample code showing the Class vs. Structures
Imports System
Class Test
Dim classvar As Integer
Dim anothervar As Integer = 20
Sub New()
classvar = 28
End Sub
Structure ExampleStruct
Dim i As Integer
Sub New(ByVal j As Integer)
i = j
End Sub
Sub trialMethod()
Console.WriteLine("Inside Trial Method")
End Sub
End Structure
Shared Sub main()
Dim t As New Test()
Dim strct As New ExampleStruct(20)
Console.WriteLine(strct.i)
strct.i = 10
Console.WriteLine(t.classvar)
Console.WriteLine(strct.i)
strct.trialMethod()
End Sub
End Class
O/P: -
28
20
10
Inside Trial Method
  In the above example, I have declared and used a constructor with a single parameter for a structure. Instead if I had tried to use a default parameter-less parameter I would have got an error. But the same is possible in the case of classes as shown by the default parameter-less constructor, which initializes the classvar variable to 28. Another point to note is that a variable called anothervar has been declared and initialized within the class whereas the same cannot be done for members of a structure.

Why Namespaces
  Namespaces are used in .Net to organize class libraries into a hierarchical structure and reduce conflicts between various identifiers in a program. By helping organize classes, namespaces help programmers manage their projects efficiently and in a meaningful way that is understood by consumers of the class library. Namespaces enables reusable components from different companies to be used in the same program without the worry of ambiguity caused by multiple instances of the same identifier.
   Namespaces provide a logical organization for programs to exist. Starting with a toplevel namespace, sub-namespaces are created to further categorize code, based upon its purpose.
  In .Net, the base class library begins at the System namespace. There are several classes at the System level such as Console, Exception etc. The namespace name gives a good idea of the types of classes that are contained within the namespace. The fully qualified name of a class is the class name prefixed with the namespace name. There are also several nested namespaces within the System namespace such as System.Security, System.IO, System.Data, System.Collections etc.
   Reducing conflict is the greatest strength of namespaces. Class and method names often collide when using multiple libraries. This risk increases as programs get larger and include more third-party tools.
Boxing Conversions
Boxing is the implicit conversion of a value type to a reference type or to any interface type implemented by this value type. This is possible due to the principle of type system unification where everything is an object.
  When boxing occurs, the contents of value type are copied from the stack into the memory allocated on the managed heap. The new reference type created contains a copy of the value type and can be used by other types that expect an object reference. The value contained in the value type and the created reference types are not associated in any way. If you change the original value type, the reference type is not affected. Boxing,
thus, enables everything to appear to be an object, thereby avoiding the overhead required if everything actually were an object.
Example:

VB.NET
Dim n as Integer = 10
Dim obj as Object
obj = n
Explanation:
In the above code segment, a value-type variable n is declared and is assigned the value 10. The next statement declares an object-type variable obj. The last statement implicitly performs boxing operation on the variable n.
UnBoxing Conversions
  UnBoxing is the explicit conversion from a reference type to a value type or from an interface type to a value type that implements the interface.
   When unboxing occurs, memory is copied from the managed heap to the stack. For an unboxing conversion to a given value type to succeed at run time, the value of the source argument must be a reference to an object that was previously created by boxing a value of that value type otherwise an exception is thrown.
   VB.Net does not support the ability to explicitly unbox values. It relies on the helper functions in the Microsoft.VisualBasic.Helpers namespace to carry out unboxing. Since these helper functions are considerably less efficient than C# support for explicit unboxing. Thus it is recommended to avoid excessive use of variables of type Object.
   Boxing and UnBoxing have performance implications. Every time a value type is boxed, a new reference type is created and the value type is copied onto the managed heap. Depending on the size of the value type and the number of times value types are boxed and unboxed, the CLR can spend a lot of CPU cycles just doing these conversions.
It is recommended to perform boxing and unboxing in a scenario where you have to pass a value parameter multiple times to a method that accepts a reference parameter. In such a case, it is advantageous to box the value parameter once before passing it multiple times to methods that accept reference methods.
Enumerations
Enumerations are types that inherit from System.Enum. The elements of an enumeration are expressed in words rather than numbers, which makes it convenient for understanding the meaning of the value being used. Enumerations symbolically represent a set of values of one of the primitive integral types.
The type of the elements of an enumeration can be Byte, Short, Integer or Long. If no type is specified explicitly, the default type is Integer.
Example:
Enum month As Byte
Jan = 2
Feb = 5
Mar = 10
End Enum
Explanation:
In the above code segment, an enumeration type month is declared. The underlying type of the elements has been specified as Byte. It has three elements viz: Jan, Feb and Mar. These three elements have been assigned specific values. In case of an enumeration, if no values are specified, the value of the first element corresponds to 0 and so on.
Delegates
   The runtime supports constructs called delegates, which enable late-bound operations such as method invocation and callback procedures. With delegates, a program can dynamically call different methods at runtime. They are type safe, secure, managed objects that always point to a valid object and cannot corrupt the memory of another object. The closest equivalent of a delegate in other languages is a function pointer, but
whereas a function pointer can only reference Shared functions, a delegate can reference both Shared and instance methods. Delegates are Marshal by Value Objects.
   The members of a delegate are the members inherited from class System.Delegate. A delegate defines the signature and return type of a method. The resulting delegate can reference any method with a matching signature. Each instance of a delegate can forward a call to one or more methods that take those parameters and return the same type. Once a method has been assigned to a delegate, it is called when the delegate is invoked.
Example:
Module delegate_example
Delegate Function calculation(ByVal a As Integer, ByVal b As Integer) As Integer
Public Function add(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
add = num1 + num2
End Function
Sub Main()
Dim calc_delegate As New calculation(AddressOf add)
Dim result As Integer
result = calc_delegate(50, 70)
End Sub
End Module
Explanation:
Four steps are required to implement delegates viz.
• Defining Delegates
The foremost step is to define the delegate. The definition of the delegate specifies the method signature, return type of the method, access modifier and the delegate name. The method signature specifies the order and type of each argument. The definition of a delegate is indicated by the usage of the Delegate keyword. As
shown in the above code segment, the delegate name is calculation, it's access modifier is public, it receives two integer arguments and returns an integer value.
• Creating Delegate Method Handler(s)
The next step is to define the method(s) that will be associated with the delegate. In the above code segment, a method named add is defined. This method must have same method signature as that of the delegate, as shown in the above code segment.
• Hooking up Delegates and Method Handlers
For a delegate method handler to be invoked, it must be assigned to a delegate object. In the above code, the delegate object is calc_delegate and is hooked up to the method handler add.
• Invoking the method through the Delegate
The last step is to invoke the methods that are associated with the delegate. A delegate method handler is invoked by making a method call on the delegate itself. This causes the method handler to invoke with the assigned input parameters as if they were invoked directly by the program, as shown in the above code

History of VB.NET

  .NET framework offers a myriad of languages which puts us programmers into a deep thought process about which programming language best suits our needs.
   Which language is the "best" language choice? If you are a VB wizard, should you take the time to learn C# or continue to use VB.NET? Are C# ASP.NET pages "faster" than VB.NET ASP.NET pages? These are questions that you may find yourself asking, especially when you're just starting to delve into .NET. Fortunately the answer is simple: there is no "best" language. All .NET languages use, at their root, functionality from the set of classes provided by the .NET Framework. Therefore, everything you can do in
VB.NET you can do in C#, and vice-a-versa.
   The differences occur in three main areas: syntax, object-oriented principles, and the Visual Studio .NET IDE. Syntax concerns the statements and language elements. Object Oriented differences are less obvious, and concern differences in implementation and feature sets between the two languages. IDE differences include things like compiler settings or attributes. There is also a fourth area of difference: language features that are present in one language but have no equivalent in the other.
   If you are more familiar with Java, JScript, or C/C++, you may find C#'s syntax more familiar than VB.NET's.
   If you've been doing VB for the past five years, there's no reason to think you have to now switch to a new language (although you should always look to be learning new things).
The fact is that VB.NET has all the facilities of VB such as not being case-sensitive, having the option of using IntelliSense etc in addition to which you have an ocean of new ideas & concepts thrown in for the benefit of programmers.
   VB has matured as a language and if you do not know it already, its almost 11 years since VB was born. It now provides all facilities for distributed computing and Internet programming for which it was not useful earlier. With VB.NET, due to the .NET framework all the classes and all the namespaces available with the other languages are made available to VB also. This is in addition to the drag and drop facility of building
forms and web pages which was always the attraction in the use of VB. Thus it has the dual advantage of ease of use and the availability of advanced features.
   As already stated earlier both VB.NET and C# are equally powerful. So the primary reason for which VB could not reach the zenith of popularity has been eradicated and programmers who have been waiting for OOPs concepts to be incorporated into VB are rewarded with this offering of Microsoft.

Language Features of VB.NET

.NET framework offers a myriad of languages which puts us programmers into a deep thought process about which programming language best suits our needs.

Monday, 9 January 2012

Managed Vs. Unmanaged Methods/Transitions


   In .Net Framework CLR provides execution of instruction targeted for CLR and the instructions that are not targeted for CLR. The instructions targeted for CLR are called as managed code and other type of code is called unmanaged code. After going through this topic you will know the following things mentioned below
   Difference between Managed Method and Unmanaged Method.
   Difference between Managed Type and Unmanaged Type.
   How to call unmanaged methods in managed methods.
   How to use unmanaged types.
  When an application is launched for execution, first request is given to the Operating System, the OS will load the executable file in memory and starts executing the instruction from the entry point function in the executable file. Where in .NET executable file contains four main components the CLR header, the Metadata, the MSIL Code, and Native code.
   CLR header will be used by the managed code in the module which will have the version number of the CLR on which the module is built and entry point method of the module in the executable.
   Metadata describes the types used in the managed code, combination of CLR header and MSIL Code is the compiled format of a .Net language on a .Net Compiler, which will not have the instruction in targeted machine instruction format, which will again get compiled by the JIT Compiler
   Native Code contains the machine instruction, which will be directly executed by the OS. Not all the .NET PE will have the Native code. PE of type EXE’s will be having a native method like main() called as “unmanaged stub” which will be an entry point for the OS to execute code, that function will jump to CorExeMain function located in MSCoree.dll which will be executed by the OS to initialize CLR and attach the running .NET module to CLR. Once CLR is initialized and loaded CLR will start executing the assembly by executing the managed entry point function specified in the CLR header of the file.

Managed Code
Machine instructions in MSIL format and located in Assemblies will be executed by the CLR, will have the following intrinsic advantages,
Memory management to prevent memory leaks in the program code,
• Thread execution,
• Code safety verification,
• Compilation,
Executed on many platforms like Windows 95, Windows 98, Windows 2000,and other system services.
  Managed methods will be marked as “cil” in MSIL code. Methods marked with “cil” will be compiled by mscorjit.dll before execution. C# and VB.NET will generate only managed code. (Managed C++ can generate managed code by specifying “#pragma managed”)

Unmanaged Code
Unmanaged codes are the instructions, which are targeted for specific platforms. Unmanaged code will exist in any of the format, A code instructions in managed C++ with “#pragma unmanaged”
COM/COM+ Components
Win32 Dlls/System Dlls
As these codes are in native format of OS, these instructions will be executed faster compared with JIT compilation and execution of Managed code.

Managed and Unmanaged transitions
  As we get more benefits from managed code, still we may need to use unmanaged code. .Net provides many ways to access unmanaged code in managed code. Managed- Unmanaged transitions are achieved in .Net by set of services called Platform Invocation Services (P/Invoke) and IJW(It Just Works).
   P/Invoke services are targeted for unmanaged code, which exists as COM/COM+ components and Win32 DLLs. COM/COM+ components will accessed by the concept called COM Interop - is a mechanism in which existing COM components will be accessed through a wrapper class called COM Callable Wrapper (CCW) in managed code without modifying the existing COM components. Using P/Invoke mechanism we can call Windows DLL functions in managed code.
IJW(It Just Works) targets code instructions built on C++ managed extensions, This mechanism is only for the code in Managed C++. In this way we can call the unmanaged methods directly by the managed code.
  For example following code calls the MessageBox function in User 2.dll(VB.NET)
Imports System.Runtime.InteropServices
Public Class Win32
Declare Auto Function MessageBox Lib "user32.dll" (ByVal hWnd As Integer, _
ByVal txt As String, ByVal caption As String, ByVal Typ As Integer) As Integer
End Class
Module Module1
Sub Main()
Win32.MessageBox(0, "Hello world" , "Temp path is", 0)
End Sub
End Module
Declare is the statement to state the Win32 API functions located in the Win32 DLLs. And the respective arguments declared with CLR data type.
In C#, we need to use the extern keyword with the attribute DLL Import to specify the Win32 DLL and the function should be declared as static function.
using System;
class PInvokeDemo
{
[dllimport("user32.dll")]
public static extern int MessageBox(int hwnd, string msg, string caption, int type);
public static int Main()
{
MessageBox(0, "Hello World!", "Tutorial", 1);
return 0;
}
}
In the above example MessageBox function is accessed from user32.dll by using the attribute DLL Import, and declared as static function

Managed Types and Unmanaged Types
We have seen how to call an unmanaged code in a managed code, now the question is how unmanaged code understands the managed data type and vice the versa. We will see how string will be sent from managed code and returned back to managed code. When passing a string value as an input argument to an unmanaged code CLR will take care of converting that to a native string type.
When we try to call a function, which returns string then the managed code, has to allocate memory and send to the function in unmanaged code. For example if we want to retrieve the OS Temp path then we can call GetTempPath API function of “kernel32.dll”,
Following code snippet shows how to call the function with string as an out argument with VB.NET.
Imports System.Runtime.InteropServices
Public Class Win32
Declare Auto Function MessageBox Lib
"user32.dll" (ByVal hWnd As Integer, _
ByVal txt As String, ByVal caption As String, ByVal Typ As Integer) As Integer
Declare Auto Function GetTempPath Lib "kernel32.dll"
(ByVal lenOfChar As Integer, ByVal strData As System.Text.StringBuilder) As Integer
End Class
Module Module1
Sub Main()
Dim l As Integer
Dim data As String
Dim tempPath As System.Text.StringBuilder = New System.Text.StringBuilder(255)
l = 255
Win32.GetTempPath(l, tempPath)
Win32.MessageBox(0, tempPath.ToString(), "Temp path is", 0)
End Sub
End Module
Following code snippet shows how to call the function with string as an out
argument with C#.
using System;
using System.Text;
class PInvokeDemo
{
[ dllimport("kernel32") ]
public static extern int GetTempPath ( int size, StringBuilder buf );
public static int Main()
{
const int size = 255;
StringBuilder tempPath = new StringBuilder ( size);
GetTempPath ( size, tempPath );
System.Console.WriteLine ( tempPath );
return 0;
}
}
  The above code uses StringBuilder class of System.Text namespace to allocate string with 255 characters (Just think for this as a fixed string we used to have in VB). Some of the functions in managed code will be accepting arguments as structures, structures in unmanaged code will be having set of member fields located in memory as the order in which it has been declared, that is the layout of member variable location is fixed. But in .Net, structures will have fields of managed data type and these member fields will automatically change the memory location of the structure. CLR will automatically move the data members to improve memory usage and performance. When an unmanaged method, which expects an argument as a structure, then managed
code has to declare the structure so that it can be accessed by the unmanaged code. But .NET structures will have auto memory layout of data members, so to pass structures from managed code to unmanaged code has to be declared with an attribute StructLayout in System.Runtime.InteropServices namespace.
  StructLayout is used with an enumerated value LayoutKind with following options given below:
• Auto – default option which changes the member field memory layout.
• Sequential - specifies member variable should be placed in a sequential order as specified while declaring the type.
• Explicit- specifies the exact location of the member variable in the structure.

JIT (Just–in-Time Compiler) & Debugging


    The .NET Runtime ships with a Just-In-Time (JIT or JITter) compiler, which will convert the MSIL code in to the native code (CPU Specific executable code). So whatever code we write will be complied in to MSIL format and the JIT takes over when you run it.
The .NET runtime/Common Language Runtime (CLR) ships three different classes of JITters. The Main JIT compiler converts the MSIL code it to native code with out any optimizations. The JIT compiler takes the MSIL code and optimizes it. So this compiler requires lot of resources like, time to compile, larger memory footprint, etc. The PreJIT is based on the Main JIT and it works like the traditional compilers (compiles MSIL to native code during compilation time rather than runtime). This compiler is usually used at
the time of installation.
   No matter whatever language we used to develop the HelloWorld program, it’s a known fact that compiler’s are going to generate a MSIL format, once our code has been converted in to MSIL format, from MSIL format all the code that we write will be converted to native code in the same way whether if it is a VB.NET source or C# source.

Intermediate Language (IL)
  To support our discussion let us examine the IL code of HelloWorld program written using VB.NET and C#. To visualize the IL code Microsoft provides a disassembler tool through which you can easily see the IL code
   To use the tool, choose command prompt and type ILDASM->ILDASM dialog is shown-
> choose file open dialog and select the assembly
(make sure you set your path variable to point to the place where your ILDASM is available)
Figure showing disassembled HelloWorld program
The above window showing a tree displays the path of the assembly as the root node, manifest information and namespace information as the child node (if you do not specify the namespace for the class then class name will be shown instead of namespace).
Figure showing manifest information of helloworld program
The manifest information shows the dependent assemblies like mscorlib, Microsoft.VisualBasic and their versions and it self describes the HelloWorld assembly. Since we have a simple program, which does not contain any embedded resource, the manifest does not include any information on those.
Figure showing list of information present in the namespace
The above figure shows the list of information present within the namespace. In general the namespace contains the list of classes, structures, delegates, enums etc., In this case it shows the HelloWorld class which in turn contains the methods present in the class. It also shows the following information.
.. .class public auto ansi
The above figure shows that HelloWorld is derived from System.Object, System.Object is the base class in the .NET framework
.. .ctor : void()
The above figure shows the IL code of the constructor of HelloWorld Class, you can see that it in turn calls System.Object::.ctor(), which is the base class’s constructor
.. Main : void()
The above figure shows the IL code of the Main function, which is the entry point for that assembly. It also shows the method “System.Console::WriteLine” is called with the string “HelloWorld “ within the Main function

Compiler Options
  If you can recollect the statement we have used to compile the HelloWorld program is vbc HelloWorld.vb for Vb.NET and csc HelloWorld.cs for C# , in this we have used the default settings of the compiler. Let us spend sometime in compiling the same code with some important options of the vbc /csc compiler.
  In our program we have referred System.Dll assembly, in real life we would be application-referring lot of assemblies, in those cases the compiler should be intimated about the references. We can achieve this by the option mentioned below
  /reference:<file-list> - needs to be used to indicate the list of references used by the application, in short it can also be represented as “/r”. In our case it will be represented like this statement given below
vbc /reference:”System.dll” HelloWorld.vb for Vb.NET
csc /reference:”System.dll” HelloWorld.cs for C#.NET
   The compiler by default will produce a HelloWorld.exe, in case you want to create a module or a library, then you have to specify the target in the compiler. It can be done like this
vbc /target:library /reference:”System.dll” HelloWorld.vb => to generate a library
csc /target:library /reference:”System.dll” HelloWorld.cs => to generate a library
Executing the above line of statement in the command prompt will generate a HelloWorld.dll, in the same manner a module can be generated by applying this switch /target:module
In case if we would like to give a different name to the assembly file then the statement given below can be applied
vbc /target:exe /out:”SampleHelloWorld.exe” /reference:”System.dll”
HelloWorld.vb
csc /target:exe /out:”SampleHelloWorld.exe” /reference:”System.dll”
HelloWorld.cs
  In the above statement the switch /out:<filename> is used to give a different name to the
output assembly file.
   The above compiler statements what we have seen is for simple applications, let us assume we have an application which is a Win32 executable and it has got resources, which could be embedded or linked (More on resource file later). An embedded resource could be an image for the splash screen, in those cases the following compiler options will be used
/target:winexe - used to create a Win32 executable file
/linkresource:<resource file(s)> - used to link a resource file to the assembly
/resource:<resource file(s)> - used to embed a resource file to the assembly
/imports:<import list> - used to include the list of namespaces used by the assembly
For other compiler options refer .Net framework SDK documentation.

.NET Debugging
   Debugging is the most important feature of any programming language and Visual Studio .NET IDE provides this feature in an effective manner (but you can still do pretty good job with the .NET SDK alone). Application source code goes through two distinct steps before a user can run it. First, the source code is compiled to Microsoft Intermediate Language (MSIL) code using a .NET compiler. Then, at runtime, the MSIL code is compiled to native code. When we debug a .NET application, this process works in reverse. The debugger first maps the native code to the MSIL code. The MSIL code is then mapped back to the source code using the programmer's database (PDB) file. In order to debug an application, these two mappings must be available to the .NET runtime environment.
   To accomplish the mapping between the source code and the MSIL, use the/debug:pdbonly compiler switch to create the PDB file (Note: When building ASP.NET applications, specify the compilation setting debug="true" in the application’s Web.config file). The second mapping between the MSIL code and native code is accomplished by setting the JITTracking attribute in our assembly. By specifying the /debug compiler switch, the PDB file is created and the JITTracking attribute is enabled. When using this compiler switch, a debugger can be attached to an application loaded outside of the debugger.
   Once the required mappings exist, there are several means by which to debug our applications. We can use the integrated debugger within Visual Studio .NET, or, if we prefer, we can use DbgClr, a GUI-based debugger. There is also a command line debugger, CorDBG that is included in the .NET Framework SDK.

First VB.NET / C# program


  To start of with any language it’s always worth writing a simple program, which actually does nothing but displays a “HelloWorld” string in the screen. Taking this simple program we will try to figure out how .NET framework delivers a successful HelloWorld.exe. Well to write such a complex program we will go for our favorite editor, the choice is unanimous, it’s “Notepad”.

First VB.NET Program
Figure showing HelloWorld program written using VB.NET
'This is the famous HelloWorld Program written using VB.NET
Namespace HelloWorldSample
'Definition of the Class
Public Class HelloWorld
'entry point method for the Class
Public Shared Sub Main()
System.Console.WriteLine("HelloWorld")
End Sub
'end of Class Declaration
End Class
'end of the Class Module
'end of namespace
End Namespace

This is how it goes in your favorite editor ‘Notepad’
   Now let us spend sometime in examining the HelloWorld program to find out what’s new in writing code through any .NET language.
   The lines in the program that starts with a ‘(single quote) are comment entries like in other programming languages which are excluded in the compilation process. Like VB the way in which comment entries are represented remains the same in VB.NET.
Namespace HelloWorldSample - The keyword “Namespace” is new to some programmers who are not familiar with C++.
‘Namespace’ – a keyword in .NET is used to avoid name collisions i.e. For example, you develop a library which has a class named “File” and you use some other library which also has a class named “File”, in those cases there are chances of name collision. To avoid this you can give a namespace name for your class, which should be meaningful. It is always better to follow the syntax (MS Recommended) given below while giving
names for your namespaces
CompanyName.TechnologyName
However the hierarchy can be extended based on the implementation of the classes in the library.
Public Class HelloWorld - This is the class declaration in VB.NET; the interesting thing for VB developers is that VB.NET is a fully object-oriented language (so everything is a Class here) . The class always ends with an “End Class”.
‘Public’ - is the modifier to determine the scope of the class (for other modifiers refer .NET framework SDK documentation or later parts of this tutorial). HelloWorld is the class name given for the class. Consumers of the class will be accessing through this name only
Public Shared Sub Main () - This is called as the entry point function because the runtime after loading your applications searches for an entry point from which the actual execution starts. C/C++ programmers will find this method very familiar (VB Programmers remember Sub Main). All Applications (exe) must have a definition for the Main Method. Try removing the Main method from your application and the compiler will complain that "No Start Point Defined". This means that the Main Method is the starting point of any application, in other words When you execute your Application
"Main" method is called first automatically.
'Public' - This is the Access modifier for the Method. Since the Main method should be accessible to everyone in order for the .NET Runtime to be able to call it automatically it is always defined as public.
'Shared' - indicates that the method is a Class Method. Hence it can be called without making an instance of the class first.
Now its time to compile and execute this complex program. To compile the above piece of code you can use VB.NET compiler. To run the VB.NET compiler make sure you set your path variable to point to the place where your VB.NET compiler is available. (To set a new value in the path variable, go to control panel and double click System icon, then choose advanced tab and click Environment Variables button to add or edit the environmental variables)
Figure shows compilation of the HelloWorld program for VB.NET
The compiler used here is “vbc”, which is a visual basic .net compiler accepts the source file “HelloWorld.vb” compiles the same to produce a program that’s not true executable  instead it generates something called assembly. Here the VB.NET compiler produces a Managed Code/Intermediate Language (MSIL) format that uses instructions which are CPU-independent.

First C#.NET Program
/* This is the famous helloworld program written using C#.NET */
/* Indicates that the code is referring System Namespace to access the
functionality’s of System.dll */
using System;
// Namespace name given for the class
namespace HelloWorldSample
{
//Definition of the class
public class HelloWorld
{
// Entry point method for the class
public static void Main()
{
//Displaying helloworld in the screen
System.Console.WriteLine("HelloWorld");
}
//end of the class declaration
}
//end of the namespace
}
Figure showing HelloWorld program written using C#.NET in Notepad
The lines in the program that starts with a // and /*….*/ (comment blocks) are comment entries like in other programming languages which are excluded in the compilation process. For C or C++ programmers the C# style of coding sounds great because it almost follows the same style.
namespace HelloWorldSample - The keyword “namespace” is new to some programmers who are not familiar with C++.
‘namespace’ – a keyword in .NET is used to avoid name collisions i.e. For example, you develop a library which has a class named “File” and you use some other library which also has a class named “File”, in those cases there are chances of name collision. To avoid this you can give a namespace name for your class, which should be meaningful. It is always better to follow the syntax (MS Recommended) given below while giving
names for your namespaces
CompanyName.TechnologyName
However the hierarchy can be extended based on the implementation of the classes in the library.
public class HelloWorld - This is the class declaration in C#.NET; the interesting thing for C++ or Java developers is that they can apply the OOPS concepts that are supported by C#.NET . The class always ends with an “End Class”.
‘public’ - is the modifier to determine the scope of the class (for other modifiers refer .NET framework SDK documentation or later parts of this tutorial). HelloWorld is the class name given for the class. Consumers of the class will be accessing through this name only.
public static void Main () - This is called as the entry point function because the runtime after loading your applications searches for an entry point from which the actual execution starts. C/C++ programmers will find this method very familiar (VB Programmers remember Sub Main). All Applications (exe) must have a definition for the Main Method. Try removing the Main method from your application and the compiler will complain that "No Start Point Defined". This means that the Main Method is the starting point of any application, in other words When you execute your Application "Main" method is called first automatically.
'public' - This is the Access modifier for the Method. Since the Main method should be accessible to everyone in order for the .NET Runtime to be able to call it automatically it is always defined as public.
'static' - indicates that the method is a Class Method. Hence it can be called without making an instance of the class first.
‘void’ – indicates the return type of the Main function, here in this case the Main function returns nothing so it is mentioned as void, for functions that returns value should have appropriate type such as long, string etc.,
   Now its time to compile and execute this complex program. To compile the above piece of code you can use C# compiler. To run the C# compiler make sure you set your path variable to point to the place where your C# compiler is available. (To set a new value in the path variable, go to control panel and double click System icon, then choose advanced tab and click Environment Variables button to add or edit the environmental variables)
   Figure shows compilation of the HelloWorld program using C# compiler
  The compiler used here is “csc”, which is a visual basic .net compiler accepts the source file HelloWorld.cs” compiles the same to produce a program that’s not true executable, instead it generates something called assembly.

Assembly
An assembly is a grouping of files deployed as a single file. An assembly almost always consists of at least two files: the executable and the manifest. The manifest is a list of all the files that exist inside the assembly. The executable content inside the assembly is referred to individually as a module. Conceptually, modules correspond to DLLs or EXEs; each module contains metadata, in addition to the metadata of its parent assembly. The assembly format is an enhanced version of the current Portable Executable (PE)
format (your normal Windows .EXE file format).

Manifest
Manifest is considered as the integral part of every assembly that renders the assembly self-describing. The assembly manifest contains the assembly's metadata and it also establishes the assembly identity, specifies the files that make up the assembly implementation, specifies the types and resources that make up the assembly, itemizes the compile-time dependencies on other assemblies, and specifies the set of permissions required for the assembly to run properly.

Metadata
The standard PE header comes at the beginning of the file. Inside the file is the CLR header, followed by the data required to load the code into its process space—referred to as metadata. It describes to the execution engine how the module should be loaded, what additional files it needs, how to load those additional files, and how to interact with COM and the .NET runtime.
Metadata also describes the methods, interfaces, and classes contained in the module or assembly. The information the metadata provides allows the JIT compiler to compile and run the module. The metadata section exposes much of your application's internals and eases the transition from disassembled IL to useful code.

Introduction


  We all know that there have been disparities between different languages such as VB, VC++ and developers, who code program through these languages. The disparity lies in terms of language features, performance, and flexibility in developing any piece of program. Well it’s a known fact that, at the end, what matters is how efficiently your  programs run on the client machine, no matter what language you use. Earlier this was driven by compilers, which were used to compile the code written using these languages to make it native code (processor specific).
   With the release .NET framework Microsoft has driven out the disparities in such a way that no matter whatever .NET language you use to develop .NET applications, still the end result will be determined by .NET framework runtime and not by the language compilers as it was happening earlier. In this tutorial we will identify some of the key elements of the .NET framework through a simple program and concentrate on how
.NET framework Runtime addresses platform or processor specific code issues to produce optimized code, which is native to the processor and to know how the framework helps in managing code effectively.

Common Language Runtime (CLR)
   The primary function of a runtime is to support and manage the execution of code targeted for a language or a platform. For example, the Microsoft VC++ requires the msvcrt60.dll that contains its core support functionality. Even languages like Java have a run time, in the form of  Java Virtual Machine.
   The .Net platform also comes with a runtime that is officially called as the Common Language Runtime or simply the CLR. The CLR is designed to support a variety of different types of applications, from Web server applications to applications with traditional rich Windows user interface. Though the role of the CLR is similar to its counterparts in other languages or platforms, there are some key differences that make it one of the major features of the .NET platform. Here are the key differences between the .NET CLR and runtime of other languages:
• It is a common runtime for all languages targeting the .NET platform.
• It acts as an agent that manages code at execution time and also provides core services such as memory management, thread management and remoting.
• It enforces strict type safety and other forms of code accuracy that ensure security and robustness.
• It is responsible for enabling and facilitating the Common Type System. The Common Type System allows classes that are written in any .NET language to interoperate with—even inherit from, with overrides—classes written in any language. So your COBOL.NET program can interoperate with your C#, VB.NET,
Eiffel.NET and with any other .NET language programs.
• It offers a mechanism for cross-language exception handling.
• It provides a more elegant way for resolving the versioning issues (also referred to as the Dll Hell in our classic COM).
• It provides a simplified model for component interaction.

     Code that targets the runtime is known as managed code, while code that does not target the runtime is known as unmanaged code. Managed code requires a runtime host to start it. The responsibility of the runtime host is to load the runtime into a process, create the application domains (we’ll look at this in detail later) within the process, and loads the user code into the application domains. While we can write our own runtime hosts using the set of APIs provided by Microsoft, the .NET platform by default ships with runtime
hosts that include the following.
ASP.NET – Loads the runtime into the process that is to handle the Web request. ASP.NET also creates an application domain for each Web application that will run on a Web server.
Microsoft Internet Explorer – Creates application domains in which to run managed controls. The .NET Framework supports the download and execution of browser-based controls. The runtime interfaces with the extensibility mechanism of Microsoft Internet Explorer through a mime filter to create application domains in which to run the managed controls. By default, one application domain is created for each Web site.
Shell executables – Invokes runtime hosting code to transfer control to the runtime each time an executable is launched from the shell.
   Now that you have understood conceptually the key features of the CLR in .NET framework, you can begin to look into the physical implementation and execution of code in the CLR.